Version 24.2.2.2, tag libreoffice-24.2.2.2
[LibreOffice.git] / basegfx / source / tools / keystoplerp.cxx
blobe5d0d76304e2a2c0dd6e71ff5b83d69b42b058fa
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/utils/keystoplerp.hxx>
21 #include <com/sun/star/uno/Sequence.hxx>
22 #include <osl/diagnose.h>
24 #include <algorithm>
26 static void validateInput(const std::vector<double>& rKeyStops)
28 #ifdef DBG_UTIL
29 OSL_ENSURE( rKeyStops.size() > 1,
30 "KeyStopLerp::KeyStopLerp(): key stop vector must have two entries or more" );
32 // rKeyStops must be sorted in ascending order
33 for( std::size_t i=1, len=rKeyStops.size(); i<len; ++i )
35 if( rKeyStops[i-1] > rKeyStops[i] )
36 OSL_FAIL( "KeyStopLerp::KeyStopLerp(): time vector is not sorted in ascending order!" );
38 #else
39 (void)rKeyStops;
40 #endif
43 namespace basegfx::utils
45 KeyStopLerp::KeyStopLerp( std::vector<double>&& rKeyStops ) :
46 maKeyStops(std::move(rKeyStops)),
47 mnLastIndex(0)
49 validateInput(maKeyStops);
52 KeyStopLerp::KeyStopLerp( const ::css::uno::Sequence<double>& rKeyStops ) :
53 maKeyStops(rKeyStops.begin(), rKeyStops.end()),
54 mnLastIndex(0)
56 validateInput(maKeyStops);
59 KeyStopLerp::ResultType KeyStopLerp::lerp(double fAlpha) const
61 // cached value still okay?
62 if( maKeyStops.at(mnLastIndex) < fAlpha ||
63 maKeyStops.at(mnLastIndex+1) >= fAlpha )
65 // nope, find new index
66 mnLastIndex = std::min<std::ptrdiff_t>(
67 maKeyStops.size()-2,
68 // range is ensured by max below
69 std::max<std::ptrdiff_t>(
71 std::distance( maKeyStops.begin(),
72 std::lower_bound( maKeyStops.begin(),
73 maKeyStops.end(),
74 fAlpha )) - 1 ));
77 // lerp between stop and stop+1
78 const double fRawLerp=
79 (fAlpha-maKeyStops.at(mnLastIndex)) /
80 (maKeyStops.at(mnLastIndex+1) - maKeyStops.at(mnLastIndex));
82 // clamp to permissible range (input fAlpha might be
83 // everything)
84 return ResultType(
85 mnLastIndex,
86 std::clamp(fRawLerp,0.0,1.0));
90 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */