aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/makamys/neodymium/util/BufferWriter.java
blob: eb9263db66d5ab654ab688f2ad7d03cb6ba6eaa0 (plain)
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
package makamys.neodymium.util;

import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;

public class BufferWriter {
    
    private ByteBuffer buf;
    
    private FloatBuffer floatBuffer;
    private ShortBuffer shortBuffer;
    private IntBuffer intBuffer;
    
    public BufferWriter(ByteBuffer buf) {
        this.buf = buf;
        this.floatBuffer = buf.asFloatBuffer();
        this.shortBuffer = buf.asShortBuffer();
        this.intBuffer = buf.asIntBuffer();
    }
    
    private void incrementPosition(int add) {
        buf.position(buf.position() + add);
        floatBuffer.position(buf.position() / 4);
        shortBuffer.position(buf.position() / 2);
        intBuffer.position(buf.position() / 4);
    }
    
    public void writeFloat(float x) {
        try {
        floatBuffer.put(x);
        
        incrementPosition(4);
        } catch(Exception e){
            e.printStackTrace();
        }
    }
    
    public void writeInt(int x) {
        intBuffer.put(x);
        
        incrementPosition(4);
    }
    
    public void writeByte(byte x) {
        buf.put(x); // this increments the buffer position by 1
        
        incrementPosition(0);
    }
    
    public int position() {
        return buf.position();
    }

    public void writeShort(short s) {
        shortBuffer.put(s);
        
        incrementPosition(2);
    }
    
}