| 12 | import buildcraft.lib.misc.NBTUtils; |
| 13 | |
| 14 | public class AverageDouble implements INBTSerializable<NBTTagCompound> { |
| 15 | private double[] data; |
| 16 | private int pos, precise; |
| 17 | private double averageRaw, tickValue; |
| 18 | |
| 19 | public AverageDouble(int precise) { |
| 20 | this.precise = precise; |
| 21 | this.data = new double[precise]; |
| 22 | this.pos = 0; |
| 23 | } |
| 24 | |
| 25 | public double getAverage() { |
| 26 | return averageRaw / precise; |
| 27 | } |
| 28 | |
| 29 | public void tick(double value) { |
| 30 | internalTick(tickValue + value); |
| 31 | tickValue = 0; |
| 32 | } |
| 33 | |
| 34 | public void tick() { |
| 35 | internalTick(tickValue); |
| 36 | tickValue = 0; |
| 37 | } |
| 38 | |
| 39 | private void internalTick(double value) { |
| 40 | pos = ++pos % precise; |
| 41 | double oldValue = data[pos]; |
| 42 | data[pos] = value; |
| 43 | if (pos == 0) { |
| 44 | averageRaw = 0; |
| 45 | for (double iValue : data) { |
| 46 | averageRaw += iValue; |
| 47 | } |
| 48 | } else { |
| 49 | averageRaw = averageRaw - oldValue + value; |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | public void push(double value) { |
| 54 | tickValue += value; |
| 55 | } |
| 56 | |
| 57 | @Override |
| 58 | public NBTTagCompound serializeNBT() { |
| 59 | NBTTagCompound nbt = new NBTTagCompound(); |
| 60 | nbt.setInteger("pos", pos); |
| 61 | nbt.setInteger("precise", precise); |
| 62 | nbt.setDouble("averageRaw", averageRaw); |
| 63 | nbt.setDouble("tickValue", tickValue); |
| 64 | nbt.setTag("data", NBTUtils.writeDoubleArray(data)); |
| 65 | return nbt; |
| 66 | } |
| 67 | |
| 68 | @Override |
| 69 | public void deserializeNBT(NBTTagCompound nbt) { |
| 70 | precise = MathUtil.clamp(nbt.getInteger("precise"), 1, Short.MAX_VALUE); |
| 71 | pos = MathUtil.clamp(nbt.getInteger("pos"), 0, precise); |
nothing calls this directly
no outgoing calls
no test coverage detected