Blender  V2.59
unit.c
Go to the documentation of this file.
00001 /*
00002  * $Id: unit.c 39297 2011-08-11 08:24:56Z campbellbarton $
00003  *
00004  * ***** BEGIN GPL LICENSE BLOCK *****
00005  *
00006  * This program is free software; you can redistribute it and/or
00007  * modify it under the terms of the GNU General Public License
00008  * as published by the Free Software Foundation; either version 2
00009  * of the License, or (at your option) any later version.
00010  *
00011  * This program is distributed in the hope that it will be useful,
00012  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00013  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00014  * GNU General Public License for more details.
00015  *
00016  * You should have received a copy of the GNU General Public License
00017  * along with this program; if not, write to the Free Software Foundation,
00018  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
00019  *
00020  * Contributor(s): Campbell Barton
00021  *
00022  * ***** END GPL LICENSE BLOCK *****
00023  */
00024 
00029 #include <stdlib.h>
00030 #include <stdio.h>
00031 #include <ctype.h>
00032 #include <string.h>
00033 #include <assert.h>
00034 #include "BKE_unit.h"
00035 
00036 #include "BLI_math.h"
00037 #include "BLI_winstuff.h"
00038 
00039 
00040 #define TEMP_STR_SIZE 256
00041 
00042 #define SEP_CHR         '#'
00043 #define SEP_STR         "#"
00044 
00045 #define EPS 0.00001
00046 
00047 #define UN_SC_KM        1000.0f
00048 #define UN_SC_HM        100.0f
00049 #define UN_SC_DAM       10.0f
00050 #define UN_SC_M         1.0f
00051 #define UN_SC_DM        0.1f
00052 #define UN_SC_CM        0.01f
00053 #define UN_SC_MM        0.001f
00054 #define UN_SC_UM        0.000001f
00055 
00056 #define UN_SC_MI        1609.344f
00057 #define UN_SC_FUR       201.168f
00058 #define UN_SC_CH        20.1168f
00059 #define UN_SC_YD        0.9144f
00060 #define UN_SC_FT        0.3048f
00061 #define UN_SC_IN        0.0254f
00062 #define UN_SC_MIL       0.0000254f
00063 
00064 #define UN_SC_MTON      1000.0f /* metric ton */
00065 #define UN_SC_QL        100.0f
00066 #define UN_SC_KG        1.0f
00067 #define UN_SC_HG        0.1f
00068 #define UN_SC_DAG       0.01f
00069 #define UN_SC_G         0.001f
00070 
00071 #define UN_SC_ITON      907.18474f /* imperial ton */
00072 #define UN_SC_CWT       45.359237f
00073 #define UN_SC_ST        6.35029318f
00074 #define UN_SC_LB        0.45359237f
00075 #define UN_SC_OZ        0.028349523125f
00076 
00077 /* define a single unit */
00078 typedef struct bUnitDef {
00079         const char *name;
00080         const char *name_plural;        /* abused a bit for the display name */
00081         const char *name_short; /* this is used for display*/
00082         const char *name_alt;           /* keyboard-friendly ASCII-only version of name_short, can be NULL */
00083                                                 /* if name_short has non-ASCII chars, name_alt should be present */
00084         
00085         const char *name_display;               /* can be NULL */
00086 
00087         double scalar;
00088         double bias;            /* not used yet, needed for converting temperature */
00089         int flag;
00090 } bUnitDef;
00091 
00092 #define B_UNIT_DEF_NONE 0
00093 #define B_UNIT_DEF_SUPPRESS 1 /* Use for units that are not used enough to be translated into for common use */
00094 
00095 /* define a single unit */
00096 typedef struct bUnitCollection {
00097         struct bUnitDef *units;
00098         int base_unit;                          /* basic unit index (when user doesn't specify unit explicitly) */
00099         int flag;                                       /* options for this system */
00100         int length;                                     /* to quickly find the last item */
00101 } bUnitCollection;
00102 
00103 /* Dummy */
00104 static struct bUnitDef buDummyDef[] = {
00105         {"",    NULL, "",       NULL, NULL, 1.0, 0.0},
00106         {NULL,  NULL, NULL,     NULL, NULL, 0.0, 0.0}
00107 };
00108 static struct bUnitCollection buDummyCollecton = {buDummyDef, 0, 0, sizeof(buDummyDef)};
00109 
00110 
00111 /* Lengths */
00112 static struct bUnitDef buMetricLenDef[] = {
00113         {"kilometer", "kilometers",             "km", NULL,     "Kilometers", UN_SC_KM, 0.0,    B_UNIT_DEF_NONE},
00114         {"hectometer", "hectometers",   "hm", NULL,     "100 Meters", UN_SC_HM, 0.0,    B_UNIT_DEF_SUPPRESS},
00115         {"dekameter", "dekameters",             "dam",NULL,     "10 Meters",  UN_SC_DAM, 0.0,   B_UNIT_DEF_SUPPRESS},
00116         {"meter", "meters",                             "m",  NULL,     "Meters",     UN_SC_M, 0.0,     B_UNIT_DEF_NONE}, /* base unit */
00117         {"decimetre", "decimetres",             "dm", NULL,     "10 Centimeters", UN_SC_DM, 0.0,        B_UNIT_DEF_SUPPRESS},
00118         {"centimeter", "centimeters",   "cm", NULL,     "Centimeters", UN_SC_CM, 0.0,   B_UNIT_DEF_NONE},
00119         {"millimeter", "millimeters",   "mm", NULL,     "Millimeters", UN_SC_MM, 0.0,   B_UNIT_DEF_NONE},
00120         {"micrometer", "micrometers",   "µm", "um",    "Micrometers", UN_SC_UM, 0.0,   B_UNIT_DEF_NONE}, // micron too?
00121 
00122         /* These get displayed because of float precision problems in the transform header,
00123          * could work around, but for now probably people wont use these */
00124         /*
00125         {"nanometer", "Nanometers",             "nm", NULL,     0.000000001, 0.0,       B_UNIT_DEF_NONE},
00126         {"picometer", "Picometers",             "pm", NULL,     0.000000000001, 0.0,B_UNIT_DEF_NONE},
00127         */
00128         {NULL, NULL, NULL,      NULL, NULL, 0.0, 0.0}
00129 };
00130 static struct bUnitCollection buMetricLenCollecton = {buMetricLenDef, 3, 0, sizeof(buMetricLenDef)/sizeof(bUnitDef)};
00131 
00132 static struct bUnitDef buImperialLenDef[] = {
00133         {"mile", "miles",               "mi", "m", "Miles",             UN_SC_MI, 0.0,  B_UNIT_DEF_NONE},
00134         {"furlong", "furlongs", "fur", NULL, "Furlongs",UN_SC_FUR, 0.0, B_UNIT_DEF_SUPPRESS},
00135         {"chain", "chains",             "ch", NULL, "Chains",   UN_SC_CH, 0.0,  B_UNIT_DEF_SUPPRESS},
00136         {"yard", "yards",               "yd", NULL, "Yards",    UN_SC_YD, 0.0,  B_UNIT_DEF_NONE},
00137         {"foot", "feet",                "'", "ft", "Feet",              UN_SC_FT, 0.0,  B_UNIT_DEF_NONE}, /* base unit */
00138         {"inch", "inches",              "\"", "in", "Inches",   UN_SC_IN, 0.0,  B_UNIT_DEF_NONE},
00139         {"thou", "thou",                "thou", "mil", "Thou",  UN_SC_MIL, 0.0, B_UNIT_DEF_NONE}, /* plural for thou has no 's' */
00140         {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
00141 };
00142 static struct bUnitCollection buImperialLenCollecton = {buImperialLenDef, 4, 0, sizeof(buImperialLenDef)/sizeof(bUnitDef)};
00143 
00144 /* Areas */
00145 static struct bUnitDef buMetricAreaDef[] = {
00146         {"square kilometer", "square kilometers",       "km²", "km2",  "Square Kilometers", UN_SC_KM*UN_SC_KM, 0.0,    B_UNIT_DEF_NONE},
00147         {"square hectometer","square hectometers",      "hm²", "hm2",  "Square Hectometers", UN_SC_HM*UN_SC_HM, 0.0,   B_UNIT_DEF_NONE}, /* hectare */
00148         {"square dekameter", "square dekameters",       "dam²","dam2", "Square Dekameters", UN_SC_DAM*UN_SC_DAM, 0.0,  B_UNIT_DEF_SUPPRESS}, /* are */
00149         {"square meter", "square meters",                       "m²",  "m2",   "Square Meters", UN_SC_M*UN_SC_M, 0.0,                  B_UNIT_DEF_NONE}, /* base unit */
00150         {"square decimetre", "square decimetres",       "dm²", "dm2",  "Square Decimetres", UN_SC_DM*UN_SC_DM, 0.0,    B_UNIT_DEF_SUPPRESS},
00151         {"square centimeter", "square centimeters",     "cm²", "cm2",  "Square Centimeters", UN_SC_CM*UN_SC_CM, 0.0,   B_UNIT_DEF_NONE},
00152         {"square millimeter", "square millimeters",     "mm²", "mm2",  "Square Millimeters", UN_SC_MM*UN_SC_MM, 0.0,   B_UNIT_DEF_NONE},
00153         {"square micrometer", "square micrometers",     "µm²", "um2", "Square Micrometers", UN_SC_UM*UN_SC_UM, 0.0,   B_UNIT_DEF_NONE},
00154         {NULL, NULL, NULL,      NULL, NULL, 0.0, 0.0}
00155 };
00156 static struct bUnitCollection buMetricAreaCollecton = {buMetricAreaDef, 3, 0, sizeof(buMetricAreaDef)/sizeof(bUnitDef)};
00157 
00158 static struct bUnitDef buImperialAreaDef[] = {
00159         {"square mile", "square miles",                 "sq mi", "sq m","Square Miles", UN_SC_MI*UN_SC_MI, 0.0,         B_UNIT_DEF_NONE},
00160         {"square furlong", "square furlongs",   "sq fur",NULL,  "Square Furlongs", UN_SC_FUR*UN_SC_FUR, 0.0,B_UNIT_DEF_SUPPRESS},
00161         {"square chain", "square chains",               "sq ch", NULL,  "Square Chains", UN_SC_CH*UN_SC_CH, 0.0,        B_UNIT_DEF_SUPPRESS},
00162         {"square yard", "square yards",                 "sq yd", NULL,  "Square Yards", UN_SC_YD*UN_SC_YD, 0.0,         B_UNIT_DEF_NONE},
00163         {"square foot", "square feet",                  "sq ft", NULL,  "Square Feet", UN_SC_FT*UN_SC_FT, 0.0,          B_UNIT_DEF_NONE}, /* base unit */
00164         {"square inch", "square inches",                "sq in", NULL,  "Square Inches", UN_SC_IN*UN_SC_IN, 0.0,        B_UNIT_DEF_NONE},
00165         {"square thou", "square thous",                 "sq mil",NULL,  "Square Thous", UN_SC_MIL*UN_SC_MIL, 0.0,       B_UNIT_DEF_NONE},
00166         {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
00167 };
00168 static struct bUnitCollection buImperialAreaCollecton = {buImperialAreaDef, 4, 0, sizeof(buImperialAreaDef)/sizeof(bUnitDef)};
00169 
00170 /* Volumes */
00171 static struct bUnitDef buMetricVolDef[] = {
00172         {"cubic kilometer", "cubic kilometers",         "km³", "km3",  "Cubic Kilometers", UN_SC_KM*UN_SC_KM*UN_SC_KM, 0.0,    B_UNIT_DEF_NONE},
00173         {"cubic hectometer","cubic hectometers",        "hm³", "hm3",  "Cubic Hectometers", UN_SC_HM*UN_SC_HM*UN_SC_HM, 0.0,   B_UNIT_DEF_NONE},
00174         {"cubic dekameter", "cubic dekameters",         "dam³","dam3", "Cubic Dekameters", UN_SC_DAM*UN_SC_DAM*UN_SC_DAM, 0.0, B_UNIT_DEF_SUPPRESS},
00175         {"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 */
00176         {"cubic decimetre", "cubic decimetres",         "dm³", "dm3",  "Cubic Decimetres", UN_SC_DM*UN_SC_DM*UN_SC_DM, 0.0,    B_UNIT_DEF_SUPPRESS},
00177         {"cubic centimeter", "cubic centimeters",       "cm³", "cm3",  "Cubic Centimeters", UN_SC_CM*UN_SC_CM*UN_SC_CM, 0.0,   B_UNIT_DEF_NONE},
00178         {"cubic millimeter", "cubic millimeters",       "mm³", "mm3",  "Cubic Millimeters", UN_SC_MM*UN_SC_MM*UN_SC_MM, 0.0,   B_UNIT_DEF_NONE},
00179         {"cubic micrometer", "cubic micrometers",       "µm³", "um3", "Cubic Micrometers", UN_SC_UM*UN_SC_UM*UN_SC_UM, 0.0,   B_UNIT_DEF_NONE},
00180         {NULL, NULL, NULL,      NULL, NULL, 0.0, 0.0}
00181 };
00182 static struct bUnitCollection buMetricVolCollecton = {buMetricVolDef, 3, 0, sizeof(buMetricVolDef)/sizeof(bUnitDef)};
00183 
00184 static struct bUnitDef buImperialVolDef[] = {
00185         {"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},
00186         {"cubic furlong", "cubic furlongs",     "cu fur",NULL,  "Cubic Furlongs", UN_SC_FUR*UN_SC_FUR*UN_SC_FUR, 0.0,B_UNIT_DEF_SUPPRESS},
00187         {"cubic chain", "cubic chains",         "cu ch", NULL,  "Cubic Chains", UN_SC_CH*UN_SC_CH*UN_SC_CH, 0.0,        B_UNIT_DEF_SUPPRESS},
00188         {"cubic yard", "cubic yards",           "cu yd", NULL,  "Cubic Yards", UN_SC_YD*UN_SC_YD*UN_SC_YD, 0.0,         B_UNIT_DEF_NONE},
00189         {"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 */
00190         {"cubic inch", "cubic inches",          "cu in", NULL,  "Cubic Inches", UN_SC_IN*UN_SC_IN*UN_SC_IN, 0.0,        B_UNIT_DEF_NONE},
00191         {"cubic thou", "cubic thous",           "cu mil",NULL,  "Cubic Thous", UN_SC_MIL*UN_SC_MIL*UN_SC_MIL, 0.0,      B_UNIT_DEF_NONE},
00192         {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
00193 };
00194 static struct bUnitCollection buImperialVolCollecton = {buImperialVolDef, 4, 0, sizeof(buImperialVolDef)/sizeof(bUnitDef)};
00195 
00196 /* Mass */
00197 static struct bUnitDef buMetricMassDef[] = {
00198         {"ton", "tonnes",                       "ton", "t", "1000 Kilograms", UN_SC_MTON, 0.0,  B_UNIT_DEF_NONE},
00199         {"quintal", "quintals",         "ql", "q",      "100 Kilograms", UN_SC_QL, 0.0,         B_UNIT_DEF_NONE},
00200         {"kilogram", "kilograms",       "kg", NULL,     "Kilograms", UN_SC_KG, 0.0,                     B_UNIT_DEF_NONE}, /* base unit */
00201         {"hectogram", "hectograms",     "hg", NULL,     "Hectograms", UN_SC_HG, 0.0,            B_UNIT_DEF_NONE},
00202         {"dekagram", "dekagrams",       "dag",NULL,     "10 Grams", UN_SC_DAG, 0.0,                     B_UNIT_DEF_SUPPRESS},
00203         {"gram", "grams",                       "g",  NULL,     "Grams", UN_SC_G, 0.0,                          B_UNIT_DEF_NONE},
00204         {NULL, NULL, NULL,      NULL, NULL, 0.0, 0.0}
00205 };
00206 static struct bUnitCollection buMetricMassCollecton = {buMetricMassDef, 2, 0, sizeof(buMetricMassDef)/sizeof(bUnitDef)};
00207 
00208 static struct bUnitDef buImperialMassDef[] = {
00209         {"ton", "tonnes",       "ton", "t",     "Tonnes", UN_SC_ITON, 0.0,              B_UNIT_DEF_NONE},
00210         {"centum weight", "centum weights", "cwt", NULL, "Centum weights", UN_SC_CWT, 0.0, B_UNIT_DEF_NONE},
00211         {"stone", "stones",     "st", NULL,             "Stones", UN_SC_ST, 0.0,        B_UNIT_DEF_NONE},
00212         {"pound", "pounds",     "lb", NULL,             "Pounds", UN_SC_LB, 0.0,        B_UNIT_DEF_NONE}, /* base unit */
00213         {"ounce", "ounces",     "oz", NULL,             "Ounces", UN_SC_OZ, 0.0,        B_UNIT_DEF_NONE},
00214         {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
00215 };
00216 static struct bUnitCollection buImperialMassCollecton = {buImperialMassDef, 3, 0, sizeof(buImperialMassDef)/sizeof(bUnitDef)};
00217 
00218 /* Even if user scales the system to a point where km^3 is used, velocity and
00219  * acceleration aren't scaled: that's why we have so few units for them */
00220 
00221 /* Velocity */
00222 static struct bUnitDef buMetricVelDef[] = {
00223         {"meter per second", "meters per second",               "m/s",  NULL,   "Meters per second", UN_SC_M, 0.0,                        B_UNIT_DEF_NONE}, /* base unit */
00224         {"kilometer per hour", "kilometers per hour",   "km/h", NULL,   "Kilometers per hour", UN_SC_KM/3600.0f, 0.0, B_UNIT_DEF_SUPPRESS},
00225         {NULL, NULL, NULL,      NULL, NULL, 0.0, 0.0}
00226 };
00227 static struct bUnitCollection buMetricVelCollecton = {buMetricVelDef, 0, 0, sizeof(buMetricVelDef)/sizeof(bUnitDef)};
00228 
00229 static struct bUnitDef buImperialVelDef[] = {
00230         {"foot per second", "feet per second",  "ft/s", "fps",  "Feet per second", UN_SC_FT, 0.0,               B_UNIT_DEF_NONE}, /* base unit */
00231         {"mile per hour", "miles per hour",             "mph", NULL,    "Miles per hour", UN_SC_MI/3600.0f, 0.0,B_UNIT_DEF_SUPPRESS},
00232         {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
00233 };
00234 static struct bUnitCollection buImperialVelCollecton = {buImperialVelDef, 0, 0, sizeof(buImperialVelDef)/sizeof(bUnitDef)};
00235 
00236 /* Acceleration */
00237 static struct bUnitDef buMetricAclDef[] = {
00238         {"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 */
00239         {NULL, NULL, NULL,      NULL, NULL, 0.0, 0.0}
00240 };
00241 static struct bUnitCollection buMetricAclCollecton = {buMetricAclDef, 0, 0, sizeof(buMetricAclDef)/sizeof(bUnitDef)};
00242 
00243 static struct bUnitDef buImperialAclDef[] = {
00244         {"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 */
00245         {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
00246 };
00247 static struct bUnitCollection buImperialAclCollecton = {buImperialAclDef, 0, 0, sizeof(buImperialAclDef)/sizeof(bUnitDef)};
00248 
00249 /* Time */
00250 static struct bUnitDef buNaturalTimeDef[] = {
00251         /* weeks? - probably not needed for blender */
00252         {"day", "days",                                 "d", NULL,      "Days",                 90000.0, 0.0,   B_UNIT_DEF_NONE},
00253         {"hour", "hours",                               "hr", "h",      "Hours",                3600.0, 0.0,    B_UNIT_DEF_NONE},
00254         {"minute", "minutes",                   "min", "m",     "Minutes",              60.0, 0.0,              B_UNIT_DEF_NONE},
00255         {"second", "seconds",                   "sec", "s",     "Seconds",              1.0, 0.0,               B_UNIT_DEF_NONE}, /* base unit */
00256         {"millisecond", "milliseconds", "ms", NULL,     "Milliseconds", 0.001, 0.0      ,       B_UNIT_DEF_NONE},
00257         {"microsecond", "microseconds", "µs", "us",    "Microseconds", 0.000001, 0.0,  B_UNIT_DEF_NONE},
00258         {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
00259 };
00260 static struct bUnitCollection buNaturalTimeCollecton = {buNaturalTimeDef, 3, 0, sizeof(buNaturalTimeDef)/sizeof(bUnitDef)};
00261 
00262 
00263 static struct bUnitDef buNaturalRotDef[] = {
00264         {"degree", "degrees",                   "°", NULL, "Degrees",          M_PI/180.0, 0.0,        B_UNIT_DEF_NONE},
00265 //      {"radian", "radians",                   "r", NULL, "Radians",           1.0, 0.0,                       B_UNIT_DEF_NONE},
00266 //      {"turn", "turns",                               "t", NULL, "Turns",                     1.0/(M_PI*2.0), 0.0,B_UNIT_DEF_NONE},
00267         {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0}
00268 };
00269 static struct bUnitCollection buNaturalRotCollection = {buNaturalRotDef, 0, 0, sizeof(buNaturalRotDef)/sizeof(bUnitDef)};
00270 
00271 #define UNIT_SYSTEM_TOT (((sizeof(bUnitSystems) / 9) / sizeof(void *)) - 1)
00272 static struct bUnitCollection *bUnitSystems[][9] = {
00273         {NULL, NULL, NULL, NULL, NULL, &buNaturalRotCollection, &buNaturalTimeCollecton, NULL, NULL},
00274         {NULL, &buMetricLenCollecton, &buMetricAreaCollecton, &buMetricVolCollecton, &buMetricMassCollecton, &buNaturalRotCollection, &buNaturalTimeCollecton, &buMetricVelCollecton, &buMetricAclCollecton}, /* metric */
00275         {NULL, &buImperialLenCollecton, &buImperialAreaCollecton, &buImperialVolCollecton, &buImperialMassCollecton, &buNaturalRotCollection, &buNaturalTimeCollecton, &buImperialVelCollecton, &buImperialAclCollecton}, /* imperial */
00276         {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}
00277 };
00278 
00279 
00280 
00281 /* internal, has some option not exposed */
00282 static bUnitCollection *unit_get_system(int system, int type)
00283 {
00284         assert((system > -1) && (system < UNIT_SYSTEM_TOT) && (type > -1) && (type < B_UNIT_TYPE_TOT));
00285         return bUnitSystems[system][type]; /* select system to use, metric/imperial/other? */
00286 }
00287 
00288 static bUnitDef *unit_default(bUnitCollection *usys)
00289 {
00290         return &usys->units[usys->base_unit];
00291 }
00292 
00293 static bUnitDef *unit_best_fit(double value, bUnitCollection *usys, bUnitDef *unit_start, int suppress)
00294 {
00295         bUnitDef *unit;
00296         double value_abs= value>0.0?value:-value;
00297 
00298         for(unit= unit_start ? unit_start:usys->units; unit->name; unit++) {
00299 
00300                 if(suppress && (unit->flag & B_UNIT_DEF_SUPPRESS))
00301                         continue;
00302 
00303                 if (value_abs >= unit->scalar*(1.0-EPS)) /* scale down scalar so 1cm doesnt convert to 10mm because of float error */
00304                         return unit;
00305         }
00306 
00307         return unit_default(usys);
00308 }
00309 
00310 
00311 
00312 /* convert into 2 units and 2 values for "2ft, 3inch" syntax */
00313 static void unit_dual_convert(double value, bUnitCollection *usys,
00314                 bUnitDef **unit_a, bUnitDef **unit_b, double *value_a, double *value_b)
00315 {
00316         bUnitDef *unit= unit_best_fit(value, usys, NULL, 1);
00317 
00318         *value_a=  (value < 0.0 ? ceil:floor)(value/unit->scalar) * unit->scalar;
00319         *value_b= value - (*value_a);
00320 
00321         *unit_a=        unit;
00322         *unit_b=        unit_best_fit(*value_b, usys, *unit_a, 1);
00323 }
00324 
00325 static int unit_as_string(char *str, int len_max, double value, int prec, bUnitCollection *usys,
00326                 /* non exposed options */
00327                 bUnitDef *unit, char pad)
00328 {
00329         double value_conv;
00330         int len, i;
00331         
00332         if(unit) {
00333                 /* use unit without finding the best one */
00334         }
00335         else if(value == 0.0) {
00336                 /* use the default units since there is no way to convert */
00337                 unit= unit_default(usys);
00338         }
00339         else {
00340                 unit= unit_best_fit(value, usys, NULL, 1);
00341         }
00342 
00343         value_conv= value/unit->scalar;
00344 
00345         /* Convert to a string */
00346         {
00347                 len= snprintf(str, len_max, "%.*lf", prec, value_conv);
00348 
00349                 if(len >= len_max)
00350                         len= len_max;
00351         }
00352         
00353         /* Add unit prefix and strip zeros */
00354 
00355         /* replace trailing zero's with spaces
00356          * so the number is less complicated but allignment in a button wont
00357          * jump about while dragging */
00358         i= len-1;
00359 
00360         while(i>0 && str[i]=='0') { /* 4.300 -> 4.3 */
00361                 str[i--]= pad;
00362         }
00363 
00364         if(i>0 && str[i]=='.') { /* 10. -> 10 */
00365                 str[i--]= pad;
00366         }
00367         
00368         /* Now add the suffix */
00369         if(i<len_max) {
00370                 int j=0;
00371                 i++;
00372                 while(unit->name_short[j] && (i < len_max)) {
00373                         str[i++]= unit->name_short[j++];
00374                 }
00375 
00376                 if(pad) {
00377                         /* this loop only runs if so many zeros were removed that
00378                          * the unit name only used padded chars,
00379                          * In that case add padding for the name. */
00380 
00381                         while(i<=len+j && (i < len_max)) {
00382                                 str[i++]= pad;
00383                         }
00384                 }
00385         }
00386 
00387         /* terminate no matter whats done with padding above */
00388         if(i >= len_max)
00389                 i= len_max-1;
00390 
00391         str[i] = '\0';
00392         return i;
00393 }
00394 
00395 
00396 /* Used for drawing number buttons, try keep fast */
00397 void bUnit_AsString(char *str, int len_max, double value, int prec, int system, int type, int split, int pad)
00398 {
00399         bUnitCollection *usys = unit_get_system(system, type);
00400 
00401         if(usys==NULL || usys->units[0].name==NULL)
00402                 usys= &buDummyCollecton;
00403    
00404         /* split output makes sense only for length, mass and time */
00405         if(split && (type==B_UNIT_LENGTH || type==B_UNIT_MASS || type==B_UNIT_TIME)) {
00406                 bUnitDef *unit_a, *unit_b;
00407                 double value_a, value_b;
00408 
00409                 unit_dual_convert(value, usys,          &unit_a, &unit_b, &value_a, &value_b);
00410 
00411                 /* check the 2 is a smaller unit */
00412                 if(unit_b > unit_a) {
00413                         int i= unit_as_string(str, len_max, value_a, prec, usys,  unit_a, '\0');
00414 
00415                         /* is there enough space for at least 1 char of the next unit? */
00416                         if(i+2 < len_max) {
00417                                 str[i++]= ' ';
00418 
00419                                 /* use low precision since this is a smaller unit */
00420                                 unit_as_string(str+i, len_max-i, value_b, prec?1:0, usys,  unit_b, '\0');
00421                         }
00422                         return;
00423                 }
00424         }
00425 
00426         unit_as_string(str, len_max, value, prec, usys,    NULL, pad?' ':'\0');
00427 }
00428 
00429 
00430 static char *unit_find_str(char *str, const char *substr)
00431 {
00432         char *str_found;
00433 
00434         if(substr && substr[0] != '\0') {
00435                 str_found= strstr(str, substr);
00436                 if(str_found) {
00437                         /* previous char cannot be a letter */
00438                         if (str_found == str || isalpha(*(str_found-1))==0) {
00439                                 /* next char cannot be alphanum */
00440                                 int len_name = strlen(substr);
00441 
00442                                 if (!isalpha(*(str_found+len_name))) {
00443                                         return str_found;
00444                                 }
00445                         }
00446                 }
00447 
00448         }
00449         return NULL;
00450 
00451 }
00452 
00453 /* Note that numbers are added within brackets
00454  * ") " - is used to detect numbers we added so we can detect if commas need to be added
00455  *
00456  * "1m1cm+2mm"                          - Original value
00457  * "1*1#1*0.01#+2*0.001#"       - Replace numbers
00458  * "1*1,1*0.01 +2*0.001 "       - Add comma's if ( - + * / % ^ < > ) not found in between
00459  *
00460  */
00461 
00462 /* not too strict, (- = * /) are most common  */
00463 static int ch_is_op(char op)
00464 {
00465         switch(op) {
00466         case '+':
00467         case '-':
00468         case '*':
00469         case '/':
00470         case '|':
00471         case '&':
00472         case '~':
00473         case '<':
00474         case '>':
00475         case '^':
00476         case '!':
00477         case '=':
00478         case '%':
00479                 return 1;
00480         default:
00481                 return 0;
00482         }
00483 }
00484 
00485 static int unit_scale_str(char *str, int len_max, char *str_tmp, double scale_pref, bUnitDef *unit, const char *replace_str)
00486 {
00487         char *str_found;
00488 
00489         if((len_max>0) && (str_found= unit_find_str(str, replace_str))) { /* XXX - investigate, does not respect len_max properly  */
00490                 int len, len_num, len_name, len_move, found_ofs;
00491 
00492                 found_ofs = (int)(str_found-str);
00493 
00494                 len= strlen(str);
00495 
00496                 len_name = strlen(replace_str);
00497                 len_move= (len - (found_ofs+len_name)) + 1; /* 1+ to copy the string terminator */
00498                 len_num= snprintf(str_tmp, TEMP_STR_SIZE, "*%lg"SEP_STR, unit->scalar/scale_pref); /* # removed later */
00499 
00500                 if(len_num > len_max)
00501                         len_num= len_max;
00502 
00503                 if(found_ofs+len_num+len_move > len_max) {
00504                         /* can't move the whole string, move just as much as will fit */
00505                         len_move -= (found_ofs+len_num+len_move) - len_max;
00506                 }
00507 
00508                 if(len_move>0) {
00509                         /* resize the last part of the string */
00510                         memmove(str_found+len_num, str_found+len_name, len_move); /* may grow or shrink the string */
00511                 }
00512 
00513                 if(found_ofs+len_num > len_max) {
00514                         /* not even the number will fit into the string, only copy part of it */
00515                         len_num -= (found_ofs+len_num) - len_max;
00516                 }
00517 
00518                 if(len_num > 0) {
00519                         /* its possible none of the number could be copied in */
00520                         memcpy(str_found, str_tmp, len_num); /* without the string terminator */
00521                 }
00522 
00523                 /* since the null terminator wont be moved if the stringlen_max
00524                  * was not long enough to fit everything in it */
00525                 str[len_max-1]= '\0';
00526                 return found_ofs + len_num;
00527         }
00528         return 0;
00529 }
00530 
00531 static int unit_replace(char *str, int len_max, char *str_tmp, double scale_pref, bUnitDef *unit)
00532 {       
00533         int ofs= 0;
00534         ofs += unit_scale_str(str+ofs, len_max-ofs, str_tmp, scale_pref, unit, unit->name_short);
00535         ofs += unit_scale_str(str+ofs, len_max-ofs, str_tmp, scale_pref, unit, unit->name_plural);
00536         ofs += unit_scale_str(str+ofs, len_max-ofs, str_tmp, scale_pref, unit, unit->name_alt);
00537         ofs += unit_scale_str(str+ofs, len_max-ofs, str_tmp, scale_pref, unit, unit->name);
00538         return ofs;
00539 }
00540 
00541 static int unit_find(char *str, bUnitDef *unit)
00542 {
00543         if (unit_find_str(str, unit->name_short))       return 1;
00544         if (unit_find_str(str, unit->name_plural))      return 1;
00545         if (unit_find_str(str, unit->name_alt))         return 1;
00546         if (unit_find_str(str, unit->name))                     return 1;
00547 
00548         return 0;
00549 }
00550 
00551 /* make a copy of the string that replaces the units with numbers
00552  * this is used before parsing
00553  * This is only used when evaluating user input and can afford to be a bit slower
00554  * 
00555  * This is to be used before python evaluation so..
00556  * 10.1km -> 10.1*1000.0
00557  * ...will be resolved by python.
00558  * 
00559  * values will be split by a comma's
00560  * 5'2" -> 5'0.0254, 2*0.3048
00561  *
00562  * str_prev is optional, when valid it is used to get a base unit when none is set.
00563  *
00564  * return true of a change was made.
00565  */
00566 int bUnit_ReplaceString(char *str, int len_max, char *str_prev, double scale_pref, int system, int type)
00567 {
00568         bUnitCollection *usys = unit_get_system(system, type);
00569 
00570         bUnitDef *unit;
00571         char str_tmp[TEMP_STR_SIZE];
00572         int change= 0;
00573 
00574         if(usys==NULL || usys->units[0].name==NULL) {
00575                 return 0;
00576         }
00577         
00578 
00579         {       /* make lowercase */
00580                 int i;
00581                 char *ch= str;
00582 
00583                 for(i=0; (i>=len_max || *ch=='\0'); i++, ch++)
00584                         if((*ch>='A') && (*ch<='Z'))
00585                                 *ch += ('a'-'A');
00586         }
00587 
00588 
00589         for(unit= usys->units; unit->name; unit++) {
00590                 /* incase there are multiple instances */
00591                 while(unit_replace(str, len_max, str_tmp, scale_pref, unit))
00592                         change= 1;
00593         }
00594         unit= NULL;
00595 
00596         {
00597                 /* try other unit systems now, so we can evaluate imperial when metric is set for eg. */
00598                 bUnitCollection *usys_iter;
00599                 int system_iter;
00600 
00601                 for(system_iter= 0; system_iter<UNIT_SYSTEM_TOT; system_iter++) {
00602                         if (system_iter != system) {
00603                                 usys_iter= unit_get_system(system_iter, type);
00604                                 if (usys_iter) {
00605                                         for(unit= usys_iter->units; unit->name; unit++) {
00606                                                 int ofs = 0;
00607                                                 /* incase there are multiple instances */
00608                                                 while((ofs=unit_replace(str+ofs, len_max-ofs, str_tmp, scale_pref, unit)))
00609                                                         change= 1;
00610                                         }
00611                                 }
00612                         }
00613                 }
00614         }
00615         unit= NULL;
00616         
00617         if(change==0) {
00618                 /* no units given so infer a unit from the previous string or default */
00619                 if(str_prev) {
00620                         /* see which units the original value had */
00621                         for(unit= usys->units; unit->name; unit++) {
00622                                 if (unit_find(str_prev, unit))
00623                                         break;
00624                         }
00625                 }
00626 
00627                 if(unit==NULL || unit->name == NULL)
00628                         unit= unit_default(usys);
00629 
00630 
00631                 /* add the unit prefix and re-run, use brackets incase there was an expression given */
00632                 if(snprintf(str_tmp, sizeof(str_tmp), "(%s)%s", str, unit->name) < sizeof(str_tmp)) {
00633                         strncpy(str, str_tmp, len_max);
00634                         return bUnit_ReplaceString(str, len_max, NULL, scale_pref, system, type);
00635                 }
00636                 else {
00637                         /* snprintf would not fit into str_tmp, cant do much in this case
00638                          * check for this because otherwise bUnit_ReplaceString could call its self forever */
00639                         return 0;
00640                 }
00641 
00642         }
00643 
00644         /* replace # with commas when there is no operator between it and the next number
00645          *
00646          * "1*1# 3*100# * 3"  ->  "1 *1, 3 *100  * 3"
00647          *
00648          * */
00649         {
00650                 char *str_found= str;
00651                 char *ch= str;
00652 
00653                 while((str_found= strchr(str_found, SEP_CHR))) {
00654 
00655                         int op_found= 0;
00656                         /* any operators after this?*/
00657                         for(ch= str_found+1; *ch!='\0'; ch++) {
00658 
00659                                 if(*ch==' ' || *ch=='\t') {
00660                                         /* do nothing */
00661                                 }
00662                                 else if (ch_is_op(*ch) || *ch==',') { /* found an op, no need to insert a ,*/
00663                                         op_found= 1;
00664                                         break;
00665                                 }
00666                                 else { /* found a non-op character */
00667                                         op_found= 0;
00668                                         break;
00669                                 }
00670                         }
00671 
00672                         *str_found++ = op_found ? ' ':',';
00673                 }
00674         }
00675 
00676         return change;
00677 }
00678 
00679 /* 45µm --> 45um */
00680 void bUnit_ToUnitAltName(char *str, int len_max, char *orig_str, int system, int type)
00681 {
00682         bUnitCollection *usys = unit_get_system(system, type);
00683 
00684         bUnitDef *unit;
00685         bUnitDef *unit_def= unit_default(usys);
00686 
00687         /* find and substitute all units */
00688         for(unit= usys->units; unit->name; unit++) {
00689                 if(len_max > 0 && (unit->name_alt || unit == unit_def))
00690                 {
00691                         char *found= NULL;
00692 
00693                         found= unit_find_str(orig_str, unit->name_short);
00694                         if(found) {
00695                                 int offset= (int)(found - orig_str);
00696                                 int len_name= 0;
00697 
00698                                 /* copy everything before the unit */
00699                                 offset= (offset<len_max? offset: len_max);
00700                                 strncpy(str, orig_str, offset);
00701 
00702                                 str+= offset;
00703                                 orig_str+= offset + strlen(unit->name_short);
00704                                 len_max-= offset;
00705 
00706                                 /* print the alt_name */
00707                                 if(unit->name_alt)
00708                                         len_name= snprintf(str, len_max, "%s", unit->name_alt);
00709                                 else
00710                                         len_name= 0;
00711 
00712                                 len_name= (len_name<len_max? len_name: len_max);
00713                                 str+= len_name;
00714                                 len_max-= len_name;
00715                         }
00716                 }
00717         }
00718 
00719         /* finally copy the rest of the string */
00720         strncpy(str, orig_str, len_max);
00721 }
00722 
00723 double bUnit_ClosestScalar(double value, int system, int type)
00724 {
00725         bUnitCollection *usys = unit_get_system(system, type);
00726         bUnitDef *unit;
00727 
00728         if(usys==NULL)
00729                 return -1;
00730 
00731         unit= unit_best_fit(value, usys, NULL, 1);
00732         if(unit==NULL)
00733                 return -1;
00734 
00735         return unit->scalar;
00736 }
00737 
00738 double bUnit_BaseScalar(int system, int type)
00739 {
00740         bUnitCollection *usys = unit_get_system(system, type);
00741         return unit_default(usys)->scalar;
00742 }
00743 
00744 /* external access */
00745 int bUnit_IsValid(int system, int type)
00746 {
00747         return !(system < 0 || system > UNIT_SYSTEM_TOT || type < 0 || type > B_UNIT_TYPE_TOT);
00748 }
00749 
00750 
00751 void bUnit_GetSystem(void **usys_pt, int *len, int system, int type)
00752 {
00753         bUnitCollection *usys = unit_get_system(system, type);
00754         *usys_pt= usys;
00755 
00756         if(usys==NULL) {
00757                 *len= 0;
00758                 return;
00759         }
00760 
00761         *len= usys->length;
00762 }
00763 
00764 int bUnit_GetBaseUnit(void *usys_pt)
00765 {
00766         return ((bUnitCollection *)usys_pt)->base_unit;
00767 }
00768 
00769 const char *bUnit_GetName(void *usys_pt, int index)
00770 {
00771         return ((bUnitCollection *)usys_pt)->units[index].name;
00772 }
00773 const char *bUnit_GetNameDisplay(void *usys_pt, int index)
00774 {
00775         return ((bUnitCollection *)usys_pt)->units[index].name_display;
00776 }
00777 
00778 double bUnit_GetScaler(void *usys_pt, int index)
00779 {
00780         return ((bUnitCollection *)usys_pt)->units[index].scalar;
00781 }