Blender V5.3
bpy_utils_units.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
11
12/* Future-proof, See https://docs.python.org/3/c-api/arg.html#strings-and-buffers */
13#define PY_SSIZE_T_CLEAN
14
15#include <Python.h>
16#include <structmember.h>
17
18#include "BLI_string.hh"
19#include "BLI_utildefines.hh"
20
21#include "bpy_utils_units.hh"
22
24#include "../generic/python_compat.hh" /* IWYU pragma: keep. */
25
26#include "BKE_unit.hh"
27
28namespace blender {
29
30/***** C-defined systems and types *****/
31
32static PyTypeObject BPyUnitsSystemsType;
33static PyTypeObject BPyUnitsCategoriesType;
34
35/* XXX: Maybe better as `extern` of `BKE_unit.hh` ? */
36static const char *bpyunits_usystem_items[] = {
37 "NONE",
38 "METRIC",
39 "IMPERIAL",
40 nullptr,
41};
42
43static const char *bpyunits_ucategories_items[] = {
44 "NONE",
45 "LENGTH",
46 "AREA",
47 "VOLUME",
48 "MASS",
49 "ROTATION",
50 "TIME",
51 "TIME_ABSOLUTE",
52 "VELOCITY",
53 "ACCELERATION",
54 "CAMERA",
55 "POWER",
56 "TEMPERATURE",
57 "WAVELENGTH",
58 "COLOR_TEMPERATURE",
59 "FREQUENCY",
60 nullptr,
61};
62
65 "`bpyunits_ucategories_items` should match `B_UNIT_` enum items in `BKE_units.h`")
66
67
72static PyStructSequence_Field bpyunits_systems_fields[ARRAY_SIZE(bpyunits_usystem_items)];
74
75static PyStructSequence_Desc bpyunits_systems_desc = {
76 /*name*/ "bpy.utils.units.systems",
77 /*doc*/ "This named tuple contains all predefined unit systems",
78 /*fields*/ bpyunits_systems_fields,
79 /*n_in_sequence*/ ARRAY_SIZE(bpyunits_systems_fields) - 1,
80};
81static PyStructSequence_Desc bpyunits_categories_desc = {
82 /*name*/ "bpy.utils.units.categories",
83 /*doc*/ "This named tuple contains all predefined unit names",
85 /*n_in_sequence*/ ARRAY_SIZE(bpyunits_categories_fields) - 1,
86};
87
91static PyObject *py_structseq_from_strings(PyTypeObject *py_type,
92 PyStructSequence_Desc *py_sseq_desc,
93 const char **str_items)
94{
95 PyObject *py_struct_seq;
96 int pos = 0;
97
98 const char **str_iter;
99 PyStructSequence_Field *desc;
100
101 /* Initialize array. */
102 /* We really populate the contexts' fields here! */
103 for (str_iter = str_items, desc = py_sseq_desc->fields; *str_iter; str_iter++, desc++) {
104 desc->name = const_cast<char *>(*str_iter);
105 desc->doc = nullptr;
106 }
107 /* end sentinel */
108 desc->name = desc->doc = nullptr;
109
110 PyStructSequence_InitType(py_type, py_sseq_desc);
111
112 /* Initialize the Python type. */
113 py_struct_seq = PyStructSequence_New(py_type);
114 BLI_assert(py_struct_seq != nullptr);
115
116 for (str_iter = str_items; *str_iter; str_iter++) {
117 PyStructSequence_SET_ITEM(py_struct_seq, pos++, PyUnicode_FromString(*str_iter));
118 }
119
120 return py_struct_seq;
121}
122
123static bool bpyunits_validate(const char *usys_str, const char *ucat_str, int *r_usys, int *r_ucat)
124{
126 if (*r_usys < 0) {
127 PyErr_Format(PyExc_ValueError, "Unknown unit system specified: %.200s.", usys_str);
128 return false;
129 }
130
132 if (*r_ucat < 0) {
133 PyErr_Format(PyExc_ValueError, "Unknown unit category specified: %.200s.", ucat_str);
134 return false;
135 }
136
137 if (!BKE_unit_is_valid(*r_usys, *r_ucat)) {
138 PyErr_Format(PyExc_ValueError,
139 "%.200s / %.200s unit system/category combination is not valid.",
140 usys_str,
141 ucat_str);
142 return false;
143 }
144
145 return true;
146}
147
149 /* Wrap. */
150 bpyunits_to_value_doc,
151 ".. function:: to_value(unit_system, unit_category, str_input, *, str_ref_unit=None)\n"
152 "\n"
153 " Convert a given input string into a float value.\n"
154 "\n"
155 " :param unit_system: The unit system, from :attr:`bpy.utils.units.systems`.\n"
156 " :type unit_system: str\n"
157 " :param unit_category: The category of data we are converting (length, area, rotation, "
158 "etc.),\n"
159 " from :attr:`bpy.utils.units.categories`.\n"
160 " :type unit_category: str\n"
161 " :param str_input: The string to convert to a float value.\n"
162 " :type str_input: str\n"
163 " :param str_ref_unit: A reference string from which to extract a default unit, if none is "
164 "found in ``str_input``.\n"
165 " :type str_ref_unit: str | None\n"
166 " :return: The converted/interpreted value.\n"
167 " :rtype: float\n"
168 " :raises ValueError: if conversion fails to generate a valid Python float value.\n");
169static PyObject *bpyunits_to_value(PyObject * /*self*/, PyObject *args, PyObject *kw)
170{
171 char *usys_str = nullptr, *ucat_str = nullptr, *inpt = nullptr, *uref = nullptr;
172 const float scale = 1.0f;
173
174 char *str;
175 Py_ssize_t str_len;
176 double result;
177 int usys, ucat;
178 PyObject *ret;
179
180 static const char *_keywords[] = {
181 "unit_system",
182 "unit_category",
183 "str_input",
184 "str_ref_unit",
185 nullptr,
186 };
187 static _PyArg_Parser _parser = {
188 "s" /* `unit_system` */
189 "s" /* `unit_category` */
190 "s#" /* `str_input` */
191 "|$" /* Optional, keyword only arguments. */
192 "z" /* `str_ref_unit` */
193 ":to_value",
194 _keywords,
195 nullptr,
196 };
197 if (!_PyArg_ParseTupleAndKeywordsFast(
198 args, kw, &_parser, &usys_str, &ucat_str, &inpt, &str_len, &uref))
199 {
200 return nullptr;
201 }
202
203 if (!bpyunits_validate(usys_str, ucat_str, &usys, &ucat)) {
204 return nullptr;
205 }
206
207 const size_t str_maxncpy = str_len * 2 + 64;
208 str = static_cast<char *>(PyMem_MALLOC(sizeof(*str) * str_maxncpy));
209 BLI_strncpy(str, inpt, str_maxncpy);
210
211 BKE_unit_replace_string(str, int(str_maxncpy), uref, scale, usys, ucat);
212
213 if (!PyC_RunString_AsNumber(nullptr, str, "<bpy_units_api>", &result)) {
214 if (PyErr_Occurred()) {
215 PyErr_Print();
216 }
217
218 PyErr_Format(
219 PyExc_ValueError, "'%.200s' (converted as '%s') could not be evaluated.", inpt, str);
220 ret = nullptr;
221 }
222 else {
223 ret = PyFloat_FromDouble(result);
224 }
225
226 PyMem_FREE(str);
227 return ret;
228}
229
231 /* Wrap. */
232 bpyunits_to_string_doc,
233 ".. function:: to_string(unit_system, unit_category, value, *, precision=3, "
234 "split_unit=False, compatible_unit=False)\n"
235 "\n"
236 " Convert a given input float value into a string with units.\n"
237 "\n"
238 " :param unit_system: The unit system, from :attr:`bpy.utils.units.systems`.\n"
239 " :type unit_system: str\n"
240 " :param unit_category: The category of data we are converting (length, area, "
241 "rotation, etc.),\n"
242 " from :attr:`bpy.utils.units.categories`.\n"
243 " :type unit_category: str\n"
244 " :param value: The value to convert to a string.\n"
245 " :type value: float\n"
246 " :param precision: Number of digits after the decimal point.\n"
247 " :type precision: int\n"
248 " :param split_unit: Whether to use several units if needed (1m1cm), or always only "
249 "one (1.01m).\n"
250 " :type split_unit: bool\n"
251 " :param compatible_unit: Whether to use keyboard-friendly units (1m2) or nicer "
252 "UTF8 ones (1m²).\n"
253 " :type compatible_unit: bool\n"
254 " :return: The converted string.\n"
255 " :rtype: str\n"
256 " :raises ValueError: if conversion fails to generate a valid Python string.\n");
257static PyObject *bpyunits_to_string(PyObject * /*self*/, PyObject *args, PyObject *kw)
258{
259 char *usys_str = nullptr, *ucat_str = nullptr;
260 double value = 0.0;
261 int precision = 3;
262 bool split_unit = false, compatible_unit = false;
263
264 int usys, ucat;
265
266 static const char *_keywords[] = {
267 "unit_system",
268 "unit_category",
269 "value",
270 "precision",
271 "split_unit",
272 "compatible_unit",
273 nullptr,
274 };
275 static _PyArg_Parser _parser = {
276 "s" /* `unit_system` */
277 "s" /* `unit_category` */
278 "d" /* `value` */
279 "|$" /* Optional, keyword only arguments. */
280 "i" /* `precision` */
281 "O&" /* `split_unit` */
282 "O&" /* `compatible_unit` */
283 ":to_string",
284 _keywords,
285 nullptr,
286 };
287 if (!_PyArg_ParseTupleAndKeywordsFast(args,
288 kw,
289 &_parser,
290 &usys_str,
291 &ucat_str,
292 &value,
293 &precision,
295 &split_unit,
297 &compatible_unit))
298 {
299 return nullptr;
300 }
301
302 if (!bpyunits_validate(usys_str, ucat_str, &usys, &ucat)) {
303 return nullptr;
304 }
305
306 {
307 /* Maximum expected length of string result:
308 * - Number itself: precision + decimal dot + up to four 'above dot' digits.
309 * - Unit: up to ten chars
310 * (six currently, let's be conservative, also because we use some UTF8 chars).
311 * This can be repeated twice (e.g. `1m20cm`), and we add ten more spare chars
312 * (spaces, trailing '\0'...).
313 * So in practice, 64 should be more than enough.
314 */
315 char buf1[64], buf2[64];
316 const char *str;
317 PyObject *result;
318
320 buf1, sizeof(buf1), value, precision, usys, ucat, split_unit, false, true);
321
322 if (compatible_unit) {
323 BKE_unit_name_to_alt(buf2, sizeof(buf2), buf1, usys, ucat);
324 str = buf2;
325 }
326 else {
327 str = buf1;
328 }
329
330 result = PyUnicode_FromString(str);
331
332 return result;
333 }
334}
335
336#ifdef __GNUC__
337# ifdef __clang__
338# pragma clang diagnostic push
339# pragma clang diagnostic ignored "-Wcast-function-type"
340# else
341# pragma GCC diagnostic push
342# pragma GCC diagnostic ignored "-Wcast-function-type"
343# endif
344#endif
345
346static PyMethodDef bpyunits_methods[] = {
347 {"to_value",
348 reinterpret_cast<PyCFunction>(bpyunits_to_value),
349 METH_VARARGS | METH_KEYWORDS,
350 bpyunits_to_value_doc},
351 {"to_string",
352 reinterpret_cast<PyCFunction>(bpyunits_to_string),
353 METH_VARARGS | METH_KEYWORDS,
354 bpyunits_to_string_doc},
355 {nullptr, nullptr, 0, nullptr},
356};
357
358#ifdef __GNUC__
359# ifdef __clang__
360# pragma clang diagnostic pop
361# else
362# pragma GCC diagnostic pop
363# endif
364#endif
365
367 /* Wrap. */
368 bpyunits_doc,
369 "This module contains some data/methods regarding units handling.\n");
370static PyModuleDef bpyunits_module = {
371 /*m_base*/ PyModuleDef_HEAD_INIT,
372 /*m_name*/ "bpy.utils.units",
373 /*m_doc*/ bpyunits_doc,
374 /*m_size*/ -1, /* multiple "initialization" just copies the module dict. */
375 /*m_methods*/ bpyunits_methods,
376 /*m_slots*/ nullptr,
377 /*m_traverse*/ nullptr,
378 /*m_clear*/ nullptr,
379 /*m_free*/ nullptr,
380};
381
383{
384 PyObject *submodule, *item;
385
386 submodule = PyModule_Create(&bpyunits_module);
387 PyDict_SetItemString(PyImport_GetModuleDict(), bpyunits_module.m_name, submodule);
388
389 /* Finalize our unit systems and types structseq definitions! */
390
391 /* bpy.utils.units.system */
394 PyModule_AddObject(submodule, "systems", item); /* steals ref */
395
396 /* bpy.utils.units.categories */
399 PyModule_AddObject(submodule, "categories", item); /* steals ref */
400
401 return submodule;
402}
403
404} // namespace blender
#define str(s)
float3x3 scale(float3x3 mat, float2 scale)
BMesh Iterators.
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
bool PyC_RunString_AsNumber(const char *imports[], const char *expr, const char *filename, double *r_value)
BLI_STATIC_ASSERT(ARRAY_SIZE(data_mode_strings)==CTX_MODE_NUM+1, "Must have a string for each context mode") const char *CTX_data_mode_string(const bContext *C)
int PyC_ParseBool(PyObject *o, void *p)
static PyObject * bpyunits_to_string(PyObject *, PyObject *args, PyObject *kw)
PyDoc_STRVAR(bpy_bm_new_doc, ".. function:: new(*, use_operators=True)\n" "\n" " :param use_operators: Support calling operators in :mod:`bmesh.ops` (uses some " "extra memory per vert/edge/face).\n" " :type use_operators: bool\n" " :return: Return a new, empty BMesh.\n" " :rtype: :class:`bmesh.types.BMesh`\n")
static PyTypeObject BPyUnitsSystemsType
static const char * bpyunits_ucategories_items[]
static PyStructSequence_Desc bpyunits_systems_desc
static PyModuleDef bpyunits_module
static PyMethodDef bpyunits_methods[]
int BLI_str_index_in_array(const char *__restrict str, const char **__restrict str_array) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1
static PyObject * py_structseq_from_strings(PyTypeObject *py_type, PyStructSequence_Desc *py_sseq_desc, const char **str_items)
bool BKE_unit_replace_string(char *str, int str_maxncpy, const char *str_prev, double scale_pref, int system, int type)
Definition unit.cc:2414
static PyObject * bpyunits_to_value(PyObject *, PyObject *args, PyObject *kw)
char * BLI_strncpy(char *__restrict dst, const char *__restrict src, size_t dst_maxncpy) ATTR_NONNULL(1
static PyStructSequence_Field bpyunits_categories_fields[ARRAY_SIZE(bpyunits_ucategories_items)]
static PyTypeObject BPyUnitsCategoriesType
PyObject * BPY_utils_units()
constexpr size_t ARRAY_SIZE(const T(&arg)[N]) noexcept
static PyStructSequence_Desc bpyunits_categories_desc
size_t BKE_unit_value_as_string_adaptive(char *str, int str_maxncpy, double value, int prec, int system, int type, bool split, bool pad, bool do_unit_suffix)
Definition unit.cc:1908
bool BKE_unit_is_valid(int system, int type)
Definition unit.cc:2571
static bool bpyunits_validate(const char *usys_str, const char *ucat_str, int *r_usys, int *r_ucat)
void BKE_unit_name_to_alt(char *str, int str_maxncpy, const char *orig_str, int system, int type)
Definition unit.cc:2504
static const char * bpyunits_usystem_items[]
@ B_UNIT_TYPE_TOT
Definition BKE_unit.hh:181
header-only compatibility defines.