2 #include <msp/core/raii.h>
3 #include <msp/gl/extensions/arb_direct_state_access.h>
6 #include "bufferable.h"
13 Bufferable::Bufferable():
21 Bufferable::~Bufferable()
26 void Bufferable::use_buffer(Buffer *buf, Bufferable *prev)
28 if(prev && buf!=prev->buffer)
29 throw invalid_argument("Bufferable::use_buffer");
37 prev_in_buffer = prev;
40 next_in_buffer = prev_in_buffer->next_in_buffer;
41 prev_in_buffer->next_in_buffer = this;
49 Bufferable::AsyncUpdater *Bufferable::refresh_async() const
51 return dirty ? new AsyncUpdater(*this) : 0;
54 void Bufferable::unlink_from_buffer()
57 prev_in_buffer->next_in_buffer = next_in_buffer;
60 next_in_buffer->prev_in_buffer = prev_in_buffer;
61 next_in_buffer->update_offset();
68 void Bufferable::update_offset()
70 unsigned new_offset = 0;
72 new_offset = prev_in_buffer->offset+prev_in_buffer->get_data_size();
74 unsigned align = get_alignment();
75 new_offset += align-1;
76 new_offset -= new_offset%align;
77 if(new_offset!=offset)
85 next_in_buffer->update_offset();
87 /* Do not resize the buffer here, as more bufferables may be added before
88 the buffer is actually used. */
91 bool Bufferable::resize_buffer() const
93 if(offset+get_data_size()>=buffer->get_size())
95 const Bufferable *last = this;
96 for(; last->next_in_buffer; last=last->next_in_buffer) ;
98 unsigned total_size = last->offset+last->get_data_size();
100 if(total_size>buffer->get_size())
102 buffer->data(total_size, 0);
110 void Bufferable::update_buffer() const
112 Conditional<BindRestore> _bind(!ARB_direct_state_access, buffer, buffer->get_type());
116 /* Resizing the buffer invalidates its contents. Non-dirty data may
117 be in use, so reupload it. */
118 for(const Bufferable *b=prev_in_buffer; b; b=b->prev_in_buffer)
121 for(const Bufferable *b=next_in_buffer; b; b=b->next_in_buffer)
130 void Bufferable::upload_data(char *target) const
134 const char *source = reinterpret_cast<const char *>(get_data_pointer());
135 copy(source, source+get_data_size(), target);
138 buffer->sub_data(offset, get_data_size(), get_data_pointer());
142 Bufferable::AsyncUpdater::AsyncUpdater(const Bufferable &b):
145 buffer_resized = bufferable.resize_buffer();
146 mapped_address = reinterpret_cast<char *>(bufferable.buffer->map(WRITE_ONLY));
149 Bufferable::AsyncUpdater::~AsyncUpdater()
151 bufferable.buffer->unmap();
154 void Bufferable::AsyncUpdater::upload_data()
156 bufferable.upload_data(mapped_address+bufferable.offset);
157 // Update all bufferables in the same buffer at once
158 for(const Bufferable *b=bufferable.prev_in_buffer; b; b=b->prev_in_buffer)
159 if(b->dirty || buffer_resized)
161 b->upload_data(mapped_address+b->offset);
164 for(const Bufferable *b=bufferable.next_in_buffer; b; b=b->next_in_buffer)
165 if(b->dirty || buffer_resized)
167 b->upload_data(mapped_address+b->offset);