Version 6.4.0.0.beta1, tag libreoffice-6.4.0.0.beta1
[LibreOffice.git] / basegfx / source / numeric / ftools.cxx
blobd1eca66ca2fced45e53e9b889219605f9e90d457
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include <basegfx/numeric/ftools.hxx>
21 #include <algorithm>
23 namespace basegfx
25 double snapToNearestMultiple(double v, const double fStep)
27 if(fTools::equalZero(fStep))
29 // with a zero step, all snaps to 0.0
30 return 0.0;
32 else
34 const double fHalfStep(fStep * 0.5);
35 const double fChange(fHalfStep - fmod(v + fHalfStep, fStep));
37 if(basegfx::fTools::equal(fabs(v), fabs(fChange)))
39 return 0.0;
41 else
43 return v + fChange;
48 double snapToZeroRange(double v, double fWidth)
50 if(fTools::equalZero(fWidth))
52 // with no range all snaps to range bound
53 return 0.0;
55 else
57 if(v < 0.0 || v > fWidth)
59 double fRetval(fmod(v, fWidth));
61 if(fRetval < 0.0)
63 fRetval += fWidth;
66 return fRetval;
68 else
70 return v;
75 double snapToRange(double v, double fLow, double fHigh)
77 if(fTools::equal(fLow, fHigh))
79 // with no range all snaps to range bound
80 return 0.0;
82 else
84 if(fLow > fHigh)
86 // correct range order. Evtl. assert this (?)
87 std::swap(fLow, fHigh);
90 if(v < fLow || v > fHigh)
92 return snapToZeroRange(v - fLow, fHigh - fLow) + fLow;
94 else
96 return v;
101 double normalizeToRange(double v, const double fRange)
103 if(fTools::lessOrEqual(fRange, 0.0))
105 // with a zero (or less) range, all normalizes to 0.0
106 return 0.0;
109 const bool bNegative(fTools::less(v, 0.0));
111 if(bNegative)
113 if(fTools::moreOrEqual(v, -fRange))
115 // in range [-fRange, 0.0[, shift one step
116 return v + fRange;
119 // re-calculate
120 return v - (floor(v/fRange)*fRange);
122 else
124 if(fTools::less(v, fRange))
126 // already in range [0.0, fRange[, nothing to do
127 return v;
130 // re-calculate
131 return v - (floor(v/fRange)*fRange);
134 } // end of namespace basegfx
136 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */