Revert "Remove Lua 5.1 support"
[lsnes.git] / src / library / controller-data.cpp
blob21f3011e8009526002c332b512676ef44e9d5938
1 #include "binarystream.hpp"
2 #include "controller-data.hpp"
3 #include "threads.hpp"
4 #include "minmax.hpp"
5 #include "globalwrap.hpp"
6 #include "serialization.hpp"
7 #include "string.hpp"
8 #include "sha256.hpp"
9 #include <iostream>
10 #include <sys/time.h>
11 #include <sstream>
12 #include <list>
13 #include <deque>
14 #include <complex>
16 namespace
18 port_controller simple_controller = {"(system)", "system", {}};
19 port_controller_set simple_port = {"system", "system", "system", {simple_controller},{0}};
21 struct porttype_basecontrol : public port_type
23 porttype_basecontrol() : port_type("basecontrol", "basecontrol", 1)
25 write = [](const port_type* _this, unsigned char* buffer, unsigned idx, unsigned ctrl,
26 short x) -> void {
27 if(idx > 0 || ctrl > 0) return;
28 buffer[0] = x ? 1 : 0;
30 read = [](const port_type* _this, const unsigned char* buffer, unsigned idx, unsigned ctrl) ->
31 short {
32 if(idx > 0 || ctrl > 0) return 0;
33 return buffer[0] ? 1 : 0;
35 serialize = [](const port_type* _this, const unsigned char* buffer, char* textbuf) -> size_t {
36 textbuf[0] = buffer[0] ? 'F' : '-';
37 textbuf[1] = '\0';
38 return 1;
40 deserialize = [](const port_type* _this, unsigned char* buffer, const char* textbuf) ->
41 size_t {
42 size_t ptr = 0;
43 buffer[0] = 0;
44 if(read_button_value(textbuf, ptr))
45 buffer[0] = 1;
46 skip_rest_of_field(textbuf, ptr, false);
47 return ptr;
49 controller_info = &simple_port;
53 unsigned macro_random_bit()
55 static unsigned char state[32];
56 static unsigned extracted = 256;
57 if(extracted == 256) {
58 timeval tv;
59 gettimeofday(&tv, NULL);
60 unsigned char buffer[48];
61 memcpy(buffer, state, 32);
62 serialization::u64b(buffer + 32, tv.tv_sec);
63 serialization::u64b(buffer + 40, tv.tv_usec);
64 sha256::hash(state, buffer, 48);
65 extracted = 0;
67 unsigned bit = extracted++;
68 return ((state[bit / 8] >> (bit % 8)) & 1);
72 port_type& get_default_system_port_type()
74 static porttype_basecontrol x;
75 return x;
78 port_type::port_type(const std::string& iname, const std::string& _hname, size_t ssize) throw(std::bad_alloc)
79 : hname(_hname), storage_size(ssize), name(iname)
83 port_type::~port_type() throw()
87 bool port_type::is_present(unsigned controller) const throw()
89 return controller_info->controllers.size() > controller;
92 namespace
94 size_t dummy_offset = 0;
95 port_type* dummy_type = &get_default_system_port_type();
96 unsigned dummy_index = 0;
97 struct binding
99 std::vector<port_type*> types;
100 port_type_set* stype;
101 bool matches(const std::vector<class port_type*>& x)
103 if(x.size() != types.size())
104 return false;
105 for(size_t i = 0; i < x.size(); i++)
106 if(x[i] != types[i])
107 return false;
108 return true;
111 std::list<binding>& bindings()
113 static std::list<binding> x;
114 return x;
118 port_type_set::port_type_set() throw()
121 port_offsets = &dummy_offset;
122 port_types = &dummy_type;
123 port_count = 1;
124 total_size = 1;
125 _indices.resize(1);
126 _indices[0].valid = true;
127 _indices[0].port = 0;
128 _indices[0].controller = 0;
129 _indices[0].control = 0;
131 port_multiplier = 1;
132 controller_multiplier = 1;
133 indices_size = 1;
134 indices_tab = &dummy_index;
137 port_type_set& port_type_set::make(std::vector<class port_type*> types, struct port_index_map control_map)
138 throw(std::bad_alloc, std::runtime_error)
140 for(auto i : bindings())
141 if(i.matches(types))
142 return *(i.stype);
143 //Not found, create new.
144 port_type_set& ret = *new port_type_set(types, control_map);
145 binding b;
146 b.types = types;
147 b.stype = &ret;
148 bindings().push_back(b);
149 return ret;
152 port_type_set::port_type_set(std::vector<class port_type*> types, struct port_index_map control_map)
154 port_count = types.size();
155 //Verify legality of port types.
156 for(size_t i = 0; i < port_count; i++)
157 if(!types[i] || !types[i]->legal(i))
158 throw std::runtime_error("Illegal port types");
159 //Count maximum number of controller indices to determine the controller multiplier.
160 controller_multiplier = 1;
161 for(size_t i = 0; i < port_count; i++)
162 for(unsigned j = 0; j < types[i]->controller_info->controllers.size(); j++)
163 controller_multiplier = max(controller_multiplier, (size_t)types[i]->used_indices(j));
164 //Count maximum number of controllers to determine the port multiplier.
165 port_multiplier = 1;
166 for(size_t i = 0; i < port_count; i++)
167 port_multiplier = max(port_multiplier, controller_multiplier *
168 (size_t)types[i]->controller_info->controllers.size());
169 //Allocate the per-port tables.
170 port_offsets = new size_t[types.size()];
171 port_types = new class port_type*[types.size()];
172 //Determine the total size and offsets.
173 size_t offset = 0;
174 for(size_t i = 0; i < port_count; i++) {
175 port_offsets[i] = offset;
176 offset += types[i]->storage_size;
177 port_types[i] = types[i];
179 total_size = offset;
180 //Determine the index size and allocate it.
181 indices_size = port_multiplier * port_count;
182 indices_tab = new unsigned[indices_size];
183 for(size_t i = 0; i < indices_size; i++)
184 indices_tab[i] = 0xFFFFFFFFUL;
185 //Copy the index data (and reverse it).
186 controllers = control_map.logical_map;
187 legacy_pcids = control_map.pcid_map;
188 _indices = control_map.indices;
189 for(size_t j = 0; j < _indices.size(); j++) {
190 auto& i = _indices[j];
191 if(i.valid)
192 indices_tab[i.port * port_multiplier + i.controller * controller_multiplier + i.control] = j;
196 short read_axis_value(const char* buf, size_t& idx) throw()
198 char ch;
199 //Skip ws.
200 while(is_nonterminator(buf[idx])) {
201 char ch = buf[idx];
202 if(ch != ' ' && ch != '\t')
203 break;
204 idx++;
206 //Read the sign if any.
207 ch = buf[idx];
208 if(!is_nonterminator(ch))
209 return 0;
210 bool negative = false;
211 if(ch == '-') {
212 negative = true;
213 idx++;
215 if(ch == '+')
216 idx++;
218 //Read numeric value.
219 int numval = 0;
220 while(is_nonterminator(buf[idx]) && isdigit(static_cast<unsigned char>(ch = buf[idx]))) {
221 numval = numval * 10 + (ch - '0');
222 idx++;
224 if(negative)
225 numval = -numval;
227 return static_cast<short>(numval);
230 namespace
232 port_type_set& dummytypes()
234 static port_type_set x;
235 return x;
238 size_t writeu32val(char32_t* buf, int val)
240 char c[12];
241 size_t i;
242 sprintf(c, "%d", val);
243 for(i = 0; c[i]; i++)
244 buf[i] = c[i];
245 return i;
248 uint64_t find_next_sync(controller_frame_vector& movie, uint64_t after)
250 if(after >= movie.size())
251 return after;
252 do {
253 after++;
254 } while(after < movie.size() && !movie[after].sync());
255 return after;
259 void controller_frame::display(unsigned port, unsigned controller, char32_t* buf) throw()
261 if(port >= types->ports()) {
262 //Bad port.
263 *buf = '\0';
264 return;
266 uint8_t* backingmem = backing + types->port_offset(port);
267 const port_type& ptype = types->port_type(port);
268 if(controller >= ptype.controller_info->controllers.size()) {
269 //Bad controller.
270 *buf = '\0';
271 return;
273 const port_controller& pc = ptype.controller_info->controllers[controller];
274 bool need_space = false;
275 short val;
276 for(unsigned i = 0; i < pc.buttons.size(); i++) {
277 const port_controller_button& pcb = pc.buttons[i];
278 if(need_space && pcb.type != port_controller_button::TYPE_NULL) {
279 need_space = false;
280 *(buf++) = ' ';
282 switch(pcb.type) {
283 case port_controller_button::TYPE_NULL:
284 break;
285 case port_controller_button::TYPE_BUTTON:
286 *(buf++) = ptype.read(&ptype, backingmem, controller, i) ? pcb.symbol : U'-';
287 break;
288 case port_controller_button::TYPE_AXIS:
289 case port_controller_button::TYPE_RAXIS:
290 case port_controller_button::TYPE_TAXIS:
291 case port_controller_button::TYPE_LIGHTGUN:
292 val = ptype.read(&ptype, backingmem, controller, i);
293 buf += writeu32val(buf, val);
294 need_space = true;
295 break;
298 *buf = '\0';
301 pollcounter_vector::pollcounter_vector() throw(std::bad_alloc)
303 types = &dummytypes();
304 ctrs = new uint32_t[types->indices()];
305 clear();
308 pollcounter_vector::pollcounter_vector(const port_type_set& p) throw(std::bad_alloc)
310 types = &p;
311 ctrs = new uint32_t[types->indices()];
312 clear();
315 pollcounter_vector::pollcounter_vector(const pollcounter_vector& p) throw(std::bad_alloc)
317 ctrs = new uint32_t[p.types->indices()];
318 types = p.types;
319 memcpy(ctrs, p.ctrs, sizeof(uint32_t) * p.types->indices());
320 framepflag = p.framepflag;
323 pollcounter_vector& pollcounter_vector::operator=(const pollcounter_vector& p) throw(std::bad_alloc)
325 if(this == &p)
326 return *this;
327 uint32_t* n = new uint32_t[p.types->indices()];
328 types = p.types;
329 memcpy(n, p.ctrs, sizeof(uint32_t) * p.types->indices());
330 delete[] ctrs;
331 ctrs = n;
332 framepflag = p.framepflag;
333 return *this;
336 pollcounter_vector::~pollcounter_vector() throw()
338 delete[] ctrs;
341 void pollcounter_vector::clear() throw()
343 memset(ctrs, 0, sizeof(uint32_t) * types->indices());
344 framepflag = false;
347 void pollcounter_vector::set_all_DRDY() throw()
349 for(size_t i = 0; i < types->indices(); i++)
350 ctrs[i] |= 0x80000000UL;
353 void pollcounter_vector::clear_DRDY(unsigned idx) throw()
355 ctrs[idx] &= 0x7FFFFFFFUL;
358 bool pollcounter_vector::get_DRDY(unsigned idx) throw()
360 return ((ctrs[idx] & 0x80000000UL) != 0);
363 bool pollcounter_vector::has_polled() throw()
365 uint32_t res = 0;
366 for(size_t i = 0; i < types->indices() ; i++)
367 res |= ctrs[i];
368 return ((res & 0x7FFFFFFFUL) != 0);
371 uint32_t pollcounter_vector::get_polls(unsigned idx) throw()
373 return ctrs[idx] & 0x7FFFFFFFUL;
376 uint32_t pollcounter_vector::increment_polls(unsigned idx) throw()
378 uint32_t x = ctrs[idx] & 0x7FFFFFFFUL;
379 ++ctrs[idx];
380 return x;
383 uint32_t pollcounter_vector::max_polls() throw()
385 uint32_t max = 0;
386 for(unsigned i = 0; i < types->indices(); i++) {
387 uint32_t tmp = ctrs[i] & 0x7FFFFFFFUL;
388 max = (max < tmp) ? tmp : max;
390 return max;
393 void pollcounter_vector::save_state(std::vector<uint32_t>& mem) throw(std::bad_alloc)
395 mem.resize(types->indices());
396 //Compatiblity fun.
397 for(size_t i = 0; i < types->indices(); i++)
398 mem[i] = ctrs[i];
401 void pollcounter_vector::load_state(const std::vector<uint32_t>& mem) throw()
403 for(size_t i = 0; i < types->indices(); i++)
404 ctrs[i] = mem[i];
407 bool pollcounter_vector::check(const std::vector<uint32_t>& mem) throw()
409 return (mem.size() == types->indices());
413 void pollcounter_vector::set_framepflag(bool value) throw()
415 framepflag = value;
418 bool pollcounter_vector::get_framepflag() const throw()
420 return framepflag;
423 controller_frame::controller_frame(const port_type_set& p) throw(std::runtime_error)
425 memset(memory, 0, sizeof(memory));
426 backing = memory;
427 types = &p;
428 host = NULL;
431 controller_frame::controller_frame(unsigned char* mem, const port_type_set& p, controller_frame_vector* _host)
432 throw(std::runtime_error)
434 if(!mem)
435 throw std::runtime_error("NULL backing memory not allowed");
436 memset(memory, 0, sizeof(memory));
437 backing = mem;
438 types = &p;
439 host = _host;
442 controller_frame::controller_frame(const controller_frame& obj) throw()
444 memset(memory, 0, sizeof(memory));
445 backing = memory;
446 types = obj.types;
447 memcpy(backing, obj.backing, types->size());
448 host = NULL;
451 controller_frame& controller_frame::operator=(const controller_frame& obj) throw(std::runtime_error)
453 if(backing != memory && types != obj.types)
454 throw std::runtime_error("Port types do not match");
455 types = obj.types;
456 short old = sync();
457 memcpy(backing, obj.backing, types->size());
458 if(host) host->notify_sync_change(sync() - old);
459 return *this;
462 controller_frame_vector::fchange_listener::~fchange_listener()
466 size_t controller_frame_vector::walk_helper(size_t frame, bool sflag) throw()
468 size_t ret = sflag ? frame : 0;
469 if(frame >= frames)
470 return ret;
471 frame++;
472 ret++;
473 size_t page = frame / frames_per_page;
474 size_t offset = frame_size * (frame % frames_per_page);
475 size_t index = frame % frames_per_page;
476 if(cache_page_num != page) {
477 cache_page = &pages[page];
478 cache_page_num = page;
480 while(frame < frames) {
481 if(index == frames_per_page) {
482 page++;
483 cache_page = &pages[page];
484 cache_page_num = page;
485 index = 0;
486 offset = 0;
488 if(controller_frame::sync(cache_page->content + offset))
489 break;
490 index++;
491 offset += frame_size;
492 frame++;
493 ret++;
495 return ret;
498 size_t controller_frame_vector::recount_frames() throw()
500 uint64_t old_frame_count = real_frame_count;
501 size_t ret = 0;
502 if(!frames)
503 return 0;
504 cache_page_num = 0;
505 cache_page = &pages[0];
506 size_t offset = 0;
507 size_t index = 0;
508 for(size_t i = 0; i < frames; i++) {
509 if(index == frames_per_page) {
510 cache_page_num++;
511 cache_page = &pages[cache_page_num];
512 index = 0;
513 offset = 0;
515 if(controller_frame::sync(cache_page->content + offset))
516 ret++;
517 index++;
518 offset += frame_size;
521 real_frame_count = ret;
522 call_framecount_notification(old_frame_count);
523 return ret;
526 void controller_frame_vector::clear(const port_type_set& p) throw(std::runtime_error)
528 uint64_t old_frame_count = real_frame_count;
529 frame_size = p.size();
530 frames_per_page = CONTROLLER_PAGE_SIZE / frame_size;
531 frames = 0;
532 types = &p;
533 clear_cache();
534 pages.clear();
535 real_frame_count = 0;
536 call_framecount_notification(old_frame_count);
539 controller_frame_vector::~controller_frame_vector() throw()
541 pages.clear();
542 cache_page = NULL;
545 controller_frame_vector::controller_frame_vector() throw()
547 real_frame_count = 0;
548 freeze_count = 0;
549 clear(dummytypes());
552 controller_frame_vector::controller_frame_vector(const port_type_set& p) throw()
554 real_frame_count = 0;
555 freeze_count = 0;
556 clear(p);
559 void controller_frame_vector::append(controller_frame frame) throw(std::bad_alloc, std::runtime_error)
561 controller_frame check(*types);
562 if(!check.types_match(frame))
563 throw std::runtime_error("controller_frame_vector::append: Type mismatch");
564 if(frames % frames_per_page == 0) {
565 //Create new page.
566 pages[frames / frames_per_page];
568 //Write the entry.
569 size_t page = frames / frames_per_page;
570 size_t offset = frame_size * (frames % frames_per_page);
571 if(cache_page_num != page) {
572 cache_page_num = page;
573 cache_page = &pages[page];
575 controller_frame(cache_page->content + offset, *types) = frame;
576 if(frame.sync()) real_frame_count++;
577 frames++;
580 controller_frame_vector::controller_frame_vector(const controller_frame_vector& vector) throw(std::bad_alloc)
582 real_frame_count = 0;
583 freeze_count = 0;
584 clear(*vector.types);
585 *this = vector;
588 controller_frame_vector& controller_frame_vector::operator=(const controller_frame_vector& v)
589 throw(std::bad_alloc)
591 if(this == &v)
592 return *this;
593 uint64_t old_frame_count = real_frame_count;
594 resize(v.frames);
595 clear_cache();
597 //Copy the fields.
598 frame_size = v.frame_size;
599 frames_per_page = v.frames_per_page;
600 types = v.types;
601 real_frame_count = v.real_frame_count;
603 //This can't fail anymore. Copy the raw page contents.
604 size_t pagecount = (frames + frames_per_page - 1) / frames_per_page;
605 for(size_t i = 0; i < pagecount; i++) {
606 page& pg = pages[i];
607 const page& pg2 = v.pages.find(i)->second;
608 pg = pg2;
610 call_framecount_notification(old_frame_count);
611 return *this;
614 void controller_frame_vector::resize(size_t newsize) throw(std::bad_alloc)
616 clear_cache();
617 if(newsize == 0) {
618 clear();
619 } else if(newsize < frames) {
620 //Shrink movie.
621 uint64_t old_frame_count = real_frame_count;
622 for(size_t i = newsize; i < frames; i++)
623 if((*this)[i].sync()) real_frame_count--;
624 size_t current_pages = (frames + frames_per_page - 1) / frames_per_page;
625 size_t pages_needed = (newsize + frames_per_page - 1) / frames_per_page;
626 for(size_t i = pages_needed; i < current_pages; i++)
627 pages.erase(i);
628 //Now zeroize the excess memory.
629 if(newsize < pages_needed * frames_per_page) {
630 size_t offset = frame_size * (newsize % frames_per_page);
631 memset(pages[pages_needed - 1].content + offset, 0, CONTROLLER_PAGE_SIZE - offset);
633 frames = newsize;
634 call_framecount_notification(old_frame_count);
635 } else if(newsize > frames) {
636 //Enlarge movie.
637 size_t current_pages = (frames + frames_per_page - 1) / frames_per_page;
638 size_t pages_needed = (newsize + frames_per_page - 1) / frames_per_page;
639 //Create the needed pages.
640 for(size_t i = current_pages; i < pages_needed; i++) {
641 try {
642 pages[i];
643 } catch(...) {
644 for(size_t i = current_pages; i < pages_needed; i++)
645 if(pages.count(i))
646 pages.erase(i);
647 throw;
650 frames = newsize;
651 //This can use real_frame_count, because the real frame count won't change.
652 call_framecount_notification(real_frame_count);
656 bool controller_frame_vector::compatible(controller_frame_vector& with, uint64_t frame, const uint32_t* polls)
658 //Types have to match.
659 if(get_types() != with.get_types())
660 return false;
661 const port_type_set& pset = with.get_types();
662 //If new movie is before first frame, anything with same project_id is compatible.
663 if(frame == 0)
664 return true;
665 //Scan both movies until frame syncs are seen. Out of bounds reads behave as all neutral but frame
666 //sync done.
667 uint64_t syncs_seen = 0;
668 uint64_t frames_read = 0;
669 size_t old_size = size();
670 size_t new_size = with.size();
671 size_t pagenum = 0;
672 size_t ocomplete_pages = old_size / frames_per_page; //Round DOWN
673 size_t ncomplete_pages = new_size / frames_per_page; //Round DOWN
674 size_t complete_pages = min(ocomplete_pages, ncomplete_pages);
675 while(syncs_seen + frames_per_page < frame - 1 && pagenum < complete_pages) {
676 //Fast process page. The above condition guarantees that these pages are completely used.
677 auto opagedata = pages[pagenum].content;
678 auto npagedata = with.pages[pagenum].content;
679 size_t pagedataamt = frames_per_page * frame_size;
680 if(memcmp(opagedata, npagedata, pagedataamt))
681 return false;
682 frames_read += frames_per_page;
683 pagenum++;
684 for(size_t i = 0; i < pagedataamt; i += frame_size)
685 if(opagedata[i] & 1) syncs_seen++;
687 while(syncs_seen < frame - 1) {
688 controller_frame oldc = blank_frame(true), newc = with.blank_frame(true);
689 if(frames_read < old_size)
690 oldc = (*this)[frames_read];
691 if(frames_read < new_size)
692 newc = with[frames_read];
693 if(oldc != newc)
694 return false; //Mismatch.
695 frames_read++;
696 if(newc.sync())
697 syncs_seen++;
699 //We increment the counter one time too many.
700 frames_read--;
701 //Current frame. We need to compare each control up to poll counter.
702 uint64_t readable_old_subframes = 0, readable_new_subframes = 0;
703 uint64_t oldlen = find_next_sync(*this, frames_read);
704 uint64_t newlen = find_next_sync(with, frames_read);
705 if(frames_read < oldlen)
706 readable_old_subframes = oldlen - frames_read;
707 if(frames_read < newlen)
708 readable_new_subframes = newlen - frames_read;
709 //Then rest of the stuff.
710 for(unsigned i = 0; i < pset.indices(); i++) {
711 uint32_t p = polls[i] & 0x7FFFFFFFUL;
712 short ov = 0, nv = 0;
713 for(uint32_t j = 0; j < p; j++) {
714 if(j < readable_old_subframes)
715 ov = (*this)[j + frames_read].axis2(i);
716 if(j < readable_new_subframes)
717 nv = with[j + frames_read].axis2(i);
718 if(ov != nv)
719 return false;
722 return true;
725 uint64_t controller_frame_vector::binary_size() const throw()
727 return size() * get_stride();
730 void controller_frame_vector::save_binary(binarystream::output& stream) const throw(std::runtime_error)
732 uint64_t stride = get_stride();
733 uint64_t pageframes = get_frames_per_page();
734 uint64_t vsize = size();
735 size_t pagenum = 0;
736 while(vsize > 0) {
737 uint64_t count = (vsize > pageframes) ? pageframes : vsize;
738 size_t bytes = count * stride;
739 const unsigned char* content = get_page_buffer(pagenum++);
740 stream.raw(content, bytes);
741 vsize -= count;
745 void controller_frame_vector::load_binary(binarystream::input& stream) throw(std::bad_alloc, std::runtime_error)
747 uint64_t stride = get_stride();
748 uint64_t pageframes = get_frames_per_page();
749 uint64_t vsize = 0;
750 size_t pagenum = 0;
751 uint64_t pagesize = stride * pageframes;
752 while(stream.get_left()) {
753 resize(vsize + pageframes);
754 unsigned char* contents = get_page_buffer(pagenum++);
755 uint64_t gcount = min(pagesize, stream.get_left());
756 stream.raw(contents, gcount);
757 vsize += (gcount / stride);
759 resize(vsize);
760 recount_frames();
763 void controller_frame_vector::swap_data(controller_frame_vector& v) throw()
765 uint64_t toldsize = real_frame_count;
766 uint64_t voldsize = v.real_frame_count;
767 std::swap(pages, v.pages);
768 std::swap(frames_per_page, v.frames_per_page);
769 std::swap(frame_size, v.frame_size);
770 std::swap(frames, v.frames);
771 std::swap(types, v.types);
772 std::swap(cache_page_num, v.cache_page_num);
773 std::swap(cache_page, v.cache_page);
774 std::swap(real_frame_count, v.real_frame_count);
775 if(!freeze_count)
776 call_framecount_notification(toldsize);
777 if(!v.freeze_count)
778 v.call_framecount_notification(voldsize);
781 int64_t controller_frame_vector::find_frame(uint64_t n)
783 if(!n) return -1;
784 uint64_t stride = get_stride();
785 uint64_t pageframes = get_frames_per_page();
786 uint64_t vsize = size();
787 size_t pagenum = 0;
788 while(vsize > 0) {
789 uint64_t count = (vsize > pageframes) ? pageframes : vsize;
790 const unsigned char* content = get_page_buffer(pagenum++);
791 size_t offset = 0;
792 for(unsigned i = 0; i < count; i++) {
793 if(controller_frame::sync(content + offset)) n--;
794 if(n == 0) return (pagenum - 1) * pageframes + i;
795 offset += stride;
797 vsize -= count;
799 return -1;
802 controller_frame::controller_frame() throw()
804 memset(memory, 0, sizeof(memory));
805 backing = memory;
806 types = &dummytypes();
807 host = NULL;
810 unsigned port_controller::analog_actions() const
812 unsigned r = 0, s = 0;
813 for(unsigned i = 0; i < buttons.size(); i++) {
814 if(buttons[i].shadow)
815 continue;
816 switch(buttons[i].type) {
817 case port_controller_button::TYPE_AXIS:
818 case port_controller_button::TYPE_RAXIS:
819 case port_controller_button::TYPE_LIGHTGUN:
820 r++;
821 break;
822 case port_controller_button::TYPE_TAXIS:
823 s++;
824 break;
825 case port_controller_button::TYPE_NULL:
826 case port_controller_button::TYPE_BUTTON:
830 return (r + 1)/ 2 + s;
833 std::pair<unsigned, unsigned> port_controller::analog_action(unsigned k) const
835 unsigned x1 = std::numeric_limits<unsigned>::max();
836 unsigned x2 = std::numeric_limits<unsigned>::max();
837 unsigned r = 0;
838 bool second = false;
839 bool selecting = false;
840 for(unsigned i = 0; i < buttons.size(); i++) {
841 if(buttons[i].shadow)
842 continue;
843 switch(buttons[i].type) {
844 case port_controller_button::TYPE_AXIS:
845 case port_controller_button::TYPE_RAXIS:
846 case port_controller_button::TYPE_LIGHTGUN:
847 if(selecting) {
848 x2 = i;
849 goto out;
851 if(r == k && !second) {
852 //This and following.
853 x1 = i;
854 selecting = true;
856 if(!second)
857 r++;
858 second = !second;
859 break;
860 case port_controller_button::TYPE_TAXIS:
861 if(selecting)
862 break;
863 if(r == k) {
864 x1 = i;
865 goto out;
867 r++;
868 break;
869 case port_controller_button::TYPE_NULL:
870 case port_controller_button::TYPE_BUTTON:
874 out:
875 return std::make_pair(x1, x2);
878 namespace
880 std::string macro_field_as_string(const JSON::node& parent, const std::string& path)
882 const JSON::node& n = parent.follow(path);
883 if(n.type() != JSON::string)
884 (stringfmt() << "Expected string as field '" << path << "'").throwex();
885 return n.as_string8();
888 bool macro_field_as_boolean(const JSON::node& parent, const std::string& path)
890 const JSON::node& n = parent.follow(path);
891 if(n.type() != JSON::boolean)
892 (stringfmt() << "Expected boolean as field '" << path << "'").throwex();
893 return n.as_bool();
896 const JSON::node& macro_field_as_array(const JSON::node& parent, const std::string& path)
898 const JSON::node& n = parent.follow(path);
899 if(n.type() != JSON::array)
900 (stringfmt() << "Expected array as field '" << path << "'").throwex();
901 return n;
905 controller_macro_data::controller_macro_data(const std::string& spec, const JSON::node& desc, unsigned inum)
907 _descriptor = desc;
908 unsigned btnnum = 0;
909 std::map<std::string, unsigned> symbols;
910 if(desc.type() != JSON::array)
911 (stringfmt() << "Expected controller descriptor " << (inum + 1) << " to be an array");
912 for(auto i = desc.begin(); i != desc.end(); ++i) {
913 if(i->type() == JSON::string) {
914 symbols[i->as_string8()] = btnnum++;
915 btnmap.push_back(i.index());
916 } else if(i->type() == JSON::number) {
917 uint64_t anum = i->as_uint();
918 if(anum > aaxes.size())
919 (stringfmt() << "Descriptor axis number " << anum << " out of range in descriptor "
920 << (inum + 1)).throwex();
921 else if(anum == aaxes.size())
922 aaxes.push_back(std::make_pair(i.index(), std::numeric_limits<unsigned>::max()));
923 else
924 aaxes[anum].second = i.index();
925 } else
926 (stringfmt() << "Controller descriptor " << (inum + 1) << " contains element of unknown"
927 << "kind").throwex();
929 buttons = symbols.size();
930 orig = spec;
931 enabled = true;
932 autoterminate = false;
934 std::deque<size_t> stack;
935 bool in_sparen = false;
936 bool first = true;
937 bool btn_token = false;
938 bool btn_token_next = false;
939 size_t last_bit = 0;
940 size_t last_size = 0;
941 size_t astride = aaxes.size();
942 size_t stride = get_stride();
943 size_t idx = 0;
944 size_t len = spec.length();
945 try {
946 while(idx < len) {
947 btn_token = btn_token_next;
948 btn_token_next = false;
949 unsigned char ch = spec[idx];
950 if(autoterminate)
951 throw std::runtime_error("Asterisk must be the last thing");
952 if(ch == '(') {
953 if(in_sparen)
954 throw std::runtime_error("Parentheses in square brackets not allowed");
955 stack.push_back(data.size());
956 } else if(ch == ')') {
957 if(in_sparen)
958 throw std::runtime_error("Parentheses in square brackets not allowed");
959 if(stack.empty())
960 throw std::runtime_error("Unmatched right parenthesis");
961 size_t x = stack.back();
962 stack.pop_back();
963 last_size = (data.size() - x) / stride;
964 } else if(ch == '*') {
965 autoterminate = true;
966 } else if(ch == '?') {
967 if(!btn_token)
968 throw std::runtime_error("? needs button to apply to");
969 if(!in_sparen)
970 throw std::runtime_error("? needs to be in brackets");
971 data[data.size() - stride + last_bit] |= 2;
972 } else if(ch == '[') {
973 if(in_sparen)
974 throw std::runtime_error("Nested square brackets not allowed");
975 in_sparen = true;
976 data.resize(data.size() + stride);
977 adata.resize(adata.size() + astride);
978 last_size = 1;
979 } else if(ch == ']') {
980 if(!in_sparen)
981 throw std::runtime_error("Unmatched right square bracket");
982 in_sparen = false;
983 } else if(ch == '.') {
984 if(!in_sparen) {
985 data.resize(data.size() + stride);
986 adata.resize(adata.size() + astride);
987 last_size = 1;
989 } else if(spec[idx] >= '0' && spec[idx] <= '9') {
990 size_t rep = 0;
991 unsigned i = 0;
992 while(spec[idx + i] >= '0' && spec[idx + i] <= '9') {
993 rep = 10 * rep + (spec[idx + i] - '0');
994 i++;
996 if(in_sparen) {
997 //This has special meaning: Axis transform.
998 //Rep is the axis pair to operate on.
999 if(spec[idx + i] != ':')
1000 throw std::runtime_error("Expected ':' in axis transform");
1001 size_t sep = i;
1002 while(idx + i < len && spec[idx + i] != '@')
1003 i++;
1004 if(idx + i >= len)
1005 throw std::runtime_error("Expected '@' in axis transform");
1006 std::string aexpr = spec.substr(idx + sep + 1, i - sep - 1);
1007 if(rep >= astride)
1008 throw std::runtime_error("Axis transform refers to invalid axis");
1009 adata[adata.size() - astride + rep] = axis_transform(aexpr);
1010 i++;
1011 } else {
1012 if(first)
1013 throw std::runtime_error("Repeat not allowed without frame to "
1014 "repeat");
1015 size_t o = data.size();
1016 size_t ao = adata.size();
1017 data.resize(o + (rep - 1) * last_size * stride);
1018 adata.resize(ao + (rep - 1) * last_size * astride);
1019 for(unsigned i = 1; i < rep; i++) {
1020 memcpy(&data[o + (i - 1) * last_size * stride], &data[o - last_size *
1021 stride], last_size * stride);
1022 memcpy(&data[ao + (i - 1) * last_size * astride], &data[ao -
1023 last_size * astride], last_size * astride);
1025 last_size = last_size * rep;
1027 idx = idx + (i - 1);
1028 } else { //Symbol.
1029 bool found = false;
1030 for(auto k : symbols) {
1031 std::string key = k.first;
1032 size_t j;
1033 for(j = 0; idx + j < len && j < key.length(); j++)
1034 if(spec[idx + j] != key[j])
1035 break;
1036 if(j == key.length()) {
1037 idx += key.length() - 1;
1038 found = true;
1039 if(!in_sparen) {
1040 data.resize(data.size() + stride);
1041 adata.resize(adata.size() + astride);
1043 last_bit = k.second;
1044 data[data.size() - stride + k.second] |= 1;
1045 if(!in_sparen)
1046 last_size = 1;
1049 if(!found)
1050 throw std::runtime_error("Unknown character or button");
1051 btn_token_next = true;
1053 idx++;
1054 first = false;
1056 if(in_sparen)
1057 throw std::runtime_error("Unmatched left square bracket");
1058 if(!stack.empty())
1059 throw std::runtime_error("Unmatched left parenthesis");
1060 } catch(std::exception& e) {
1061 (stringfmt() << "Error parsing macro for controller " << (inum + 1) << ": " << e.what()).throwex();
1065 bool controller_macro_data::syntax_check(const std::string& spec, const JSON::node& desc)
1067 unsigned buttons = 0;
1068 size_t astride = 0;
1069 if(desc.type() != JSON::array)
1070 return false;
1071 for(auto i = desc.begin(); i != desc.end(); ++i) {
1072 if(i->type() == JSON::string)
1073 buttons++;
1074 else if(i->type() == JSON::number) {
1075 uint64_t anum = i->as_uint();
1076 if(anum > astride)
1077 return false;
1078 else if(anum == astride)
1079 astride++;
1080 } else
1081 return false;
1083 bool autoterminate = false;
1084 size_t depth = 0;
1085 bool in_sparen = false;
1086 bool first = true;
1087 bool btn_token = false;
1088 bool btn_token_next = false;
1089 size_t idx = 0;
1090 size_t len = spec.length();
1091 while(idx < len) {
1092 btn_token = btn_token_next;
1093 btn_token_next = false;
1094 unsigned char ch = spec[idx];
1095 if(autoterminate)
1096 return false;
1097 if(ch == '(') {
1098 if(in_sparen)
1099 return false;
1100 depth++;
1101 } else if(ch == ')') {
1102 if(in_sparen)
1103 return false;
1104 if(!depth)
1105 return false;
1106 depth--;
1107 } else if(ch == '*') {
1108 autoterminate = true;
1109 } else if(ch == '?') {
1110 if(!btn_token || !in_sparen)
1111 return false;
1112 } else if(ch == '[') {
1113 if(in_sparen)
1114 return false;
1115 in_sparen = true;
1116 } else if(ch == ']') {
1117 if(!in_sparen)
1118 return false;
1119 in_sparen = false;
1120 } else if(ch == '.') {
1121 } else if(spec[idx] >= '0' && spec[idx] <= '9') {
1122 size_t rep = 0;
1123 unsigned i = 0;
1124 while(spec[idx + i] >= '0' && spec[idx + i] <= '9') {
1125 rep = 10 * rep + (spec[idx + i] - '0');
1126 i++;
1128 if(in_sparen) {
1129 //This has special meaning: Axis transform.
1130 //Rep is the axis pair to operate on.
1131 if(spec[idx + i] != ':')
1132 return false;
1133 size_t sep = i;
1134 while(idx + i < len && spec[idx + i] != '@')
1135 i++;
1136 if(idx + i >= len)
1137 return false;
1138 if(rep >= astride)
1139 return false;
1140 try {
1141 std::string aexpr = spec.substr(idx + sep + 1, i - sep - 1);
1142 axis_transform x(aexpr);
1143 } catch(...) {
1144 return false;
1146 i++;
1147 } else {
1148 if(first)
1149 return false;
1151 idx = idx + (i - 1);
1152 } else { //Symbol.
1153 bool found = false;
1154 for(auto i = desc.begin(); i != desc.end(); ++i) {
1155 if(i->type() != JSON::string)
1156 continue;
1157 std::string key = i->as_string8();
1158 size_t j;
1159 for(j = 0; idx + j < len && j < key.length(); j++)
1160 if(spec[idx + j] != key[j])
1161 break;
1162 if(j == key.length()) {
1163 idx += key.length() - 1;
1164 found = true;
1167 if(!found)
1168 return false;
1169 btn_token_next = true;
1171 idx++;
1172 first = false;
1174 if(in_sparen)
1175 return false;
1176 if(depth)
1177 return false;
1178 return true;
1181 void controller_macro_data::write(controller_frame& frame, unsigned port, unsigned controller, int64_t nframe,
1182 apply_mode amode)
1184 if(!enabled)
1185 return;
1186 if(autoterminate && (nframe < 0 || nframe >= (int64_t)get_frames()))
1187 return;
1188 if(nframe < 0)
1189 nframe += ((-nframe / get_frames()) + 3) * get_frames();
1190 nframe %= get_frames();
1191 for(size_t i = 0; i < buttons; i++) {
1192 unsigned lb = btnmap[i];
1193 unsigned st = data[nframe * get_stride() + i];
1194 if(st == 3)
1195 st = macro_random_bit();
1196 if(st == 1)
1197 switch(amode) {
1198 case AM_OVERWRITE:
1199 case AM_OR:
1200 frame.axis3(port, controller, lb, 1);
1201 break;
1202 case AM_XOR:
1203 frame.axis3(port, controller, lb, frame.axis3(port, controller, lb) ^ 1);
1204 break;
1206 else
1207 switch(amode) {
1208 case AM_OVERWRITE:
1209 frame.axis3(port, controller, lb, 0);
1210 break;
1211 case AM_OR:
1212 case AM_XOR:
1216 const port_controller* _ctrl = frame.porttypes().port_type(port).controller_info->get(controller);
1217 if(!_ctrl)
1218 return;
1219 size_t abuttons = aaxes.size();
1220 for(size_t i = 0; i < abuttons; i++) {
1221 unsigned ax = aaxes[i].first;
1222 unsigned ay = aaxes[i].second;
1223 if(ay != std::numeric_limits<unsigned>::max()) {
1224 if(ax > _ctrl->buttons.size()) continue;
1225 if(ay > _ctrl->buttons.size()) continue;
1226 auto g = adata[nframe * abuttons + i].transform(_ctrl->buttons[ax], _ctrl->buttons[ay],
1227 frame.axis3(port, controller, ax), frame.axis3(port, controller, ay));
1228 frame.axis3(port, controller, ax, g.first);
1229 frame.axis3(port, controller, ay, g.second);
1230 } else {
1231 if(ax > _ctrl->buttons.size()) continue;
1232 int16_t g = adata[nframe * abuttons + i].transform(_ctrl->buttons[ax],
1233 frame.axis3(port, controller, ax));
1234 frame.axis3(port, controller, ax, g);
1239 std::string controller_macro_data::dump(const port_controller& ctrl)
1241 std::ostringstream o;
1242 for(size_t i = 0; i < get_frames(); i++) {
1243 o << "[";
1244 for(size_t j = 0; j < aaxes.size(); j++) {
1245 controller_macro_data::axis_transform& t = adata[i * aaxes.size() + j];
1246 o << j << ":";
1247 o << t.coeffs[0] << "," << t.coeffs[1] << "," << t.coeffs[2] << ",";
1248 o << t.coeffs[3] << "," << t.coeffs[4] << "," << t.coeffs[5] << "@";
1250 for(size_t j = 0; j < buttons && j < ctrl.buttons.size(); j++) {
1251 unsigned st = data[i * get_stride() + j];
1252 if(ctrl.buttons[j].macro == "")
1253 continue;
1254 if(st == 1)
1255 o << ctrl.buttons[j].macro;
1256 if(st == 3)
1257 o << ctrl.buttons[j].macro << "?";
1259 o << "]";
1261 if(autoterminate)
1262 o << "*";
1263 return o.str();
1266 void controller_macro::write(controller_frame& frame, int64_t nframe)
1268 for(auto& i : macros) {
1269 unsigned port;
1270 unsigned controller;
1271 try {
1272 auto g = frame.porttypes().lcid_to_pcid(i.first);
1273 port = g.first;
1274 controller = g.second;
1275 } catch(...) {
1276 continue;
1278 i.second.write(frame, port, controller, nframe, amode);
1282 int16_t controller_macro_data::axis_transform::transform(const port_controller_button& b, int16_t v)
1284 return scale_axis(b, coeffs[0] * unscale_axis(b, v) + coeffs[4]);
1287 std::pair<int16_t, int16_t> controller_macro_data::axis_transform::transform(const port_controller_button& b1,
1288 const port_controller_button& b2, int16_t v1, int16_t v2)
1290 double x, y, u, v, au, av, s;
1291 x = unscale_axis(b1, v1);
1292 y = unscale_axis(b2, v2);
1293 u = coeffs[0] * x + coeffs[1] * y + coeffs[4];
1294 v = coeffs[2] * x + coeffs[3] * y + coeffs[5];
1295 au = abs(u);
1296 av = abs(v);
1297 s = max(max(au, 1.0), max(av, 1.0));
1298 //If u and v exceed nominal range of [-1,1], those need to be projected to the edge.
1299 if(s > 1) {
1300 u /= s;
1301 v /= s;
1303 auto g = std::make_pair(scale_axis(b1, u), scale_axis(b2, v));
1304 return g;
1307 double controller_macro_data::axis_transform::unscale_axis(const port_controller_button& b, int16_t v)
1309 if(b.centers) {
1310 int32_t center = ((int32_t)b.rmin + (int32_t)b.rmax) / 2;
1311 if(v <= b.rmin)
1312 return -1;
1313 if(v < center)
1314 return -(center - (double)v) / (center - b.rmin);
1315 if(v == center)
1316 return 0;
1317 if(v < b.rmax)
1318 return ((double)v - center) / (b.rmax - center);
1319 return 1;
1320 } else {
1321 if(v <= b.rmin)
1322 return 0;
1323 if(v >= b.rmax)
1324 return 1;
1325 return ((double)v - b.rmin) / (b.rmax - b.rmin);
1329 int16_t controller_macro_data::axis_transform::scale_axis(const port_controller_button& b, double v)
1331 if(b.centers) {
1332 int32_t center = ((int32_t)b.rmin + (int32_t)b.rmax) / 2;
1333 if(v == 0)
1334 return center;
1335 if(v < 0) {
1336 double v2 = v * (center - b.rmin) + center;
1337 if(v2 < b.rmin)
1338 return b.rmin;
1339 return v2;
1341 double v2 = v * (b.rmax - center) + center;
1342 if(v2 > b.rmax)
1343 return b.rmax;
1344 return v2;
1345 } else {
1346 double v2 = v * (b.rmax - b.rmin) + b.rmin;
1347 if(v2 < b.rmin)
1348 return b.rmin;
1349 if(v2 > b.rmax)
1350 return b.rmax;
1351 return v2;
1355 namespace
1357 std::complex<double> parse_complex(const std::string& expr)
1359 regex_results r;
1360 if(r = regex("\\((.*),(.*)\\)", expr)) {
1361 //Real,Imaginary.
1362 return std::complex<double>(parse_value<double>(r[1]), parse_value<double>(r[2]));
1363 } else if(r = regex("\\((.*)<(.*)\\)", expr)) {
1364 return std::polar(parse_value<double>(r[1]), parse_value<double>(r[2]) * M_PI / 180);
1365 } else {
1366 return std::complex<double>(parse_value<double>(expr), 0.0);
1371 controller_macro_data::axis_transform::axis_transform(const std::string& expr)
1373 regex_results r;
1374 if(r = regex("\\*(.*)\\+(.*)", expr)) {
1375 //Affine transform.
1376 std::complex<double> a = parse_complex(r[1]);
1377 std::complex<double> b = parse_complex(r[2]);
1378 coeffs[0] = a.real();
1379 coeffs[1] = -a.imag();
1380 coeffs[2] = a.imag();
1381 coeffs[3] = a.real();
1382 coeffs[4] = b.real();
1383 coeffs[5] = b.imag();
1384 } else if(r = regex("\\*(.*)", expr)) {
1385 //Linear transform.
1386 std::complex<double> a = parse_complex(r[1]);
1387 coeffs[0] = a.real();
1388 coeffs[1] = -a.imag();
1389 coeffs[2] = a.imag();
1390 coeffs[3] = a.real();
1391 coeffs[4] = 0;
1392 coeffs[5] = 0;
1393 } else if(r = regex("\\+(.*)", expr)) {
1394 //Relative
1395 std::complex<double> b = parse_complex(r[1]);
1396 coeffs[0] = 1;
1397 coeffs[1] = 0;
1398 coeffs[2] = 0;
1399 coeffs[3] = 1;
1400 coeffs[4] = b.real();
1401 coeffs[5] = b.imag();
1402 } else if(r = regex("(.*),(.*),(.*),(.*),(.*),(.*)", expr)) {
1403 //Full affine.
1404 coeffs[0] = parse_value<double>(r[1]);
1405 coeffs[1] = parse_value<double>(r[2]);
1406 coeffs[2] = parse_value<double>(r[3]);
1407 coeffs[3] = parse_value<double>(r[4]);
1408 coeffs[4] = parse_value<double>(r[5]);
1409 coeffs[5] = parse_value<double>(r[6]);
1410 } else {
1411 //Absolute.
1412 std::complex<double> b = parse_complex(expr);
1413 coeffs[0] = 0;
1414 coeffs[1] = 0;
1415 coeffs[2] = 0;
1416 coeffs[3] = 0;
1417 coeffs[4] = b.real();
1418 coeffs[5] = b.imag();
1422 JSON::node controller_macro::serialize()
1424 JSON::node v(JSON::object);
1425 switch(amode) {
1426 case controller_macro_data::AM_OVERWRITE: v.insert("mode", JSON::s("overwrite")); break;
1427 case controller_macro_data::AM_OR: v.insert("mode", JSON::s("or")); break;
1428 case controller_macro_data::AM_XOR: v.insert("mode", JSON::s("xor")); break;
1430 JSON::node& c = v.insert("data", JSON::array());
1431 for(auto& i : macros) {
1432 while(i.first > c.index_count())
1433 c.append(JSON::n());
1434 i.second.serialize(c.append(JSON::n()));
1436 return v;
1439 void controller_macro_data::serialize(JSON::node& v)
1441 v = JSON::object();
1442 v.insert("enable", JSON::b(enabled));
1443 v.insert("expr", JSON::s(orig));
1444 v.insert("desc", _descriptor);
1447 JSON::node controller_macro_data::make_descriptor(const port_controller& ctrl)
1449 JSON::node n(JSON::array);
1450 for(size_t i = 0; i < ctrl.buttons.size(); i++) {
1451 if(ctrl.buttons[i].macro != "")
1452 n.append(JSON::s(ctrl.buttons[i].macro));
1453 else
1454 n.append(JSON::n()); //Placeholder.
1456 for(size_t i = 0; i < ctrl.analog_actions(); i++) {
1457 auto g = ctrl.analog_action(i);
1458 n.index(g.first) = JSON::u(i);
1459 if(g.second != std::numeric_limits<unsigned>::max())
1460 n.index(g.second) = JSON::u(i);
1462 return n;
1465 controller_macro::controller_macro(const JSON::node& v)
1467 if(v.type() != JSON::object)
1468 throw std::runtime_error("Expected macro to be JSON object");
1469 std::string mode = macro_field_as_string(v, "mode");
1470 if(mode == "overwrite") amode = controller_macro_data::AM_OVERWRITE;
1471 else if(mode == "or") amode = controller_macro_data::AM_OR;
1472 else if(mode == "xor") amode = controller_macro_data::AM_XOR;
1473 else (stringfmt() << "Unknown button mode '" << mode << "'").throwex();
1474 const JSON::node& c = macro_field_as_array(v, "data");
1475 for(auto i = c.begin(); i != c.end(); ++i) {
1476 if(i->type() == JSON::object)
1477 macros[i.index()] = controller_macro_data(*i, i.index());
1478 else
1479 (stringfmt() << "Expected object as field 'data/" << i.index() << "'").throwex();
1483 controller_macro_data::controller_macro_data(const JSON::node& v, unsigned i)
1484 : controller_macro_data(macro_field_as_string(v, "expr"), macro_field_as_array(v, "desc"), i)
1486 enabled = macro_field_as_boolean(v, "enable");