Blender V5.3
grease_pencil_io_import_svg.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2024 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
5#include "BKE_attribute.hh"
6#include "BKE_main.hh"
7#include "BLI_assert.hh"
8#include "BLI_bounds.hh"
9#include "BLI_color_types.hh"
10#include "BLI_math_color_c.hh"
12#include "BLI_math_matrix.hh"
14#include "BLI_math_vector.hh"
15#include "BLI_offset_indices.hh"
16#include "BLI_path_utils.hh"
17#include "BLI_string.hh"
18
19#include "BKE_curves.hh"
20#include "BKE_grease_pencil.hh"
21#include "BKE_report.hh"
22
24#include "DNA_space_types.h"
26
27#include "ED_grease_pencil.hh"
28
30
31#include "nanosvg.h"
32
33#include <fmt/core.h>
34#include <fmt/format.h>
35
36namespace blender {
37
41
45
46namespace io::grease_pencil {
47
49 public:
51
52 bool read(StringRefNull filepath);
53};
54
55static std::string get_layer_id(const NSVGshape &shape, const int prefix)
56{
57 return (shape.id_parent[0] == '\0') ? fmt::format("Layer_{:03d}", prefix) :
58 fmt::format("{:s}", shape.id_parent);
59}
60
61/* Unpack internal NanoSVG color. */
63{
64 const uchar4 rgb_u = {uint8_t(((pack) >> 0) & 0xFF),
65 uint8_t(((pack) >> 8) & 0xFF),
66 uint8_t(((pack) >> 16) & 0xFF),
67 uint8_t(((pack) >> 24) & 0xFF)};
68 const float4 rgb_f = {float(rgb_u[0]) / 255.0f,
69 float(rgb_u[1]) / 255.0f,
70 float(rgb_u[2]) / 255.0f,
71 float(rgb_u[3]) / 255.0f};
72
75 return color;
76}
77
78/* Simple approximation of a gradient by a single color. */
79static ColorGeometry4f average_gradient_color(const NSVGgradient &svg_gradient)
80{
81 const Span<NSVGgradientStop> stops = {svg_gradient.stops, svg_gradient.nstops};
82
83 float4 avg_color = float4(0, 0, 0, 0);
84 if (stops.is_empty()) {
85 return ColorGeometry4f(avg_color);
86 }
87
88 for (const int i : stops.index_range()) {
89 avg_color += float4(unpack_nano_color(stops[i].color));
90 }
91 avg_color /= stops.size();
92
93 return ColorGeometry4f(avg_color);
94}
95
96/* TODO Gradients are not yet supported (will output magenta placeholder color).
97 * This is because gradients for fill materials in particular can only be defined by materials.
98 * Since each path can have a unique gradient it potentially requires a material per curve.
99 * Stroke gradients could be baked into vertex colors. */
100static ColorGeometry4f convert_svg_color(const NSVGpaint &svg_paint)
101{
102 switch (NSVGpaintType(svg_paint.type)) {
103 case NSVG_PAINT_UNDEF:
104 return ColorGeometry4f(1, 0, 1, 1);
105 case NSVG_PAINT_NONE:
106 return ColorGeometry4f(0, 0, 0, 1);
107 case NSVG_PAINT_COLOR:
108 return unpack_nano_color(svg_paint.color);
109 case NSVG_PAINT_LINEAR_GRADIENT:
110 return average_gradient_color(*svg_paint.gradient);
111 case NSVG_PAINT_RADIAL_GRADIENT:
112 return average_gradient_color(*svg_paint.gradient);
113
114 default:
116 return ColorGeometry4f(0, 0, 0, 0);
117 }
118}
119
120/* Make room for curves and points from the SVG shape.
121 * Returns the index range of newly added curves. */
123{
124 const int old_curves_num = curves.curves_num();
125 const int old_points_num = curves.points_num();
126 const Span<int> old_offsets = curves.offsets();
127
128 /* Count curves and points. */
129 Vector<int> new_curve_offsets;
130 for (NSVGpath *path = shape.paths; path; path = path->next) {
131 if (path->npts == 0) {
132 continue;
133 }
134 BLI_assert(path->npts >= 1 && path->npts == int(path->npts / 3) * 3 + 1);
135 /* nanosvg converts everything to bezier curves, points come in triplets. Round up to the
136 * next full integer, since there is one point without handles (3*n+1 points in total). */
137 int point_num = (path->npts + 2) / 3;
138
139 /* 2D vectors in triplets: [control point, left handle, right handle]. */
140 const Span<float2> svg_path_data = Span<float>(path->pts, 2 * path->npts).cast<float2>();
141
142 /* Extra points can be at the end of the path, so loop through until they are gone. */
143 const float2 pos_first = svg_path_data.first();
144 float2 pos_last = svg_path_data[(point_num - 1) * 3];
145
146 while (math::almost_equal_relative(pos_first, pos_last, 1e-6f) && point_num > 1) {
147 point_num--;
148 pos_last = svg_path_data[(point_num - 1) * 3];
149 }
150
151 new_curve_offsets.append(point_num);
152 }
153 if (new_curve_offsets.is_empty()) {
154 return {};
155 }
156 new_curve_offsets.append(0);
158 new_curve_offsets, old_points_num);
159
160 const IndexRange new_curves_range = {old_curves_num, new_points_by_curve.size()};
161 const int curves_num = new_curves_range.one_after_last();
162 const int points_num = new_points_by_curve.total_size() + old_points_num;
163
164 Array<int> new_offsets(curves_num + 1);
165 if (old_curves_num > 0) {
166 new_offsets.as_mutable_span().slice(0, old_curves_num).copy_from(old_offsets.drop_back(1));
167 }
168 new_offsets.as_mutable_span()
169 .slice(old_curves_num, new_curve_offsets.size())
170 .copy_from(new_curve_offsets);
171
172 curves.resize(points_num, curves_num);
173 curves.offsets_for_write().copy_from(new_offsets);
174
175 curves.tag_topology_changed();
176
177 return new_curves_range;
178}
179
181 const NSVGshape &shape,
182 const IndexRange curves_range,
183 const float4x4 &transform,
184 const int shape_index,
185 const int material_index)
186{
187 /* Path width is twice the radius. */
188 const float path_width_scale = 0.5f * math::average(math::to_scale(transform));
189 const OffsetIndices points_by_curve = curves.points_by_curve();
190
191 /* nanosvg converts everything to Bezier curves. */
192 curves.curve_types_for_write().slice(curves_range).fill(CURVE_TYPE_BEZIER);
193 curves.update_curve_types();
194
195 bke::MutableAttributeAccessor attributes = curves.attributes_for_write();
197 "material_index", bke::AttrDomain::Curve);
198 MutableSpan<bool> cyclic = curves.cyclic_for_write();
199
201 "fill_color", bke::AttrDomain::Curve);
202 bke::SpanAttributeWriter<float> fill_opacities = attributes.lookup_or_add_for_write_span<float>(
203 "fill_opacity", bke::AttrDomain::Curve);
204
205 MutableSpan<float3> positions = curves.positions_for_write();
206 MutableSpan<float3> handle_positions_left = curves.handle_positions_left_for_write();
207 MutableSpan<float3> handle_positions_right = curves.handle_positions_right_for_write();
208 MutableSpan<int8_t> handle_types_left = curves.handle_types_left_for_write();
209 MutableSpan<int8_t> handle_types_right = curves.handle_types_right_for_write();
211 "radius", bke::AttrDomain::Point);
213 attributes.lookup_or_add_for_write_span<ColorGeometry4f>("vertex_color",
215 bke::SpanAttributeWriter<float> point_opacities = attributes.lookup_or_add_for_write_span<float>(
216 "opacity", bke::AttrDomain::Point);
217
218 materials.span.slice(curves_range).fill(material_index);
219 const ColorGeometry4f shape_color = convert_svg_color(shape.fill);
220 if (fill_colors) {
221 fill_colors.span.slice(curves_range).fill(shape_color);
222 }
223 if (fill_opacities) {
224 fill_opacities.span.slice(curves_range).fill(shape_color.a);
225 }
226
227 const bool use_stroke = bool(shape.stroke.type);
228 const bool use_fill = bool(shape.fill.type);
229 /* Ensure stroke/fill attributes exist if non-zero values need to be written. */
230 if (!use_stroke) {
231 attributes.add<bool>("hide_stroke", bke::AttrDomain::Curve, bke::AttributeInitDefaultValue());
232 }
233 if (use_fill) {
234 attributes.add<int>("fill_id", bke::AttrDomain::Curve, bke::AttributeInitDefaultValue());
235 }
236
237 bke::SpanAttributeWriter<bool> hide_stroke = attributes.lookup_for_write_span<bool>(
238 "hide_stroke");
239 bke::SpanAttributeWriter<int> fill_ids = attributes.lookup_for_write_span<int>("fill_id");
240 if (hide_stroke) {
241 hide_stroke.span.slice(curves_range).fill(!use_stroke);
242 hide_stroke.finish();
243 }
244 if (fill_ids) {
245 fill_ids.span.slice(curves_range).fill(use_fill ? shape_index + 1 : 0);
246 fill_ids.finish();
247 }
248
249 int curve_index = curves_range.start();
250 for (NSVGpath *path = shape.paths; path; path = path->next) {
251 if (path->npts == 0) {
252 continue;
253 }
254 const IndexRange points = points_by_curve[curve_index];
255
256 /* Close the curve if any points have been removed. An unmodified non-closed curve will have 3
257 * positions for every point (Center, Left, Right) except for the 2 ends which each remove 1
258 * (either Left or Right for the Start and End) */
259 const bool closed = bool(path->closed) || (points.size() * 3 - 2 != path->npts);
260 cyclic[curve_index] = closed;
261
262 /* 2D vectors in triplets: [control point, left handle, right handle]. */
263 const Span<float2> svg_path_data = Span<float>(path->pts, 2 * path->npts).cast<float2>();
264 const ColorGeometry4f point_color = convert_svg_color(shape.stroke);
265
266 /* Handle first point separately. */
267 {
268 const float2 pos_center = svg_path_data.first();
269 const float2 pos_handle_left = closed ? svg_path_data[points.size() * 3 - 1] : pos_center;
270
271 const float2 pos_handle_right = svg_path_data[1];
272 positions[points.first()] = math::transform_point(transform, float3(pos_center, 0.0f));
273 handle_positions_left[points.first()] = math::transform_point(transform,
274 float3(pos_handle_left, 0.0f));
275 handle_positions_right[points.first()] = math::transform_point(
276 transform, float3(pos_handle_right, 0.0f));
277 handle_types_left[points.first()] = BEZIER_HANDLE_FREE;
278 handle_types_right[points.first()] = BEZIER_HANDLE_FREE;
279
280 radii.span[points.first()] = shape.strokeWidth * path_width_scale;
281
282 if (vertex_colors) {
283 vertex_colors.span[points.first()] = point_color;
284 }
285 if (point_opacities) {
286 point_opacities.span[points.first()] = point_color.a;
287 }
288 }
289
290 for (const int i : points.index_range().drop_front(1)) {
291 const int point_index = points[i];
292 const float2 pos_center = svg_path_data[i * 3];
293 float2 pos_handle_left = svg_path_data[i * 3 - 1];
294 const float2 pos_handle_right = (i < points.size() - 1 + closed) ? svg_path_data[i * 3 + 1] :
295 pos_center;
296 positions[point_index] = math::transform_point(transform, float3(pos_center, 0.0f));
297 handle_positions_left[point_index] = math::transform_point(transform,
298 float3(pos_handle_left, 0.0f));
299 handle_positions_right[point_index] = math::transform_point(transform,
300 float3(pos_handle_right, 0.0f));
301 handle_types_left[point_index] = BEZIER_HANDLE_FREE;
302 handle_types_right[point_index] = BEZIER_HANDLE_FREE;
303
304 radii.span[point_index] = shape.strokeWidth * path_width_scale;
305
306 if (vertex_colors) {
307 vertex_colors.span[point_index] = point_color;
308 }
309 if (point_opacities) {
310 point_opacities.span[point_index] = point_color.a;
311 }
312 }
313
314 ++curve_index;
315 }
316
317 materials.finish();
318 fill_colors.finish();
319 fill_opacities.finish();
320 radii.finish();
321 vertex_colors.finish();
322 point_opacities.finish();
323 curves.tag_positions_changed();
324 curves.tag_radii_changed();
325}
326
328{
329 const std::optional<Bounds<float3>> bounds = [&]() {
330 std::optional<Bounds<float3>> bounds;
331 for (GreasePencilDrawingBase *drawing_base : grease_pencil.drawings()) {
332 if (drawing_base->type != GP_DRAWING) {
333 continue;
334 }
335 Drawing &drawing = reinterpret_cast<GreasePencilDrawing *>(drawing_base)->wrap();
337 }
338 return bounds;
339 }();
340 if (!bounds) {
341 return;
342 }
343 const float3 offset = -bounds->center();
344
345 for (GreasePencilDrawingBase *drawing_base : grease_pencil.drawings()) {
346 if (drawing_base->type != GP_DRAWING) {
347 continue;
348 }
349 Drawing &drawing = reinterpret_cast<GreasePencilDrawing *>(drawing_base)->wrap();
350 drawing.strokes_for_write().translate(offset);
351 drawing.tag_positions_changed();
352 }
353}
354
356{
357 /* Fixed SVG unit for scaling. */
358 constexpr const char *svg_units = "mm";
359 constexpr float svg_dpi = 96.0f;
360
361 char abs_filepath[FILE_MAX];
362 STRNCPY(abs_filepath, filepath.c_str());
364
365 NSVGimage *svg_data = nullptr;
366 svg_data = nsvgParseFromFile(abs_filepath, svg_units, svg_dpi);
367 if (svg_data == nullptr) {
368 BKE_report(context_.reports, RPT_ERROR, "Could not open SVG");
369 return false;
370 }
371
372 /* Create grease pencil object. */
373 char filename[FILE_MAX];
376 if (object_ == nullptr) {
377 BKE_report(context_.reports, RPT_ERROR, "Unable to create new object");
378 nsvgDelete(svg_data);
379 return false;
380 }
381 GreasePencil &grease_pencil = *id_cast<GreasePencil *>(object_->data);
382
383 /* The three possible materials that might be created. */
384 std::optional<int> mat_index_stroke;
385 std::optional<int> mat_index_fill;
386 std::optional<int> mat_index_both;
387
388 const float scene_unit_scale = (context_.scene->unit.system != USER_UNIT_NONE &&
391 1.0f;
392 /* Overall scale for SVG coordinates in millimeters. */
393 const float svg_scale = 0.001f / scene_unit_scale * params_.scale;
394 /* Grease pencil is rotated 90 degrees in X axis by default. */
397
398 /* True if any shape has a color gradient, which are not fully supported. */
399 bool has_color_gradient = false;
400
401 /* Loop all shapes. */
402 std::string prv_id = "*";
403 int prefix = 0;
404 int shape_index = 0;
405 for (NSVGshape *shape = svg_data->shapes; shape; shape = shape->next) {
406 std::string layer_id = get_layer_id(*shape, prefix);
407 if (prv_id != layer_id) {
408 prefix++;
409 layer_id = get_layer_id(*shape, prefix);
410 prv_id = layer_id;
411 }
412
413 /* Check if the layer exist and create if needed. */
414 Layer &layer = [&]() -> Layer & {
415 TreeNode *layer_node = grease_pencil.find_node_by_name(layer_id);
416 if (layer_node && layer_node->is_layer()) {
417 return layer_node->as_layer();
418 }
419
420 Layer &layer = grease_pencil.add_layer(layer_id);
421 layer.as_node().flag |= GP_LAYER_TREE_NODE_USE_LIGHTS;
422 return layer;
423 }();
424
425 /* Check frame. */
426 Drawing *drawing = grease_pencil.get_drawing_at(layer, params_.frame_number);
427 if (drawing == nullptr) {
428 drawing = grease_pencil.insert_frame(layer, params_.frame_number);
429 if (!drawing) {
430 continue;
431 }
432 }
433
434 /* Find or create materials. */
435 const bool is_fill = bool(shape->fill.type);
436 const bool is_stroke = bool(shape->stroke.type) || !is_fill;
437 int material_index;
438 if (is_stroke && is_fill) {
439 if (!mat_index_both) {
440 mat_index_both = create_material("Both");
441 }
442
443 material_index = *mat_index_both;
444 }
445 else if (is_stroke) {
446 if (!mat_index_stroke) {
447 mat_index_stroke = create_material("Stroke");
448 }
449
450 material_index = *mat_index_stroke;
451 }
452 else if (is_fill) {
453 if (!mat_index_fill) {
454 mat_index_fill = create_material("Fill");
455 }
456
457 material_index = *mat_index_fill;
458 }
459
460 if (ELEM(shape->fill.type, NSVG_PAINT_LINEAR_GRADIENT, NSVG_PAINT_RADIAL_GRADIENT)) {
461 has_color_gradient = true;
462 }
463
465 const IndexRange new_curves_range = extend_curves_geometry(curves, *shape);
466 if (new_curves_range.is_empty()) {
467 continue;
468 }
469
471 curves, *shape, new_curves_range, transform, shape_index, material_index);
472 drawing->strokes_for_write() = std::move(curves);
473
474 shape_index++;
475 }
476
477 /* Free SVG memory. */
478 nsvgDelete(svg_data);
479
480 /* Calculate bounding box and move all points to new origin center. */
483 }
484
485 if (has_color_gradient) {
488 "SVG has gradients, Grease Pencil color will be approximated");
489 }
490
491 return true;
492}
493
494bool import_svg(const IOContext &context, const ImportParams &params, StringRefNull filepath)
495{
496 SVGImporter importer(context, params);
497 return importer.read(filepath);
498}
499
500} // namespace io::grease_pencil
501
502} // namespace blender
Low-level operations for curves.
Low-level operations for grease pencil.
#define DEG2RAD(_deg)
#define FILE_MAX
#define BLI_assert_unreachable()
#define ELEM(...)
MutableSpan< T > as_mutable_span()
Definition BLI_array.hh:259
ChannelStorageType a
constexpr int64_t first() const
constexpr int64_t one_after_last() const
constexpr int64_t size() const
constexpr bool is_empty() const
constexpr int64_t start() const
constexpr IndexRange index_range() const
constexpr IndexRange drop_front(int64_t n) const
Span< NewT > constexpr cast() const
Definition BLI_span.hh:422
constexpr Span drop_back(int64_t n) const
Definition BLI_span.hh:186
constexpr const T & first() const
Definition BLI_span.hh:319
constexpr int64_t size() const
Definition BLI_span.hh:256
constexpr IndexRange index_range() const
Definition BLI_span.hh:405
constexpr bool is_empty() const
Definition BLI_span.hh:264
constexpr const char * c_str() const
int64_t size() const
void append(const T &value)
bool is_empty() const
std::optional< Bounds< float3 > > bounds_min_max(bool use_radius=true) const
void translate(const float3 &translation)
bool add(const StringRef name, const AttrDomain domain, const AttrType data_type, const AttributeInit &initializer)
GSpanAttributeWriter lookup_or_add_for_write_span(StringRef name, AttrDomain domain, AttrType data_type, const AttributeInit &initializer=AttributeInitDefaultValue())
GSpanAttributeWriter lookup_for_write_span(StringRef name)
bke::CurvesGeometry & strokes_for_write()
const bke::CurvesGeometry & strokes() const
GreasePencilImporter(const IOContext &context, const ImportParams &params)
GreasePencilImporter(const IOContext &context, const ImportParams &params)
#define layer
Bounds< T > merge(const Bounds< T > &a, const Bounds< T > &b)
Definition BLI_bounds.hh:27
std::string filename(const std::string_view &str, size_t pos)
BLI_INLINE Texture * wrap(MTLTexture *texture)
static void shift_to_bounds_center(GreasePencil &grease_pencil)
static ColorGeometry4f average_gradient_color(const NSVGgradient &svg_gradient)
bool import_svg(const IOContext &context, const ImportParams &params, StringRefNull filepath)
static ColorGeometry4f unpack_nano_color(const uint pack)
static ColorGeometry4f convert_svg_color(const NSVGpaint &svg_paint)
static IndexRange extend_curves_geometry(bke::CurvesGeometry &curves, const NSVGshape &shape)
static std::string get_layer_id(const NSVGshape &shape, const int prefix)
static void shape_attributes_to_curves(bke::CurvesGeometry &curves, const NSVGshape &shape, const IndexRange curves_range, const float4x4 &transform, const int shape_index, const int material_index)
MatBase< T, NumCol, NumRow > scale(const MatBase< T, NumCol, NumRow > &mat, const VectorT &scale)
EulerXYZBase< float > EulerXYZ
T average(const VecBase< T, Size > &a)
VecBase< T, 3 > to_scale(const MatBase< T, NumCol, NumRow > &mat)
bool almost_equal_relative(const VecBase< T, Size > &a, const VecBase< T, Size > &b, const T &epsilon_factor)
MatT from_rotation(const RotationT &rotation)
VecBase< T, 3 > transform_point(const CartesianBasis &basis, const VecBase< T, 3 > &v)
OffsetIndices< int > accumulate_counts_to_offsets(MutableSpan< int > counts_to_offsets, int start_offset=0)
BMesh Iterators.
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
VecBase< uint8_t, 4 > uchar4
char * STRNCPY(char(&dst)[N], const char *src)
@ RPT_WARNING
Definition BKE_report.hh:40
unsigned int uint
Definition BKE_text.h:55
bool BLI_path_abs(char path[FILE_MAX], const char *basepath) ATTR_NONNULL(1
MINLINE void srgb_to_linearrgb_v4(float linear[4], const float srgb[4])
const char * BKE_main_blendfile_path_from_global()
Definition main.cc:1063
MatBase< float, 4, 4 > float4x4
VecBase< float, 4 > float4
VecBase< float, 2 > float2
void BKE_report(ReportList *reports, eReportType type, const char *message)
Definition report.cc:162
unsigned char uint8_t
Definition BKE_text.h:79
constexpr size_t ARRAY_SIZE(const T(&arg)[N]) noexcept
void void void BLI_path_split_file_part(const char *filepath, char *file, size_t file_maxncpy) ATTR_NONNULL(1
ColorSceneLinear4f< eAlpha::Premultiplied > ColorGeometry4f
VecBase< float, 3 > float3
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
struct UnitSettings unit