3 * ***** BEGIN GPL LICENSE BLOCK *****
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * Contributor(s): Campbell Barton
21 * ***** END GPL LICENSE BLOCK *****
30 #define _USE_MATH_DEFINES
34 #include "BLI_winstuff.h"
37 #define TEMP_STR_SIZE 256
44 #define UN_SC_KM 1000.0f
45 #define UN_SC_HM 100.0f
46 #define UN_SC_DAM 10.0f
49 #define UN_SC_CM 0.01f
50 #define UN_SC_MM 0.001f
51 #define UN_SC_UM 0.000001f
53 #define UN_SC_MI 1609.344f
54 #define UN_SC_FUR 201.168f
55 #define UN_SC_CH 20.1168f
56 #define UN_SC_YD 0.9144f
57 #define UN_SC_FT 0.3048f
58 #define UN_SC_IN 0.0254f
59 #define UN_SC_MIL 0.0000254f
61 #define UN_SC_MTON 1000.0f /* metric ton */
62 #define UN_SC_QL 100.0f
65 #define UN_SC_DAG 0.01f
66 #define UN_SC_G 0.001f
68 #define UN_SC_ITON 907.18474f /* imperial ton */
69 #define UN_SC_CWT 45.359237f
70 #define UN_SC_ST 6.35029318f
71 #define UN_SC_LB 0.45359237f
72 #define UN_SC_OZ 0.028349523125f
74 /* define a single unit */
75 typedef struct bUnitDef {
77 char *name_plural; /* abused a bit for the display name */
78 char *name_short; /* this is used for display*/
79 char *name_alt; /* keyboard-friendly ASCII-only version of name_short, can be NULL */
80 /* if name_short has non-ASCII chars, name_alt should be present */
82 char *name_display; /* can be NULL */
85 double bias; /* not used yet, needed for converting temperature */
89 #define B_UNIT_DEF_NONE 0
90 #define B_UNIT_DEF_SUPPRESS 1 /* Use for units that are not used enough to be translated into for common use */
92 /* define a single unit */
93 typedef struct bUnitCollection {
94 struct bUnitDef *units;
95 int base_unit; /* basic unit index (when user desn't specify unit explicitly) */
96 int flag; /* options for this system */
97 int length; /* to quickly find the last item */
101 static struct bUnitDef buDummyDef[] = {
102 {"", NULL, "", NULL, NULL, 1.0, 0.0},
103 {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
105 static struct bUnitCollection buDummyCollecton = {buDummyDef, 0, 0, sizeof(buDummyDef)};
109 static struct bUnitDef buMetricLenDef[] = {
110 {"kilometer", "kilometers", "km", NULL, "Kilometers", UN_SC_KM, 0.0, B_UNIT_DEF_NONE},
111 {"hectometer", "hectometers", "hm", NULL, "100 Meters", UN_SC_HM, 0.0, B_UNIT_DEF_SUPPRESS},
112 {"dekameter", "dekameters", "dam",NULL, "10 Meters", UN_SC_DAM, 0.0, B_UNIT_DEF_SUPPRESS},
113 {"meter", "meters", "m", NULL, "Meters", UN_SC_M, 0.0, B_UNIT_DEF_NONE}, /* base unit */
114 {"decimetre", "decimetres", "dm", NULL, "10 Centimeters", UN_SC_DM, 0.0, B_UNIT_DEF_SUPPRESS},
115 {"centimeter", "centimeters", "cm", NULL, "Centimeters", UN_SC_CM, 0.0, B_UNIT_DEF_NONE},
116 {"millimeter", "millimeters", "mm", NULL, "Millimeters", UN_SC_MM, 0.0, B_UNIT_DEF_NONE},
117 {"micrometer", "micrometers", "µm", "um", "Micrometers", UN_SC_UM, 0.0, B_UNIT_DEF_NONE}, // micron too?
119 /* These get displayed because of float precision problems in the transform header,
120 * could work around, but for now probably people wont use these */
122 {"nanometer", "Nanometers", "nm", NULL, 0.000000001, 0.0, B_UNIT_DEF_NONE},
123 {"picometer", "Picometers", "pm", NULL, 0.000000000001, 0.0,B_UNIT_DEF_NONE},
125 {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
127 static struct bUnitCollection buMetricLenCollecton = {buMetricLenDef, 3, 0, sizeof(buMetricLenDef)/sizeof(bUnitDef)};
129 static struct bUnitDef buImperialLenDef[] = {
130 {"mile", "miles", "mi", "m", "Miles", UN_SC_MI, 0.0, B_UNIT_DEF_NONE},
131 {"furlong", "furlongs", "fur", NULL, "Furlongs",UN_SC_FUR, 0.0, B_UNIT_DEF_SUPPRESS},
132 {"chain", "chains", "ch", NULL, "Chains", UN_SC_CH, 0.0, B_UNIT_DEF_SUPPRESS},
133 {"yard", "yards", "yd", NULL, "Yards", UN_SC_YD, 0.0, B_UNIT_DEF_NONE},
134 {"foot", "feet", "'", "ft", "Feet", UN_SC_FT, 0.0, B_UNIT_DEF_NONE}, /* base unit */
135 {"inch", "inches", "\"", "in", "Inches", UN_SC_IN, 0.0, B_UNIT_DEF_NONE},
136 {"thou", "thous", "mil", NULL, "Thous", UN_SC_MIL, 0.0, B_UNIT_DEF_NONE},
137 {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
139 static struct bUnitCollection buImperialLenCollecton = {buImperialLenDef, 4, 0, sizeof(buImperialLenDef)/sizeof(bUnitDef)};
142 static struct bUnitDef buMetricAreaDef[] = {
143 {"square kilometer", "square kilometers", "km²", "km2", "Square Kilometers", UN_SC_KM*UN_SC_KM, 0.0, B_UNIT_DEF_NONE},
144 {"square hectometer","square hectometers", "hm²", "hm2", "Square Hectometers", UN_SC_HM*UN_SC_HM, 0.0, B_UNIT_DEF_NONE}, /* hectare */
145 {"square dekameter", "square dekameters", "dam²","dam2", "Square Dekameters", UN_SC_DAM*UN_SC_DAM, 0.0, B_UNIT_DEF_SUPPRESS}, /* are */
146 {"square meter", "square meters", "m²", "m2", "Square Meters", UN_SC_M*UN_SC_M, 0.0, B_UNIT_DEF_NONE}, /* base unit */
147 {"square decimetre", "square decimetres", "dm²", "dm2", "Square Decimetres", UN_SC_DM*UN_SC_DM, 0.0, B_UNIT_DEF_SUPPRESS},
148 {"square centimeter", "square centimeters", "cm²", "cm2", "Square Centimeters", UN_SC_CM*UN_SC_CM, 0.0, B_UNIT_DEF_NONE},
149 {"square millimeter", "square millimeters", "mm²", "mm2", "Square Millimeters", UN_SC_MM*UN_SC_MM, 0.0, B_UNIT_DEF_NONE},
150 {"square micrometer", "square micrometers", "µm²", "um2", "Square Micrometers", UN_SC_UM*UN_SC_UM, 0.0, B_UNIT_DEF_NONE},
151 {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
153 static struct bUnitCollection buMetricAreaCollecton = {buMetricAreaDef, 3, 0, sizeof(buMetricAreaDef)/sizeof(bUnitDef)};
155 static struct bUnitDef buImperialAreaDef[] = {
156 {"square mile", "square miles", "sq mi", "sq m","Square Miles", UN_SC_MI*UN_SC_MI, 0.0, B_UNIT_DEF_NONE},
157 {"square furlong", "square furlongs", "sq fur",NULL, "Square Furlongs", UN_SC_FUR*UN_SC_FUR, 0.0,B_UNIT_DEF_SUPPRESS},
158 {"square chain", "square chains", "sq ch", NULL, "Square Chains", UN_SC_CH*UN_SC_CH, 0.0, B_UNIT_DEF_SUPPRESS},
159 {"square yard", "square yards", "sq yd", NULL, "Square Yards", UN_SC_YD*UN_SC_YD, 0.0, B_UNIT_DEF_NONE},
160 {"square foot", "square feet", "sq ft", NULL, "Square Feet", UN_SC_FT*UN_SC_FT, 0.0, B_UNIT_DEF_NONE}, /* base unit */
161 {"square inch", "square inches", "sq in", NULL, "Square Inches", UN_SC_IN*UN_SC_IN, 0.0, B_UNIT_DEF_NONE},
162 {"square thou", "square thous", "sq mil",NULL, "Square Thous", UN_SC_MIL*UN_SC_MIL, 0.0, B_UNIT_DEF_NONE},
163 {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
165 static struct bUnitCollection buImperialAreaCollecton = {buImperialAreaDef, 4, 0, sizeof(buImperialAreaDef)/sizeof(bUnitDef)};
168 static struct bUnitDef buMetricVolDef[] = {
169 {"cubic kilometer", "cubic kilometers", "km³", "km3", "Cubic Kilometers", UN_SC_KM*UN_SC_KM*UN_SC_KM, 0.0, B_UNIT_DEF_NONE},
170 {"cubic hectometer","cubic hectometers", "hm³", "hm3", "Cubic Hectometers", UN_SC_HM*UN_SC_HM*UN_SC_HM, 0.0, B_UNIT_DEF_NONE},
171 {"cubic dekameter", "cubic dekameters", "dam³","dam3", "Cubic Dekameters", UN_SC_DAM*UN_SC_DAM*UN_SC_DAM, 0.0, B_UNIT_DEF_SUPPRESS},
172 {"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 */
173 {"cubic decimetre", "cubic decimetres", "dm³", "dm3", "Cubic Decimetres", UN_SC_DM*UN_SC_DM*UN_SC_DM, 0.0, B_UNIT_DEF_SUPPRESS},
174 {"cubic centimeter", "cubic centimeters", "cm³", "cm3", "Cubic Centimeters", UN_SC_CM*UN_SC_CM*UN_SC_CM, 0.0, B_UNIT_DEF_NONE},
175 {"cubic millimeter", "cubic millimeters", "mm³", "mm3", "Cubic Millimeters", UN_SC_MM*UN_SC_MM*UN_SC_MM, 0.0, B_UNIT_DEF_NONE},
176 {"cubic micrometer", "cubic micrometers", "µm³", "um3", "Cubic Micrometers", UN_SC_UM*UN_SC_UM*UN_SC_UM, 0.0, B_UNIT_DEF_NONE},
177 {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
179 static struct bUnitCollection buMetricVolCollecton = {buMetricVolDef, 3, 0, sizeof(buMetricVolDef)/sizeof(bUnitDef)};
181 static struct bUnitDef buImperialVolDef[] = {
182 {"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},
183 {"cubic furlong", "cubic furlongs", "cu fur",NULL, "Cubic Furlongs", UN_SC_FUR*UN_SC_FUR*UN_SC_FUR, 0.0,B_UNIT_DEF_SUPPRESS},
184 {"cubic chain", "cubic chains", "cu ch", NULL, "Cubic Chains", UN_SC_CH*UN_SC_CH*UN_SC_CH, 0.0, B_UNIT_DEF_SUPPRESS},
185 {"cubic yard", "cubic yards", "cu yd", NULL, "Cubic Yards", UN_SC_YD*UN_SC_YD*UN_SC_YD, 0.0, B_UNIT_DEF_NONE},
186 {"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 */
187 {"cubic inch", "cubic inches", "cu in", NULL, "Cubic Inches", UN_SC_IN*UN_SC_IN*UN_SC_IN, 0.0, B_UNIT_DEF_NONE},
188 {"cubic thou", "cubic thous", "cu mil",NULL, "Cubic Thous", UN_SC_MIL*UN_SC_MIL*UN_SC_MIL, 0.0, B_UNIT_DEF_NONE},
189 {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
191 static struct bUnitCollection buImperialVolCollecton = {buImperialVolDef, 4, 0, sizeof(buImperialVolDef)/sizeof(bUnitDef)};
194 static struct bUnitDef buMetricMassDef[] = {
195 {"ton", "tonnes", "ton", "t", "1000 Kilograms", UN_SC_MTON, 0.0, B_UNIT_DEF_NONE},
196 {"quintal", "quintals", "ql", "q", "100 Kilograms", UN_SC_QL, 0.0, B_UNIT_DEF_NONE},
197 {"kilogram", "kilograms", "kg", NULL, "Kilograms", UN_SC_KG, 0.0, B_UNIT_DEF_NONE}, /* base unit */
198 {"hectogram", "hectograms", "hg", NULL, "Hectograms", UN_SC_HG, 0.0, B_UNIT_DEF_NONE},
199 {"dekagram", "dekagrams", "dag",NULL, "10 Grams", UN_SC_DAG, 0.0, B_UNIT_DEF_SUPPRESS},
200 {"gram", "grams", "g", NULL, "Grams", UN_SC_G, 0.0, B_UNIT_DEF_NONE},
201 {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
203 static struct bUnitCollection buMetricMassCollecton = {buMetricMassDef, 2, 0, sizeof(buMetricMassDef)/sizeof(bUnitDef)};
205 static struct bUnitDef buImperialMassDef[] = {
206 {"ton", "tonnes", "ton", "t", "Tonnes", UN_SC_ITON, 0.0, B_UNIT_DEF_NONE},
207 {"centum weight", "centum weights", "cwt", NULL, "Centum weights", UN_SC_CWT, 0.0, B_UNIT_DEF_NONE},
208 {"stone", "stones", "st", NULL, "Stones", UN_SC_ST, 0.0, B_UNIT_DEF_NONE},
209 {"pound", "pounds", "lb", NULL, "Pounds", UN_SC_LB, 0.0, B_UNIT_DEF_NONE}, /* base unit */
210 {"ounce", "ounces", "oz", NULL, "Ounces", UN_SC_OZ, 0.0, B_UNIT_DEF_NONE},
211 {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
213 static struct bUnitCollection buImperialMassCollecton = {buImperialMassDef, 3, 0, sizeof(buImperialMassDef)/sizeof(bUnitDef)};
215 /* Even if user scales the system to a point where km^3 is used, velocity and
216 * acceleration aren't scaled: that's why we have so few units for them */
219 static struct bUnitDef buMetricVelDef[] = {
220 {"meter per second", "meters per second", "m/s", NULL, "Meters per second", UN_SC_M, 0.0, B_UNIT_DEF_NONE}, /* base unit */
221 {"kilometer per hour", "kilometers per hour", "km/h", NULL, "Kilometers per hour", UN_SC_KM/3600.0f, 0.0, B_UNIT_DEF_SUPPRESS},
222 {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
224 static struct bUnitCollection buMetricVelCollecton = {buMetricVelDef, 0, 0, sizeof(buMetricVelDef)/sizeof(bUnitDef)};
226 static struct bUnitDef buImperialVelDef[] = {
227 {"foot per second", "feet per second", "ft/s", "fps", "Feet per second", UN_SC_FT, 0.0, B_UNIT_DEF_NONE}, /* base unit */
228 {"mile per hour", "miles per hour", "mph", NULL, "Miles per hour", UN_SC_MI/3600.0f, 0.0,B_UNIT_DEF_SUPPRESS},
229 {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
231 static struct bUnitCollection buImperialVelCollecton = {buImperialVelDef, 0, 0, sizeof(buImperialVelDef)/sizeof(bUnitDef)};
234 static struct bUnitDef buMetricAclDef[] = {
235 {"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 */
236 {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
238 static struct bUnitCollection buMetricAclCollecton = {buMetricAclDef, 0, 0, sizeof(buMetricAclDef)/sizeof(bUnitDef)};
240 static struct bUnitDef buImperialAclDef[] = {
241 {"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 */
242 {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
244 static struct bUnitCollection buImperialAclCollecton = {buImperialAclDef, 0, 0, sizeof(buImperialAclDef)/sizeof(bUnitDef)};
247 static struct bUnitDef buNaturalTimeDef[] = {
248 /* weeks? - probably not needed for blender */
249 {"day", "days", "d", NULL, "Days", 90000.0, 0.0, B_UNIT_DEF_NONE},
250 {"hour", "hours", "hr", "h", "Hours", 3600.0, 0.0, B_UNIT_DEF_NONE},
251 {"minute", "minutes", "min", "m", "Minutes", 60.0, 0.0, B_UNIT_DEF_NONE},
252 {"second", "seconds", "sec", "s", "Seconds", 1.0, 0.0, B_UNIT_DEF_NONE}, /* base unit */
253 {"millisecond", "milliseconds", "ms", NULL, "Milliseconds", 0.001, 0.0 , B_UNIT_DEF_NONE},
254 {"microsecond", "microseconds", "µs", "us", "Microseconds", 0.000001, 0.0, B_UNIT_DEF_NONE},
255 {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
257 static struct bUnitCollection buNaturalTimeCollecton = {buNaturalTimeDef, 3, 0, sizeof(buNaturalTimeDef)/sizeof(bUnitDef)};
260 static struct bUnitDef buNaturalRotDef[] = {
261 {"degree", "degrees", "°", NULL, "Degrees", M_PI/180.0, 0.0, B_UNIT_DEF_NONE},
262 {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
264 static struct bUnitCollection buNaturalRotCollection = {buNaturalRotDef, 0, 0, sizeof(buNaturalRotDef)/sizeof(bUnitDef)};
266 #define UNIT_SYSTEM_TOT (((sizeof(bUnitSystems) / 9) / sizeof(void *)) - 1)
267 static struct bUnitCollection *bUnitSystems[][9] = {
268 {0, 0, 0, 0, 0, &buNaturalRotCollection, &buNaturalTimeCollecton, 0, 0},
269 {0, &buMetricLenCollecton, &buMetricAreaCollecton, &buMetricVolCollecton, &buMetricMassCollecton, &buNaturalRotCollection, &buNaturalTimeCollecton, &buMetricVelCollecton, &buMetricAclCollecton}, /* metric */
270 {0, &buImperialLenCollecton, &buImperialAreaCollecton, &buImperialVolCollecton, &buImperialMassCollecton, &buNaturalRotCollection, &buNaturalTimeCollecton, &buImperialVelCollecton, &buImperialAclCollecton}, /* imperial */
271 {0, 0, 0, 0, 0, 0, 0, 0, 0}
276 /* internal, has some option not exposed */
277 static bUnitCollection *unit_get_system(int system, int type)
279 return bUnitSystems[system][type]; /* select system to use, metric/imperial/other? */
282 static bUnitDef *unit_default(bUnitCollection *usys)
284 return &usys->units[usys->base_unit];
287 static bUnitDef *unit_best_fit(double value, bUnitCollection *usys, bUnitDef *unit_start, int suppress)
290 double value_abs= value>0.0?value:-value;
292 for(unit= unit_start ? unit_start:usys->units; unit->name; unit++) {
294 if(suppress && (unit->flag & B_UNIT_DEF_SUPPRESS))
297 if (value_abs >= unit->scalar*(1.0-EPS)) /* scale down scalar so 1cm doesnt convert to 10mm because of float error */
301 return unit_default(usys);
306 /* convert into 2 units and 2 values for "2ft, 3inch" syntax */
307 static void unit_dual_convert(double value, bUnitCollection *usys,
308 bUnitDef **unit_a, bUnitDef **unit_b, double *value_a, double *value_b)
310 bUnitDef *unit= unit_best_fit(value, usys, NULL, 1);
312 *value_a= (value < 0.0 ? ceil:floor)(value/unit->scalar) * unit->scalar;
313 *value_b= value - (*value_a);
316 *unit_b= unit_best_fit(*value_b, usys, *unit_a, 1);
319 static int unit_as_string(char *str, int len_max, double value, int prec, bUnitCollection *usys,
320 /* non exposed options */
321 bUnitDef *unit, char pad)
327 /* use unit without finding the best one */
329 else if(value == 0.0) {
330 /* use the default units since there is no way to convert */
331 unit= unit_default(usys);
334 unit= unit_best_fit(value, usys, NULL, 1);
337 value_conv= value/unit->scalar;
339 /* Convert to a string */
341 char conv_str[6] = {'%', '.', '0'+prec, 'l', 'f', '\0'}; /* "%.2lf" when prec is 2, must be under 10 */
342 len= snprintf(str, len_max, conv_str, (float)value_conv);
348 /* Add unit prefix and strip zeros */
350 /* replace trailing zero's with spaces
351 * so the number is less complicated but allignment in a button wont
352 * jump about while dragging */
355 while(i>0 && str[i]=='0') { /* 4.300 -> 4.3 */
359 if(i>0 && str[i]=='.') { /* 10. -> 10 */
363 /* Now add the suffix */
367 while(unit->name_short[j] && (i < len_max)) {
368 str[i++]= unit->name_short[j++];
372 /* this loop only runs if so many zeros were removed that
373 * the unit name only used padded chars,
374 * In that case add padding for the name. */
376 while(i<=len+j && (i < len_max)) {
382 /* terminate no matter whats done with padding above */
391 /* Used for drawing number buttons, try keep fast */
392 void bUnit_AsString(char *str, int len_max, double value, int prec, int system, int type, int split, int pad)
394 bUnitCollection *usys = unit_get_system(system, type);
396 if(usys==NULL || usys->units[0].name==NULL)
397 usys= &buDummyCollecton;
401 bUnitDef *unit_a, *unit_b;
402 double value_a, value_b;
404 unit_dual_convert(value, usys, &unit_a, &unit_b, &value_a, &value_b);
406 /* check the 2 is a smaller unit */
407 if(unit_b > unit_a) {
408 i= unit_as_string(str, len_max, value_a, prec, usys, unit_a, '\0');
410 /* is there enough space for at least 1 char of the next unit? */
414 /* use low precision since this is a smaller unit */
415 unit_as_string(str+i, len_max-i, value_b, prec?1:0, usys, unit_b, '\0');
421 unit_as_string(str, len_max, value, prec, usys, NULL, pad?' ':'\0');
425 static char *unit_find_str(char *str, char *substr)
429 if(substr && substr[0] != '\0') {
430 str_found= strstr(str, substr);
432 /* previous char cannot be a letter */
433 if (str_found == str || isalpha(*(str_found-1))==0) {
434 /* next char cannot be alphanum */
435 int len_name = strlen(substr);
437 if (!isalpha(*(str_found+len_name))) {
448 /* Note that numbers are added within brackets
449 * ") " - is used to detect numbers we added so we can detect if commas need to be added
451 * "1m1cm+2mm" - Original value
452 * "1*1#1*0.01#+2*0.001#" - Replace numbers
453 * "1*1,1*0.01 +2*0.001 " - Add comma's if ( - + * / % ^ < > ) not found in between
457 /* not too strict, (- = * /) are most common */
458 static int ch_is_op(char op)
480 static int unit_scale_str(char *str, int len_max, char *str_tmp, double scale_pref, bUnitDef *unit, char *replace_str)
484 if((len_max>0) && (str_found= unit_find_str(str, replace_str))) { /* XXX - investigate, does not respect len_max properly */
485 int len, len_num, len_name, len_move, found_ofs;
487 found_ofs = (int)(str_found-str);
491 len_name = strlen(replace_str);
492 len_move= (len - (found_ofs+len_name)) + 1; /* 1+ to copy the string terminator */
493 len_num= snprintf(str_tmp, TEMP_STR_SIZE, "*%lg"SEP_STR, unit->scalar/scale_pref); /* # removed later */
495 if(len_num > len_max)
498 if(found_ofs+len_num+len_move > len_max) {
499 /* can't move the whole string, move just as much as will fit */
500 len_move -= (found_ofs+len_num+len_move) - len_max;
504 /* resize the last part of the string */
505 memmove(str_found+len_num, str_found+len_name, len_move); /* may grow or shrink the string */
508 if(found_ofs+len_num > len_max) {
509 /* not even the number will fit into the string, only copy part of it */
510 len_num -= (found_ofs+len_num) - len_max;
514 /* its possible none of the number could be copied in */
515 memcpy(str_found, str_tmp, len_num); /* without the string terminator */
518 /* since the null terminator wont be moved if the stringlen_max
519 * was not long enough to fit everything in it */
520 str[len_max-1]= '\0';
521 return found_ofs + len_num;
526 static int unit_replace(char *str, int len_max, char *str_tmp, double scale_pref, bUnitDef *unit)
529 ofs += unit_scale_str(str+ofs, len_max-ofs, str_tmp, scale_pref, unit, unit->name_short);
530 ofs += unit_scale_str(str+ofs, len_max-ofs, str_tmp, scale_pref, unit, unit->name_plural);
531 ofs += unit_scale_str(str+ofs, len_max-ofs, str_tmp, scale_pref, unit, unit->name_alt);
532 ofs += unit_scale_str(str+ofs, len_max-ofs, str_tmp, scale_pref, unit, unit->name);
536 static int unit_find(char *str, bUnitDef *unit)
538 if (unit_find_str(str, unit->name_short)) return 1;
539 if (unit_find_str(str, unit->name_plural)) return 1;
540 if (unit_find_str(str, unit->name_alt)) return 1;
541 if (unit_find_str(str, unit->name)) return 1;
546 /* make a copy of the string that replaces the units with numbers
547 * this is used before parsing
548 * This is only used when evaluating user input and can afford to be a bit slower
550 * This is to be used before python evaluation so..
551 * 10.1km -> 10.1*1000.0
552 * ...will be resolved by python.
554 * values will be split by a comma's
555 * 5'2" -> 5'0.0254, 2*0.3048
557 * str_prev is optional, when valid it is used to get a base unit when none is set.
559 * return true of a change was made.
561 int bUnit_ReplaceString(char *str, int len_max, char *str_prev, double scale_pref, int system, int type)
563 bUnitCollection *usys = unit_get_system(system, type);
566 char str_tmp[TEMP_STR_SIZE];
569 if(usys==NULL || usys->units[0].name==NULL) {
574 { /* make lowercase */
578 for(i=0; (i>=len_max || *ch=='\0'); i++, ch++)
579 if((*ch>='A') && (*ch<='Z'))
584 for(unit= usys->units; unit->name; unit++) {
586 if(unit->flag & B_UNIT_DEF_SUPPRESS)
589 /* incase there are multiple instances */
590 while(unit_replace(str, len_max, str_tmp, scale_pref, unit))
596 /* try other unit systems now, so we can evaluate imperial when metric is set for eg. */
597 bUnitCollection *usys_iter;
600 for(system_iter= 0; system_iter<UNIT_SYSTEM_TOT; system_iter++) {
601 if (system_iter != system) {
602 usys_iter= unit_get_system(system_iter, type);
604 for(unit= usys_iter->units; unit->name; unit++) {
606 if((unit->flag & B_UNIT_DEF_SUPPRESS) == 0) {
608 /* incase there are multiple instances */
609 while((ofs=unit_replace(str+ofs, len_max-ofs, str_tmp, scale_pref, unit)))
620 /* no units given so infer a unit from the previous string or default */
622 /* see which units the original value had */
623 for(unit= usys->units; unit->name; unit++) {
625 if(unit->flag & B_UNIT_DEF_SUPPRESS)
628 if (unit_find(str_prev, unit))
633 if(unit==NULL || unit->name == NULL)
634 unit= unit_default(usys);
637 /* add the unit prefix and re-run, use brackets incase there was an expression given */
638 if(snprintf(str_tmp, sizeof(str_tmp), "(%s)%s", str, unit->name) < sizeof(str_tmp)) {
639 strncpy(str, str_tmp, len_max);
640 return bUnit_ReplaceString(str, len_max, NULL, scale_pref, system, type);
643 /* snprintf would not fit into str_tmp, cant do much in this case
644 * check for this because otherwise bUnit_ReplaceString could call its self forever */
650 /* replace # with commas when there is no operator between it and the next number
652 * "1*1# 3*100# * 3" -> "1 *1, 3 *100 * 3"
656 char *str_found= str;
659 while((str_found= strchr(str_found, SEP_CHR))) {
662 /* any operators after this?*/
663 for(ch= str_found+1; *ch!='\0'; ch++) {
665 if(*ch==' ' || *ch=='\t') {
668 else if (ch_is_op(*ch) || *ch==',') { /* found an op, no need to insert a ,*/
672 else { /* found a non-op character */
678 *str_found++ = op_found ? ' ':',';
686 void bUnit_ToUnitAltName(char *str, int len_max, char *orig_str, int system, int type)
688 bUnitCollection *usys = unit_get_system(system, type);
691 bUnitDef *unit_def= unit_default(usys);
693 /* find and substitute all units */
694 for(unit= usys->units; unit->name; unit++) {
695 if(len_max > 0 && (unit->name_alt || unit == unit_def))
699 found= unit_find_str(orig_str, unit->name_short);
701 int offset= found - orig_str;
704 /* copy everything before the unit */
705 offset= (offset<len_max? offset: len_max);
706 strncpy(str, orig_str, offset);
709 orig_str+= offset + strlen(unit->name_short);
712 /* print the alt_name */
714 len_name= snprintf(str, len_max, "%s", unit->name_alt);
718 len_name= (len_name<len_max? len_name: len_max);
725 /* finally copy the rest of the string */
726 strncpy(str, orig_str, len_max);
729 double bUnit_ClosestScalar(double value, int system, int type)
731 bUnitCollection *usys = unit_get_system(system, type);
737 unit= unit_best_fit(value, usys, NULL, 1);
744 double bUnit_BaseScalar(int system, int type)
746 bUnitCollection *usys = unit_get_system(system, type);
747 return unit_default(usys)->scalar;
750 /* external access */
751 int bUnit_IsValid(int system, int type)
753 return !(type < 0 || type >= B_UNIT_MAXDEF || system < 0 || system > UNIT_SYSTEM_TOT);
757 void bUnit_GetSystem(void **usys_pt, int *len, int system, int type)
759 bUnitCollection *usys = unit_get_system(system, type);
770 char *bUnit_GetName(void *usys_pt, int index)
772 return ((bUnitCollection *)usys_pt)->units[index].name;
774 char *bUnit_GetNameDisplay(void *usys_pt, int index)
776 return ((bUnitCollection *)usys_pt)->units[index].name_display;
779 double bUnit_GetScaler(void *usys_pt, int index)
781 return ((bUnitCollection *)usys_pt)->units[index].scalar;