-
Notifications
You must be signed in to change notification settings - Fork 7
/
RangeList.cpp
139 lines (120 loc) · 2.39 KB
/
RangeList.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
// $Id: RangeList.cpp,v 1.4 2006/01/24 03:22:14 zr Exp $
#define _USE_MATH_DEFINES
#include <math.h>
#include <stdio.h>
#include <string.h>
#include "RangeList.h"
///
static const float kSmallestRange = .000001f;
RangeList::RangeList(float min, float max)
{
numRanges = 0;
rangesSize = 8;
ranges = new RangeEntry[rangesSize];
reset(min, max);
}
RangeList::~RangeList()
{
delete[] ranges;
}
void RangeList::reset(float min, float max)
{
numRanges = 1;
ranges[0].min = min;
ranges[0].max = max;
}
void RangeList::deleteRange(int pos)
{
if (pos<numRanges-1) {
memmove(&ranges[pos], &ranges[pos+1], sizeof(*ranges)*(numRanges-(pos+1)));
}
numRanges--;
}
void RangeList::insertRange(int pos, float min, float max)
{
if (numRanges==rangesSize) {
RangeEntry *tmp = new RangeEntry[rangesSize];
memcpy(tmp, ranges, numRanges*sizeof(*tmp));
delete[] ranges;
ranges = tmp;
}
if (pos<numRanges) {
memmove(&ranges[pos+1], &ranges[pos], sizeof(*ranges)*(numRanges-pos));
}
ranges[pos].min = min;
ranges[pos].max = max;
numRanges++;
}
void RangeList::subtract(float a, float b)
{
static const float twoPi = (float) (M_PI*2);
if (a>twoPi) {
subtract(a-twoPi, b-twoPi);
} else if (b<0) {
subtract(a+twoPi, b+twoPi);
} else if (a<0) {
subtract(0, b);
subtract(a+twoPi,twoPi);
} else if (b>twoPi) {
subtract(a, twoPi);
subtract(0, b-twoPi);
} else if (numRanges==0) {
;
} else {
int pos;
if (a<ranges[0].min) {
pos = -1;
} else {
int lo=0, mid=0, hi=numRanges;
while (lo<hi-1) {
mid = (lo+hi)>>1;
if (ranges[mid].min<a) {
lo = mid;
} else {
hi = mid;
}
}
pos = lo;
}
if (pos==-1) {
pos = 0;
} else if (a<ranges[pos].max) {
float c = ranges[pos].min;
float d = ranges[pos].max;
if (a-c<kSmallestRange) {
if (b<d) {
ranges[pos].min = b;
} else {
deleteRange(pos);
}
} else {
ranges[pos].max = a;
if (b<d) {
insertRange(pos+1, b, d);
}
pos++;
}
} else {
if (pos<numRanges-1 && b>ranges[pos+1].min) {
pos++;
} else {
return;
}
}
while (pos<numRanges && b>ranges[pos].min) {
if (ranges[pos].max-b<kSmallestRange) {
deleteRange(pos);
} else {
ranges[pos].min = b;
}
}
}
}
void RangeList::print()
{
printf("[");
for (int i=0; i<numRanges; i++) {
printf("(%f,%f)%s", ranges[i].min, ranges[i].max, (i==numRanges-1)?"":", ");
}
printf("]\n");
}