unit.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  1. /*
  2. * ***** BEGIN GPL LICENSE BLOCK *****
  3. *
  4. * This program is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU General Public License
  6. * as published by the Free Software Foundation; either version 2
  7. * of the License, or (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, write to the Free Software Foundation,
  16. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  17. *
  18. * Contributor(s): Campbell Barton
  19. *
  20. * ***** END GPL LICENSE BLOCK *****
  21. */
  22. /** \file blender/blenkernel/intern/unit.c
  23. * \ingroup bke
  24. */
  25. #include <stdlib.h>
  26. #include <stdio.h>
  27. #include <ctype.h>
  28. #include <string.h>
  29. #include <assert.h>
  30. #include "BLI_sys_types.h"
  31. #include "BLI_math.h"
  32. #include "BLI_string.h"
  33. #include "BLI_string_utf8.h"
  34. #include "BKE_unit.h" /* own include */
  35. #ifdef WIN32
  36. # include "BLI_winstuff.h"
  37. #endif
  38. /* no BKE or DNA includes! */
  39. #define TEMP_STR_SIZE 256
  40. #define SEP_CHR '#'
  41. #define SEP_STR "#"
  42. #define EPS 0.001
  43. #define UN_SC_KM 1000.0f
  44. #define UN_SC_HM 100.0f
  45. #define UN_SC_DAM 10.0f
  46. #define UN_SC_M 1.0f
  47. #define UN_SC_DM 0.1f
  48. #define UN_SC_CM 0.01f
  49. #define UN_SC_MM 0.001f
  50. #define UN_SC_UM 0.000001f
  51. #define UN_SC_MI 1609.344f
  52. #define UN_SC_FUR 201.168f
  53. #define UN_SC_CH 20.1168f
  54. #define UN_SC_YD 0.9144f
  55. #define UN_SC_FT 0.3048f
  56. #define UN_SC_IN 0.0254f
  57. #define UN_SC_MIL 0.0000254f
  58. #define UN_SC_MTON 1000.0f /* metric ton */
  59. #define UN_SC_QL 100.0f
  60. #define UN_SC_KG 1.0f
  61. #define UN_SC_HG 0.1f
  62. #define UN_SC_DAG 0.01f
  63. #define UN_SC_G 0.001f
  64. #define UN_SC_MG 0.000001f
  65. #define UN_SC_ITON 907.18474f /* imperial ton */
  66. #define UN_SC_CWT 45.359237f
  67. #define UN_SC_ST 6.35029318f
  68. #define UN_SC_LB 0.45359237f
  69. #define UN_SC_OZ 0.028349523125f
  70. /* define a single unit */
  71. typedef struct bUnitDef {
  72. const char *name;
  73. const char *name_plural; /* abused a bit for the display name */
  74. const char *name_short; /* this is used for display*/
  75. const char *name_alt; /* keyboard-friendly ASCII-only version of name_short, can be NULL */
  76. /* if name_short has non-ASCII chars, name_alt should be present */
  77. const char *name_display; /* can be NULL */
  78. double scalar;
  79. double bias; /* not used yet, needed for converting temperature */
  80. int flag;
  81. } bUnitDef;
  82. #define B_UNIT_DEF_NONE 0
  83. #define B_UNIT_DEF_SUPPRESS 1 /* Use for units that are not used enough to be translated into for common use */
  84. #define B_UNIT_DEF_TENTH 2 /* Display a unit even if its value is 0.1, eg 0.1mm instead of 100um */
  85. /* define a single unit */
  86. typedef struct bUnitCollection {
  87. const struct bUnitDef *units;
  88. int base_unit; /* basic unit index (when user doesn't specify unit explicitly) */
  89. int flag; /* options for this system */
  90. int length; /* to quickly find the last item */
  91. } bUnitCollection;
  92. /* Dummy */
  93. static struct bUnitDef buDummyDef[] = { {"", NULL, "", NULL, NULL, 1.0, 0.0}, {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}};
  94. static struct bUnitCollection buDummyCollection = {buDummyDef, 0, 0, sizeof(buDummyDef)};
  95. /* Lengths */
  96. static const struct bUnitDef buMetricLenDef[] = {
  97. {"kilometer", "kilometers", "km", NULL, "Kilometers", UN_SC_KM, 0.0, B_UNIT_DEF_NONE},
  98. {"hectometer", "hectometers", "hm", NULL, "100 Meters", UN_SC_HM, 0.0, B_UNIT_DEF_SUPPRESS},
  99. {"dekameter", "dekameters", "dam", NULL, "10 Meters", UN_SC_DAM, 0.0, B_UNIT_DEF_SUPPRESS},
  100. {"meter", "meters", "m", NULL, "Meters", UN_SC_M, 0.0, B_UNIT_DEF_NONE}, /* base unit */
  101. {"decimeter", "decimeters", "dm", NULL, "10 Centimeters", UN_SC_DM, 0.0, B_UNIT_DEF_SUPPRESS},
  102. {"centimeter", "centimeters", "cm", NULL, "Centimeters", UN_SC_CM, 0.0, B_UNIT_DEF_NONE},
  103. {"millimeter", "millimeters", "mm", NULL, "Millimeters", UN_SC_MM, 0.0, B_UNIT_DEF_NONE | B_UNIT_DEF_TENTH},
  104. {"micrometer", "micrometers", "µm", "um", "Micrometers", UN_SC_UM, 0.0, B_UNIT_DEF_NONE},
  105. /* These get displayed because of float precision problems in the transform header,
  106. * could work around, but for now probably people wont use these */
  107. #if 0
  108. {"nanometer", "Nanometers", "nm", NULL, 0.000000001, 0.0, B_UNIT_DEF_NONE},
  109. {"picometer", "Picometers", "pm", NULL, 0.000000000001, 0.0, B_UNIT_DEF_NONE},
  110. #endif
  111. {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
  112. };
  113. static const struct bUnitCollection buMetricLenCollection = {buMetricLenDef, 3, 0, sizeof(buMetricLenDef) / sizeof(bUnitDef)};
  114. static struct bUnitDef buImperialLenDef[] = {
  115. {"mile", "miles", "mi", "m", "Miles", UN_SC_MI, 0.0, B_UNIT_DEF_NONE},
  116. {"furlong", "furlongs", "fur", NULL, "Furlongs", UN_SC_FUR, 0.0, B_UNIT_DEF_SUPPRESS},
  117. {"chain", "chains", "ch", NULL, "Chains", UN_SC_CH, 0.0, B_UNIT_DEF_SUPPRESS},
  118. {"yard", "yards", "yd", NULL, "Yards", UN_SC_YD, 0.0, B_UNIT_DEF_SUPPRESS},
  119. {"foot", "feet", "'", "ft", "Feet", UN_SC_FT, 0.0, B_UNIT_DEF_NONE}, /* base unit */
  120. {"inch", "inches", "\"", "in", "Inches", UN_SC_IN, 0.0, B_UNIT_DEF_NONE},
  121. {"thou", "thou", "thou", "mil", "Thou", UN_SC_MIL, 0.0, B_UNIT_DEF_NONE}, /* plural for thou has no 's' */
  122. {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
  123. };
  124. static struct bUnitCollection buImperialLenCollection = {buImperialLenDef, 4, 0, sizeof(buImperialLenDef) / sizeof(bUnitDef)};
  125. /* Areas */
  126. static struct bUnitDef buMetricAreaDef[] = {
  127. {"square kilometer", "square kilometers", "km²", "km2", "Square Kilometers", UN_SC_KM * UN_SC_KM, 0.0, B_UNIT_DEF_NONE},
  128. {"square hectometer", "square hectometers", "hm²", "hm2", "Square Hectometers", UN_SC_HM * UN_SC_HM, 0.0, B_UNIT_DEF_SUPPRESS}, /* hectare */
  129. {"square dekameter", "square dekameters", "dam²", "dam2", "Square Dekameters", UN_SC_DAM * UN_SC_DAM, 0.0, B_UNIT_DEF_SUPPRESS}, /* are */
  130. {"square meter", "square meters", "m²", "m2", "Square Meters", UN_SC_M * UN_SC_M, 0.0, B_UNIT_DEF_NONE}, /* base unit */
  131. {"square decimeter", "square decimetees", "dm²", "dm2", "Square Decimeters", UN_SC_DM * UN_SC_DM, 0.0, B_UNIT_DEF_SUPPRESS},
  132. {"square centimeter", "square centimeters", "cm²", "cm2", "Square Centimeters", UN_SC_CM * UN_SC_CM, 0.0, B_UNIT_DEF_NONE},
  133. {"square millimeter", "square millimeters", "mm²", "mm2", "Square Millimeters", UN_SC_MM * UN_SC_MM, 0.0, B_UNIT_DEF_NONE | B_UNIT_DEF_TENTH},
  134. {"square micrometer", "square micrometers", "µm²", "um2", "Square Micrometers", UN_SC_UM * UN_SC_UM, 0.0, B_UNIT_DEF_NONE},
  135. {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
  136. };
  137. static struct bUnitCollection buMetricAreaCollection = {buMetricAreaDef, 3, 0, sizeof(buMetricAreaDef) / sizeof(bUnitDef)};
  138. static struct bUnitDef buImperialAreaDef[] = {
  139. {"square mile", "square miles", "sq mi", "sq m", "Square Miles", UN_SC_MI * UN_SC_MI, 0.0, B_UNIT_DEF_NONE},
  140. {"square furlong", "square furlongs", "sq fur", NULL, "Square Furlongs", UN_SC_FUR * UN_SC_FUR, 0.0, B_UNIT_DEF_SUPPRESS},
  141. {"square chain", "square chains", "sq ch", NULL, "Square Chains", UN_SC_CH * UN_SC_CH, 0.0, B_UNIT_DEF_SUPPRESS},
  142. {"square yard", "square yards", "sq yd", NULL, "Square Yards", UN_SC_YD * UN_SC_YD, 0.0, B_UNIT_DEF_NONE},
  143. {"square foot", "square feet", "sq ft", NULL, "Square Feet", UN_SC_FT * UN_SC_FT, 0.0, B_UNIT_DEF_NONE}, /* base unit */
  144. {"square inch", "square inches", "sq in", NULL, "Square Inches", UN_SC_IN * UN_SC_IN, 0.0, B_UNIT_DEF_NONE},
  145. {"square thou", "square thous", "sq mil", NULL, "Square Thous", UN_SC_MIL * UN_SC_MIL, 0.0, B_UNIT_DEF_NONE},
  146. {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
  147. };
  148. static struct bUnitCollection buImperialAreaCollection = {buImperialAreaDef, 4, 0, sizeof(buImperialAreaDef) / sizeof(bUnitDef)};
  149. /* Volumes */
  150. static struct bUnitDef buMetricVolDef[] = {
  151. {"cubic kilometer", "cubic kilometers", "km³", "km3", "Cubic Kilometers", UN_SC_KM * UN_SC_KM * UN_SC_KM, 0.0, B_UNIT_DEF_NONE},
  152. {"cubic hectometer", "cubic hectometers", "hm³", "hm3", "Cubic Hectometers", UN_SC_HM * UN_SC_HM * UN_SC_HM, 0.0, B_UNIT_DEF_SUPPRESS},
  153. {"cubic dekameter", "cubic dekameters", "dam³", "dam3", "Cubic Dekameters", UN_SC_DAM * UN_SC_DAM * UN_SC_DAM, 0.0, B_UNIT_DEF_SUPPRESS},
  154. {"cubic meter", "cubic meters", "m³", "m3", "Cubic Meters", UN_SC_M * UN_SC_M * UN_SC_M, 0.0, B_UNIT_DEF_NONE}, /* base unit */
  155. {"cubic decimeter", "cubic decimeters", "dm³", "dm3", "Cubic Decimeters", UN_SC_DM * UN_SC_DM * UN_SC_DM, 0.0, B_UNIT_DEF_SUPPRESS},
  156. {"cubic centimeter", "cubic centimeters", "cm³", "cm3", "Cubic Centimeters", UN_SC_CM * UN_SC_CM * UN_SC_CM, 0.0, B_UNIT_DEF_NONE},
  157. {"cubic millimeter", "cubic millimeters", "mm³", "mm3", "Cubic Millimeters", UN_SC_MM * UN_SC_MM * UN_SC_MM, 0.0, B_UNIT_DEF_NONE | B_UNIT_DEF_TENTH},
  158. {"cubic micrometer", "cubic micrometers", "µm³", "um3", "Cubic Micrometers", UN_SC_UM * UN_SC_UM * UN_SC_UM, 0.0, B_UNIT_DEF_NONE},
  159. {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
  160. };
  161. static struct bUnitCollection buMetricVolCollection = {buMetricVolDef, 3, 0, sizeof(buMetricVolDef) / sizeof(bUnitDef)};
  162. static struct bUnitDef buImperialVolDef[] = {
  163. {"cubic mile", "cubic miles", "cu mi", "cu m", "Cubic Miles", UN_SC_MI * UN_SC_MI * UN_SC_MI, 0.0, B_UNIT_DEF_NONE},
  164. {"cubic furlong", "cubic furlongs", "cu fur", NULL, "Cubic Furlongs", UN_SC_FUR * UN_SC_FUR * UN_SC_FUR, 0.0, B_UNIT_DEF_SUPPRESS},
  165. {"cubic chain", "cubic chains", "cu ch", NULL, "Cubic Chains", UN_SC_CH * UN_SC_CH * UN_SC_CH, 0.0, B_UNIT_DEF_SUPPRESS},
  166. {"cubic yard", "cubic yards", "cu yd", NULL, "Cubic Yards", UN_SC_YD * UN_SC_YD * UN_SC_YD, 0.0, B_UNIT_DEF_NONE},
  167. {"cubic foot", "cubic feet", "cu ft", NULL, "Cubic Feet", UN_SC_FT * UN_SC_FT * UN_SC_FT, 0.0, B_UNIT_DEF_NONE}, /* base unit */
  168. {"cubic inch", "cubic inches", "cu in", NULL, "Cubic Inches", UN_SC_IN * UN_SC_IN * UN_SC_IN, 0.0, B_UNIT_DEF_NONE},
  169. {"cubic thou", "cubic thous", "cu mil", NULL, "Cubic Thous", UN_SC_MIL * UN_SC_MIL * UN_SC_MIL, 0.0, B_UNIT_DEF_NONE},
  170. {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
  171. };
  172. static struct bUnitCollection buImperialVolCollection = {buImperialVolDef, 4, 0, sizeof(buImperialVolDef) / sizeof(bUnitDef)};
  173. /* Mass */
  174. static struct bUnitDef buMetricMassDef[] = {
  175. {"ton", "tonnes", "ton", "t", "1000 Kilograms", UN_SC_MTON, 0.0, B_UNIT_DEF_NONE},
  176. {"quintal", "quintals", "ql", "q", "100 Kilograms", UN_SC_QL, 0.0, B_UNIT_DEF_SUPPRESS},
  177. {"kilogram", "kilograms", "kg", NULL, "Kilograms", UN_SC_KG, 0.0, B_UNIT_DEF_NONE}, /* base unit */
  178. {"hectogram", "hectograms", "hg", NULL, "Hectograms", UN_SC_HG, 0.0, B_UNIT_DEF_SUPPRESS},
  179. {"dekagram", "dekagrams", "dag", NULL, "10 Grams", UN_SC_DAG, 0.0, B_UNIT_DEF_SUPPRESS},
  180. {"gram", "grams", "g", NULL, "Grams", UN_SC_G, 0.0, B_UNIT_DEF_NONE},
  181. {"milligram", "milligrams", "mg", NULL, "Milligrams", UN_SC_MG, 0.0, B_UNIT_DEF_NONE},
  182. {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
  183. };
  184. static struct bUnitCollection buMetricMassCollection = {buMetricMassDef, 2, 0, sizeof(buMetricMassDef) / sizeof(bUnitDef)};
  185. static struct bUnitDef buImperialMassDef[] = {
  186. {"ton", "tonnes", "ton", "t", "Tonnes", UN_SC_ITON, 0.0, B_UNIT_DEF_NONE},
  187. {"centum weight", "centum weights", "cwt", NULL, "Centum weights", UN_SC_CWT, 0.0, B_UNIT_DEF_NONE},
  188. {"stone", "stones", "st", NULL, "Stones", UN_SC_ST, 0.0, B_UNIT_DEF_NONE},
  189. {"pound", "pounds", "lb", NULL, "Pounds", UN_SC_LB, 0.0, B_UNIT_DEF_NONE}, /* base unit */
  190. {"ounce", "ounces", "oz", NULL, "Ounces", UN_SC_OZ, 0.0, B_UNIT_DEF_NONE},
  191. {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
  192. };
  193. static struct bUnitCollection buImperialMassCollection = {buImperialMassDef, 3, 0, sizeof(buImperialMassDef) / sizeof(bUnitDef)};
  194. /* Even if user scales the system to a point where km^3 is used, velocity and
  195. * acceleration aren't scaled: that's why we have so few units for them */
  196. /* Velocity */
  197. static struct bUnitDef buMetricVelDef[] = {
  198. {"meter per second", "meters per second", "m/s", NULL, "Meters per second", UN_SC_M, 0.0, B_UNIT_DEF_NONE}, /* base unit */
  199. {"kilometer per hour", "kilometers per hour", "km/h", NULL, "Kilometers per hour", UN_SC_KM / 3600.0f, 0.0, B_UNIT_DEF_SUPPRESS},
  200. {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
  201. };
  202. static struct bUnitCollection buMetricVelCollection = {buMetricVelDef, 0, 0, sizeof(buMetricVelDef) / sizeof(bUnitDef)};
  203. static struct bUnitDef buImperialVelDef[] = {
  204. {"foot per second", "feet per second", "ft/s", "fps", "Feet per second", UN_SC_FT, 0.0, B_UNIT_DEF_NONE}, /* base unit */
  205. {"mile per hour", "miles per hour", "mph", NULL, "Miles per hour", UN_SC_MI / 3600.0f, 0.0, B_UNIT_DEF_SUPPRESS},
  206. {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
  207. };
  208. static struct bUnitCollection buImperialVelCollection = {buImperialVelDef, 0, 0, sizeof(buImperialVelDef) / sizeof(bUnitDef)};
  209. /* Acceleration */
  210. static struct bUnitDef buMetricAclDef[] = {
  211. {"meter per second squared", "meters per second squared", "m/s²", "m/s2", "Meters per second squared", UN_SC_M, 0.0, B_UNIT_DEF_NONE}, /* base unit */
  212. {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
  213. };
  214. static struct bUnitCollection buMetricAclCollection = {buMetricAclDef, 0, 0, sizeof(buMetricAclDef) / sizeof(bUnitDef)};
  215. static struct bUnitDef buImperialAclDef[] = {
  216. {"foot per second squared", "feet per second squared", "ft/s²", "ft/s2", "Feet per second squared", UN_SC_FT, 0.0, B_UNIT_DEF_NONE}, /* base unit */
  217. {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
  218. };
  219. static struct bUnitCollection buImperialAclCollection = {buImperialAclDef, 0, 0, sizeof(buImperialAclDef) / sizeof(bUnitDef)};
  220. /* Time */
  221. static struct bUnitDef buNaturalTimeDef[] = {
  222. /* weeks? - probably not needed for blender */
  223. {"day", "days", "d", NULL, "Days", 90000.0, 0.0, B_UNIT_DEF_NONE},
  224. {"hour", "hours", "hr", "h", "Hours", 3600.0, 0.0, B_UNIT_DEF_NONE},
  225. {"minute", "minutes", "min", "m", "Minutes", 60.0, 0.0, B_UNIT_DEF_NONE},
  226. {"second", "seconds", "sec", "s", "Seconds", 1.0, 0.0, B_UNIT_DEF_NONE}, /* base unit */
  227. {"millisecond", "milliseconds", "ms", NULL, "Milliseconds", 0.001, 0.0, B_UNIT_DEF_NONE},
  228. {"microsecond", "microseconds", "µs", "us", "Microseconds", 0.000001, 0.0, B_UNIT_DEF_NONE},
  229. {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
  230. };
  231. static struct bUnitCollection buNaturalTimeCollection = {buNaturalTimeDef, 3, 0, sizeof(buNaturalTimeDef) / sizeof(bUnitDef)};
  232. static struct bUnitDef buNaturalRotDef[] = {
  233. {"degree", "degrees", "°", "d", "Degrees", M_PI / 180.0, 0.0, B_UNIT_DEF_NONE},
  234. /* arcminutes/arcseconds are used in Astronomy/Navigation areas... */
  235. {"arcminute", "arcminutes", "'", NULL, "Arcminutes", (M_PI / 180.0) / 60.0, 0.0, B_UNIT_DEF_SUPPRESS},
  236. {"arcsecond", "arcseconds", "\"", NULL, "Arcseconds", (M_PI / 180.0) / 3600.0, 0.0, B_UNIT_DEF_SUPPRESS},
  237. {"radian", "radians", "r", NULL, "Radians", 1.0, 0.0, B_UNIT_DEF_NONE},
  238. // {"turn", "turns", "t", NULL, "Turns", 1.0 / (M_PI * 2.0), 0.0, B_UNIT_DEF_NONE},
  239. {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
  240. };
  241. static struct bUnitCollection buNaturalRotCollection = {buNaturalRotDef, 0, 0, sizeof(buNaturalRotDef) / sizeof(bUnitDef)};
  242. /* Camera Lengths */
  243. static struct bUnitDef buCameraLenDef[] = {
  244. {"meter", "meters", "m", NULL, "Meters", UN_SC_KM, 0.0, B_UNIT_DEF_NONE}, /* base unit */
  245. {"decimeter", "decimeters", "dm", NULL, "10 Centimeters", UN_SC_HM, 0.0, B_UNIT_DEF_SUPPRESS},
  246. {"centimeter", "centimeters", "cm", NULL, "Centimeters", UN_SC_DAM, 0.0, B_UNIT_DEF_SUPPRESS},
  247. {"millimeter", "millimeters", "mm", NULL, "Millimeters", UN_SC_M, 0.0, B_UNIT_DEF_NONE},
  248. {"micrometer", "micrometers", "µm", "um", "Micrometers", UN_SC_MM, 0.0, B_UNIT_DEF_SUPPRESS},
  249. {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
  250. };
  251. static struct bUnitCollection buCameraLenCollection = {buCameraLenDef, 3, 0, sizeof(buCameraLenDef) / sizeof(bUnitDef)};
  252. #define UNIT_SYSTEM_TOT (((sizeof(bUnitSystems) / B_UNIT_TYPE_TOT) / sizeof(void *)) - 1)
  253. static const struct bUnitCollection *bUnitSystems[][B_UNIT_TYPE_TOT] = {
  254. {NULL, NULL, NULL, NULL, NULL, &buNaturalRotCollection, &buNaturalTimeCollection, NULL, NULL, NULL},
  255. {NULL, &buMetricLenCollection, &buMetricAreaCollection, &buMetricVolCollection, &buMetricMassCollection, &buNaturalRotCollection, &buNaturalTimeCollection, &buMetricVelCollection, &buMetricAclCollection, &buCameraLenCollection}, /* metric */
  256. {NULL, &buImperialLenCollection, &buImperialAreaCollection, &buImperialVolCollection, &buImperialMassCollection, &buNaturalRotCollection, &buNaturalTimeCollection, &buImperialVelCollection, &buImperialAclCollection, &buCameraLenCollection}, /* imperial */
  257. {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}
  258. };
  259. /* internal, has some option not exposed */
  260. static const bUnitCollection *unit_get_system(int system, int type)
  261. {
  262. assert((system > -1) && (system < UNIT_SYSTEM_TOT) && (type > -1) && (type < B_UNIT_TYPE_TOT));
  263. return bUnitSystems[system][type]; /* select system to use, metric/imperial/other? */
  264. }
  265. static const bUnitDef *unit_default(const bUnitCollection *usys)
  266. {
  267. return &usys->units[usys->base_unit];
  268. }
  269. static const bUnitDef *unit_best_fit(
  270. double value, const bUnitCollection *usys, const bUnitDef *unit_start, int suppress)
  271. {
  272. const bUnitDef *unit;
  273. double value_abs = value > 0.0 ? value : -value;
  274. for (unit = unit_start ? unit_start : usys->units; unit->name; unit++) {
  275. if (suppress && (unit->flag & B_UNIT_DEF_SUPPRESS))
  276. continue;
  277. /* scale down scalar so 1cm doesnt convert to 10mm because of float error */
  278. if (UNLIKELY(unit->flag & B_UNIT_DEF_TENTH)) {
  279. if (value_abs >= unit->scalar * (0.1 - EPS)) {
  280. return unit;
  281. }
  282. }
  283. else {
  284. if (value_abs >= unit->scalar * (1.0 - EPS)) {
  285. return unit;
  286. }
  287. }
  288. }
  289. return unit_default(usys);
  290. }
  291. /* convert into 2 units and 2 values for "2ft, 3inch" syntax */
  292. static void unit_dual_convert(
  293. double value, const bUnitCollection *usys,
  294. bUnitDef const **r_unit_a, bUnitDef const **r_unit_b,
  295. double *r_value_a, double *r_value_b)
  296. {
  297. const bUnitDef *unit = unit_best_fit(value, usys, NULL, 1);
  298. *r_value_a = (value < 0.0 ? ceil : floor)(value / unit->scalar) * unit->scalar;
  299. *r_value_b = value - (*r_value_a);
  300. *r_unit_a = unit;
  301. *r_unit_b = unit_best_fit(*r_value_b, usys, *r_unit_a, 1);
  302. }
  303. static size_t unit_as_string(char *str, int len_max, double value, int prec, const bUnitCollection *usys,
  304. /* non exposed options */
  305. const bUnitDef *unit, char pad)
  306. {
  307. double value_conv;
  308. size_t len, i;
  309. if (unit) {
  310. /* use unit without finding the best one */
  311. }
  312. else if (value == 0.0) {
  313. /* use the default units since there is no way to convert */
  314. unit = unit_default(usys);
  315. }
  316. else {
  317. unit = unit_best_fit(value, usys, NULL, 1);
  318. }
  319. value_conv = value / unit->scalar;
  320. /* Adjust precision to expected number of significant digits.
  321. * Note that here, we shall not have to worry about very big/small numbers, units are expected to replace
  322. * 'scientific notation' in those cases. */
  323. prec -= integer_digits_d(value_conv);
  324. CLAMP(prec, 0, 6);
  325. /* Convert to a string */
  326. len = BLI_snprintf_rlen(str, len_max, "%.*f", prec, value_conv);
  327. /* Add unit prefix and strip zeros */
  328. /* replace trailing zero's with spaces
  329. * so the number is less complicated but alignment in a button wont
  330. * jump about while dragging */
  331. i = len - 1;
  332. if (prec > 0) {
  333. while (i > 0 && str[i] == '0') { /* 4.300 -> 4.3 */
  334. str[i--] = pad;
  335. }
  336. if (i > 0 && str[i] == '.') { /* 10. -> 10 */
  337. str[i--] = pad;
  338. }
  339. }
  340. /* Now add the suffix */
  341. if (i < len_max) {
  342. int j = 0;
  343. i++;
  344. while (unit->name_short[j] && (i < len_max)) {
  345. str[i++] = unit->name_short[j++];
  346. }
  347. #if 0
  348. if (pad) {
  349. /* this loop only runs if so many zeros were removed that
  350. * the unit name only used padded chars,
  351. * In that case add padding for the name. */
  352. while (i <= len + j && (i < len_max)) {
  353. str[i++] = pad;
  354. }
  355. }
  356. #endif
  357. }
  358. /* terminate no matter whats done with padding above */
  359. if (i >= len_max)
  360. i = len_max - 1;
  361. str[i] = '\0';
  362. return i;
  363. }
  364. /* Used for drawing number buttons, try keep fast.
  365. * Return the length of the generated string.
  366. */
  367. size_t bUnit_AsString(char *str, int len_max, double value, int prec, int system, int type, bool split, bool pad)
  368. {
  369. const bUnitCollection *usys = unit_get_system(system, type);
  370. if (usys == NULL || usys->units[0].name == NULL)
  371. usys = &buDummyCollection;
  372. /* split output makes sense only for length, mass and time */
  373. if (split && (type == B_UNIT_LENGTH || type == B_UNIT_MASS || type == B_UNIT_TIME || type == B_UNIT_CAMERA)) {
  374. const bUnitDef *unit_a, *unit_b;
  375. double value_a, value_b;
  376. unit_dual_convert(value, usys, &unit_a, &unit_b, &value_a, &value_b);
  377. /* check the 2 is a smaller unit */
  378. if (unit_b > unit_a) {
  379. size_t i;
  380. i = unit_as_string(str, len_max, value_a, prec, usys, unit_a, '\0');
  381. prec -= integer_digits_d(value_a / unit_b->scalar) - integer_digits_d(value_b / unit_b->scalar);
  382. prec = max_ii(prec, 0);
  383. /* is there enough space for at least 1 char of the next unit? */
  384. if (i + 2 < len_max) {
  385. str[i++] = ' ';
  386. /* use low precision since this is a smaller unit */
  387. i += unit_as_string(str + i, len_max - i, value_b, prec, usys, unit_b, '\0');
  388. }
  389. return i;
  390. }
  391. }
  392. return unit_as_string(str, len_max, value, prec, usys, NULL, pad ? ' ' : '\0');
  393. }
  394. BLI_INLINE bool isalpha_or_utf8(const int ch)
  395. {
  396. return (ch >= 128 || isalpha(ch));
  397. }
  398. static const char *unit_find_str(const char *str, const char *substr)
  399. {
  400. if (substr && substr[0] != '\0') {
  401. while (true) {
  402. const char *str_found = strstr(str, substr);
  403. if (str_found) {
  404. /* Previous char cannot be a letter. */
  405. if (str_found == str ||
  406. /* weak unicode support!, so "µm" won't match up be replaced by "m"
  407. * since non ascii utf8 values will NEVER return true */
  408. isalpha_or_utf8(*BLI_str_prev_char_utf8(str_found)) == 0)
  409. {
  410. /* next char cannot be alphanum */
  411. int len_name = strlen(substr);
  412. if (!isalpha_or_utf8(*(str_found + len_name))) {
  413. return str_found;
  414. }
  415. }
  416. /* If str_found is not a valid unit, we have to check further in the string... */
  417. for (str_found++; isalpha_or_utf8(*str_found); str_found++);
  418. str = str_found;
  419. }
  420. else {
  421. break;
  422. }
  423. }
  424. }
  425. return NULL;
  426. }
  427. /* Note that numbers are added within brackets
  428. * ") " - is used to detect numbers we added so we can detect if commas need to be added
  429. *
  430. * "1m1cm+2mm" - Original value
  431. * "1*1#1*0.01#+2*0.001#" - Replace numbers
  432. * "1*1+1*0.01 +2*0.001 " - Add add signs if ( + - * / | & ~ < > ^ ! = % ) not found in between
  433. *
  434. */
  435. /* not too strict, (+ - * /) are most common */
  436. static bool ch_is_op(char op)
  437. {
  438. switch (op) {
  439. case '+':
  440. case '-':
  441. case '*':
  442. case '/':
  443. case '|':
  444. case '&':
  445. case '~':
  446. case '<':
  447. case '>':
  448. case '^':
  449. case '!':
  450. case '=':
  451. case '%':
  452. return true;
  453. default:
  454. return false;
  455. }
  456. }
  457. static int unit_scale_str(char *str, int len_max, char *str_tmp, double scale_pref, const bUnitDef *unit,
  458. const char *replace_str)
  459. {
  460. char *str_found;
  461. if ((len_max > 0) && (str_found = (char *)unit_find_str(str, replace_str))) {
  462. /* XXX - investigate, does not respect len_max properly */
  463. int len, len_num, len_name, len_move, found_ofs;
  464. found_ofs = (int)(str_found - str);
  465. len = strlen(str);
  466. len_name = strlen(replace_str);
  467. len_move = (len - (found_ofs + len_name)) + 1; /* 1+ to copy the string terminator */
  468. len_num = BLI_snprintf(str_tmp, TEMP_STR_SIZE, "*%.9g"SEP_STR, unit->scalar / scale_pref); /* # removed later */
  469. if (len_num > len_max)
  470. len_num = len_max;
  471. if (found_ofs + len_num + len_move > len_max) {
  472. /* can't move the whole string, move just as much as will fit */
  473. len_move -= (found_ofs + len_num + len_move) - len_max;
  474. }
  475. if (len_move > 0) {
  476. /* resize the last part of the string */
  477. memmove(str_found + len_num, str_found + len_name, len_move); /* may grow or shrink the string */
  478. }
  479. if (found_ofs + len_num > len_max) {
  480. /* not even the number will fit into the string, only copy part of it */
  481. len_num -= (found_ofs + len_num) - len_max;
  482. }
  483. if (len_num > 0) {
  484. /* its possible none of the number could be copied in */
  485. memcpy(str_found, str_tmp, len_num); /* without the string terminator */
  486. }
  487. /* since the null terminator wont be moved if the stringlen_max
  488. * was not long enough to fit everything in it */
  489. str[len_max - 1] = '\0';
  490. return found_ofs + len_num;
  491. }
  492. return 0;
  493. }
  494. static int unit_replace(char *str, int len_max, char *str_tmp, double scale_pref, const bUnitDef *unit)
  495. {
  496. int ofs = 0;
  497. ofs += unit_scale_str(str + ofs, len_max - ofs, str_tmp, scale_pref, unit, unit->name_short);
  498. ofs += unit_scale_str(str + ofs, len_max - ofs, str_tmp, scale_pref, unit, unit->name_plural);
  499. ofs += unit_scale_str(str + ofs, len_max - ofs, str_tmp, scale_pref, unit, unit->name_alt);
  500. ofs += unit_scale_str(str + ofs, len_max - ofs, str_tmp, scale_pref, unit, unit->name);
  501. return ofs;
  502. }
  503. static bool unit_find(const char *str, const bUnitDef *unit)
  504. {
  505. if (unit_find_str(str, unit->name_short)) return true;
  506. if (unit_find_str(str, unit->name_plural)) return true;
  507. if (unit_find_str(str, unit->name_alt)) return true;
  508. if (unit_find_str(str, unit->name)) return true;
  509. return false;
  510. }
  511. static const bUnitDef *unit_detect_from_str(const bUnitCollection *usys, const char *str, const char *str_prev)
  512. {
  513. /* Try to find a default unit from current or previous string.
  514. * This allows us to handle cases like 2 + 2mm, people would expect to get 4mm, not 2.002m!
  515. * Note this does not handle corner cases like 2 + 2cm + 1 + 2.5mm... We can't support everything. */
  516. const bUnitDef *unit = NULL;
  517. /* see which units the new value has */
  518. for (unit = usys->units; unit->name; unit++) {
  519. if (unit_find(str, unit))
  520. break;
  521. }
  522. /* Else, try to infer the default unit from the previous string. */
  523. if (str_prev && (unit == NULL || unit->name == NULL)) {
  524. /* see which units the original value had */
  525. for (unit = usys->units; unit->name; unit++) {
  526. if (unit_find(str_prev, unit))
  527. break;
  528. }
  529. }
  530. /* Else, fall back to default unit. */
  531. if (unit == NULL || unit->name == NULL) {
  532. unit = unit_default(usys);
  533. }
  534. return unit;
  535. }
  536. /* make a copy of the string that replaces the units with numbers
  537. * this is used before parsing
  538. * This is only used when evaluating user input and can afford to be a bit slower
  539. *
  540. * This is to be used before python evaluation so..
  541. * 10.1km -> 10.1*1000.0
  542. * ...will be resolved by python.
  543. *
  544. * values will be split by an add sign
  545. * 5'2" -> 5*0.3048 + 2*0.0254
  546. *
  547. * str_prev is optional, when valid it is used to get a base unit when none is set.
  548. *
  549. * return true of a change was made.
  550. */
  551. bool bUnit_ReplaceString(char *str, int len_max, const char *str_prev, double scale_pref, int system, int type)
  552. {
  553. const bUnitCollection *usys = unit_get_system(system, type);
  554. const bUnitDef *unit = NULL, *default_unit;
  555. double scale_pref_base = scale_pref;
  556. char str_tmp[TEMP_STR_SIZE];
  557. bool changed = false;
  558. if (usys == NULL || usys->units[0].name == NULL) {
  559. return changed;
  560. }
  561. /* make lowercase */
  562. BLI_str_tolower_ascii(str, len_max);
  563. /* Try to find a default unit from current or previous string. */
  564. default_unit = unit_detect_from_str(usys, str, str_prev);
  565. /* We apply the default unit to the whole expression (default unit is now the reference '1.0' one). */
  566. scale_pref_base *= default_unit->scalar;
  567. /* Apply the default unit on the whole expression, this allows to handle nasty cases like '2+2in'. */
  568. if (BLI_snprintf(str_tmp, sizeof(str_tmp), "(%s)*%.9g", str, default_unit->scalar) < sizeof(str_tmp)) {
  569. strncpy(str, str_tmp, len_max);
  570. }
  571. else {
  572. /* BLI_snprintf would not fit into str_tmp, cant do much in this case
  573. * check for this because otherwise bUnit_ReplaceString could call its self forever */
  574. return changed;
  575. }
  576. for (unit = usys->units; unit->name; unit++) {
  577. /* in case there are multiple instances */
  578. while (unit_replace(str, len_max, str_tmp, scale_pref_base, unit))
  579. changed = true;
  580. }
  581. unit = NULL;
  582. {
  583. /* try other unit systems now, so we can evaluate imperial when metric is set for eg. */
  584. /* Note that checking other systems at that point means we do not support their units as 'default' one.
  585. * In other words, when in metrics, typing '2+2in' will give 2 meters 2 inches, not 4 inches.
  586. * I do think this is the desired behavior!
  587. */
  588. const bUnitCollection *usys_iter;
  589. int system_iter;
  590. for (system_iter = 0; system_iter < UNIT_SYSTEM_TOT; system_iter++) {
  591. if (system_iter != system) {
  592. usys_iter = unit_get_system(system_iter, type);
  593. if (usys_iter) {
  594. for (unit = usys_iter->units; unit->name; unit++) {
  595. int ofs = 0;
  596. /* in case there are multiple instances */
  597. while ((ofs = unit_replace(str + ofs, len_max - ofs, str_tmp, scale_pref_base, unit)))
  598. changed = true;
  599. }
  600. }
  601. }
  602. }
  603. }
  604. unit = NULL;
  605. /* replace # with add sign when there is no operator between it and the next number
  606. *
  607. * "1*1# 3*100# * 3" -> "1*1+ 3*100 * 3"
  608. *
  609. * */
  610. {
  611. char *str_found = str;
  612. const char *ch = str;
  613. while ((str_found = strchr(str_found, SEP_CHR))) {
  614. bool op_found = false;
  615. /* any operators after this? */
  616. for (ch = str_found + 1; *ch != '\0'; ch++) {
  617. if (*ch == ' ' || *ch == '\t') {
  618. continue;
  619. }
  620. op_found = (ch_is_op(*ch) || ELEM(*ch, ',', ')'));
  621. break;
  622. }
  623. /* If found an op, comma or closing parenthesis, no need to insert a '+', else we need it. */
  624. *str_found++ = op_found ? ' ' : '+';
  625. }
  626. }
  627. return changed;
  628. }
  629. /* 45µm --> 45um */
  630. void bUnit_ToUnitAltName(char *str, int len_max, const char *orig_str, int system, int type)
  631. {
  632. const bUnitCollection *usys = unit_get_system(system, type);
  633. const bUnitDef *unit;
  634. /* find and substitute all units */
  635. for (unit = usys->units; unit->name; unit++) {
  636. if (len_max > 0 && unit->name_alt) {
  637. const char *found = unit_find_str(orig_str, unit->name_short);
  638. if (found) {
  639. int offset = (int)(found - orig_str);
  640. int len_name = 0;
  641. /* copy everything before the unit */
  642. offset = (offset < len_max ? offset : len_max);
  643. strncpy(str, orig_str, offset);
  644. str += offset;
  645. orig_str += offset + strlen(unit->name_short);
  646. len_max -= offset;
  647. /* print the alt_name */
  648. if (unit->name_alt)
  649. len_name = BLI_strncpy_rlen(str, unit->name_alt, len_max);
  650. else
  651. len_name = 0;
  652. len_name = (len_name < len_max ? len_name : len_max);
  653. str += len_name;
  654. len_max -= len_name;
  655. }
  656. }
  657. }
  658. /* finally copy the rest of the string */
  659. strncpy(str, orig_str, len_max);
  660. }
  661. double bUnit_ClosestScalar(double value, int system, int type)
  662. {
  663. const bUnitCollection *usys = unit_get_system(system, type);
  664. const bUnitDef *unit;
  665. if (usys == NULL)
  666. return -1;
  667. unit = unit_best_fit(value, usys, NULL, 1);
  668. if (unit == NULL)
  669. return -1;
  670. return unit->scalar;
  671. }
  672. double bUnit_BaseScalar(int system, int type)
  673. {
  674. const bUnitCollection *usys = unit_get_system(system, type);
  675. return unit_default(usys)->scalar;
  676. }
  677. /* external access */
  678. bool bUnit_IsValid(int system, int type)
  679. {
  680. return !(system < 0 || system > UNIT_SYSTEM_TOT || type < 0 || type > B_UNIT_TYPE_TOT);
  681. }
  682. void bUnit_GetSystem(int system, int type, void const **r_usys_pt, int *r_len)
  683. {
  684. const bUnitCollection *usys = unit_get_system(system, type);
  685. *r_usys_pt = usys;
  686. if (usys == NULL) {
  687. *r_len = 0;
  688. return;
  689. }
  690. *r_len = usys->length;
  691. }
  692. int bUnit_GetBaseUnit(const void *usys_pt)
  693. {
  694. return ((bUnitCollection *)usys_pt)->base_unit;
  695. }
  696. const char *bUnit_GetName(const void *usys_pt, int index)
  697. {
  698. return ((bUnitCollection *)usys_pt)->units[index].name;
  699. }
  700. const char *bUnit_GetNameDisplay(const void *usys_pt, int index)
  701. {
  702. return ((bUnitCollection *)usys_pt)->units[index].name_display;
  703. }
  704. double bUnit_GetScaler(const void *usys_pt, int index)
  705. {
  706. return ((bUnitCollection *)usys_pt)->units[index].scalar;
  707. }