1 #include "binarystream.hpp"
2 #include "controller-data.hpp"
5 #include "globalwrap.hpp"
6 #include "serialization.hpp"
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
,
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
) ->
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' : '-';
40 deserialize
= [](const port_type
* _this
, unsigned char* buffer
, const char* textbuf
) ->
44 if(read_button_value(textbuf
, ptr
))
46 skip_rest_of_field(textbuf
, ptr
, false);
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) {
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);
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
;
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
;
94 size_t dummy_offset
= 0;
95 port_type
* dummy_type
= &get_default_system_port_type();
96 unsigned dummy_index
= 0;
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())
105 for(size_t i
= 0; i
< x
.size(); i
++)
111 std::list
<binding
>& bindings()
113 static std::list
<binding
> x
;
118 port_type_set::port_type_set() throw()
121 port_offsets
= &dummy_offset
;
122 port_types
= &dummy_type
;
126 _indices
[0].valid
= true;
127 _indices
[0].port
= 0;
128 _indices
[0].controller
= 0;
129 _indices
[0].control
= 0;
132 controller_multiplier
= 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())
143 //Not found, create new.
144 port_type_set
& ret
= *new port_type_set(types
, control_map
);
148 bindings().push_back(b
);
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.
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.
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
];
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
];
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()
200 while(is_nonterminator(buf
[idx
])) {
202 if(ch
!= ' ' && ch
!= '\t')
206 //Read the sign if any.
208 if(!is_nonterminator(ch
))
210 bool negative
= false;
218 //Read numeric value.
220 while(is_nonterminator(buf
[idx
]) && isdigit(static_cast<unsigned char>(ch
= buf
[idx
]))) {
221 numval
= numval
* 10 + (ch
- '0');
227 return static_cast<short>(numval
);
232 port_type_set
& dummytypes()
234 static port_type_set x
;
238 size_t writeu32val(char32_t
* buf
, int val
)
242 sprintf(c
, "%d", val
);
243 for(i
= 0; c
[i
]; i
++)
248 uint64_t find_next_sync(controller_frame_vector
& movie
, uint64_t after
)
250 if(after
>= movie
.size())
254 } while(after
< movie
.size() && !movie
[after
].sync());
259 void controller_frame::display(unsigned port
, unsigned controller
, char32_t
* buf
) throw()
261 if(port
>= types
->ports()) {
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()) {
273 const port_controller
& pc
= ptype
.controller_info
->controllers
[controller
];
274 bool need_space
= false;
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
) {
283 case port_controller_button::TYPE_NULL
:
285 case port_controller_button::TYPE_BUTTON
:
286 *(buf
++) = ptype
.read(&ptype
, backingmem
, controller
, i
) ? pcb
.symbol
: U
'-';
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
);
301 pollcounter_vector::pollcounter_vector() throw(std::bad_alloc
)
303 types
= &dummytypes();
304 ctrs
= new uint32_t[types
->indices()];
308 pollcounter_vector::pollcounter_vector(const port_type_set
& p
) throw(std::bad_alloc
)
311 ctrs
= new uint32_t[types
->indices()];
315 pollcounter_vector::pollcounter_vector(const pollcounter_vector
& p
) throw(std::bad_alloc
)
317 ctrs
= new uint32_t[p
.types
->indices()];
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
)
327 uint32_t* n
= new uint32_t[p
.types
->indices()];
329 memcpy(n
, p
.ctrs
, sizeof(uint32_t) * p
.types
->indices());
332 framepflag
= p
.framepflag
;
336 pollcounter_vector::~pollcounter_vector() throw()
341 void pollcounter_vector::clear() throw()
343 memset(ctrs
, 0, sizeof(uint32_t) * types
->indices());
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()
366 for(size_t i
= 0; i
< types
->indices() ; 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
;
383 uint32_t pollcounter_vector::max_polls() throw()
386 for(unsigned i
= 0; i
< types
->indices(); i
++) {
387 uint32_t tmp
= ctrs
[i
] & 0x7FFFFFFFUL
;
388 max
= (max
< tmp
) ? tmp
: max
;
393 void pollcounter_vector::save_state(std::vector
<uint32_t>& mem
) throw(std::bad_alloc
)
395 mem
.resize(types
->indices());
397 for(size_t i
= 0; i
< types
->indices(); i
++)
401 void pollcounter_vector::load_state(const std::vector
<uint32_t>& mem
) throw()
403 for(size_t i
= 0; i
< types
->indices(); 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()
418 bool pollcounter_vector::get_framepflag() const throw()
423 controller_frame::controller_frame(const port_type_set
& p
) throw(std::runtime_error
)
425 memset(memory
, 0, sizeof(memory
));
431 controller_frame::controller_frame(unsigned char* mem
, const port_type_set
& p
, controller_frame_vector
* _host
)
432 throw(std::runtime_error
)
435 throw std::runtime_error("NULL backing memory not allowed");
436 memset(memory
, 0, sizeof(memory
));
442 controller_frame::controller_frame(const controller_frame
& obj
) throw()
444 memset(memory
, 0, sizeof(memory
));
447 memcpy(backing
, obj
.backing
, types
->size());
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");
457 memcpy(backing
, obj
.backing
, types
->size());
458 if(host
) host
->notify_sync_change(sync() - old
);
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;
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
) {
483 cache_page
= &pages
[page
];
484 cache_page_num
= page
;
488 if(controller_frame::sync(cache_page
->content
+ offset
))
491 offset
+= frame_size
;
498 size_t controller_frame_vector::recount_frames() throw()
500 uint64_t old_frame_count
= real_frame_count
;
505 cache_page
= &pages
[0];
508 for(size_t i
= 0; i
< frames
; i
++) {
509 if(index
== frames_per_page
) {
511 cache_page
= &pages
[cache_page_num
];
515 if(controller_frame::sync(cache_page
->content
+ offset
))
518 offset
+= frame_size
;
521 real_frame_count
= ret
;
522 call_framecount_notification(old_frame_count
);
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
;
535 real_frame_count
= 0;
536 call_framecount_notification(old_frame_count
);
539 controller_frame_vector::~controller_frame_vector() throw()
545 controller_frame_vector::controller_frame_vector() throw()
547 real_frame_count
= 0;
552 controller_frame_vector::controller_frame_vector(const port_type_set
& p
) throw()
554 real_frame_count
= 0;
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) {
566 pages
[frames
/ frames_per_page
];
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
++;
580 controller_frame_vector::controller_frame_vector(const controller_frame_vector
& vector
) throw(std::bad_alloc
)
582 real_frame_count
= 0;
584 clear(*vector
.types
);
588 controller_frame_vector
& controller_frame_vector::operator=(const controller_frame_vector
& v
)
589 throw(std::bad_alloc
)
593 uint64_t old_frame_count
= real_frame_count
;
598 frame_size
= v
.frame_size
;
599 frames_per_page
= v
.frames_per_page
;
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
++) {
607 const page
& pg2
= v
.pages
.find(i
)->second
;
610 call_framecount_notification(old_frame_count
);
614 void controller_frame_vector::resize(size_t newsize
) throw(std::bad_alloc
)
619 } else if(newsize
< frames
) {
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
++)
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
);
634 call_framecount_notification(old_frame_count
);
635 } else if(newsize
> frames
) {
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
++) {
644 for(size_t i
= current_pages
; i
< pages_needed
; i
++)
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())
661 const port_type_set
& pset
= with
.get_types();
662 //If new movie is before first frame, anything with same project_id is compatible.
665 //Scan both movies until frame syncs are seen. Out of bounds reads behave as all neutral but frame
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();
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
))
682 frames_read
+= frames_per_page
;
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
];
694 return false; //Mismatch.
699 //We increment the counter one time too many.
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
);
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();
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
);
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();
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
);
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
);
776 call_framecount_notification(toldsize
);
778 v
.call_framecount_notification(voldsize
);
781 int64_t controller_frame_vector::find_frame(uint64_t n
)
784 uint64_t stride
= get_stride();
785 uint64_t pageframes
= get_frames_per_page();
786 uint64_t vsize
= size();
789 uint64_t count
= (vsize
> pageframes
) ? pageframes
: vsize
;
790 const unsigned char* content
= get_page_buffer(pagenum
++);
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
;
802 controller_frame::controller_frame() throw()
804 memset(memory
, 0, sizeof(memory
));
806 types
= &dummytypes();
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
)
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
:
822 case port_controller_button::TYPE_TAXIS
:
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();
839 bool selecting
= false;
840 for(unsigned i
= 0; i
< buttons
.size(); i
++) {
841 if(buttons
[i
].shadow
)
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
:
851 if(r
== k
&& !second
) {
852 //This and following.
860 case port_controller_button::TYPE_TAXIS
:
869 case port_controller_button::TYPE_NULL
:
870 case port_controller_button::TYPE_BUTTON
:
875 return std::make_pair(x1
, x2
);
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();
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();
905 controller_macro_data::controller_macro_data(const std::string
& spec
, const JSON::node
& desc
, unsigned inum
)
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()));
924 aaxes
[anum
].second
= i
.index();
926 (stringfmt() << "Controller descriptor " << (inum
+ 1) << " contains element of unknown"
927 << "kind").throwex();
929 buttons
= symbols
.size();
932 autoterminate
= false;
934 std::deque
<size_t> stack
;
935 bool in_sparen
= false;
937 bool btn_token
= false;
938 bool btn_token_next
= false;
940 size_t last_size
= 0;
941 size_t astride
= aaxes
.size();
942 size_t stride
= get_stride();
944 size_t len
= spec
.length();
947 btn_token
= btn_token_next
;
948 btn_token_next
= false;
949 unsigned char ch
= spec
[idx
];
951 throw std::runtime_error("Asterisk must be the last thing");
954 throw std::runtime_error("Parentheses in square brackets not allowed");
955 stack
.push_back(data
.size());
956 } else if(ch
== ')') {
958 throw std::runtime_error("Parentheses in square brackets not allowed");
960 throw std::runtime_error("Unmatched right parenthesis");
961 size_t x
= stack
.back();
963 last_size
= (data
.size() - x
) / stride
;
964 } else if(ch
== '*') {
965 autoterminate
= true;
966 } else if(ch
== '?') {
968 throw std::runtime_error("? needs button to apply to");
970 throw std::runtime_error("? needs to be in brackets");
971 data
[data
.size() - stride
+ last_bit
] |= 2;
972 } else if(ch
== '[') {
974 throw std::runtime_error("Nested square brackets not allowed");
976 data
.resize(data
.size() + stride
);
977 adata
.resize(adata
.size() + astride
);
979 } else if(ch
== ']') {
981 throw std::runtime_error("Unmatched right square bracket");
983 } else if(ch
== '.') {
985 data
.resize(data
.size() + stride
);
986 adata
.resize(adata
.size() + astride
);
989 } else if(spec
[idx
] >= '0' && spec
[idx
] <= '9') {
992 while(spec
[idx
+ i
] >= '0' && spec
[idx
+ i
] <= '9') {
993 rep
= 10 * rep
+ (spec
[idx
+ i
] - '0');
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");
1002 while(idx
+ i
< len
&& spec
[idx
+ i
] != '@')
1005 throw std::runtime_error("Expected '@' in axis transform");
1006 std::string aexpr
= spec
.substr(idx
+ sep
+ 1, i
- sep
- 1);
1008 throw std::runtime_error("Axis transform refers to invalid axis");
1009 adata
[adata
.size() - astride
+ rep
] = axis_transform(aexpr
);
1013 throw std::runtime_error("Repeat not allowed without frame to "
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);
1030 for(auto k
: symbols
) {
1031 std::string key
= k
.first
;
1033 for(j
= 0; idx
+ j
< len
&& j
< key
.length(); j
++)
1034 if(spec
[idx
+ j
] != key
[j
])
1036 if(j
== key
.length()) {
1037 idx
+= key
.length() - 1;
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;
1050 throw std::runtime_error("Unknown character or button");
1051 btn_token_next
= true;
1057 throw std::runtime_error("Unmatched left square bracket");
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;
1069 if(desc
.type() != JSON::array
)
1071 for(auto i
= desc
.begin(); i
!= desc
.end(); ++i
) {
1072 if(i
->type() == JSON::string
)
1074 else if(i
->type() == JSON::number
) {
1075 uint64_t anum
= i
->as_uint();
1078 else if(anum
== astride
)
1083 bool autoterminate
= false;
1085 bool in_sparen
= false;
1087 bool btn_token
= false;
1088 bool btn_token_next
= false;
1090 size_t len
= spec
.length();
1092 btn_token
= btn_token_next
;
1093 btn_token_next
= false;
1094 unsigned char ch
= spec
[idx
];
1101 } else if(ch
== ')') {
1107 } else if(ch
== '*') {
1108 autoterminate
= true;
1109 } else if(ch
== '?') {
1110 if(!btn_token
|| !in_sparen
)
1112 } else if(ch
== '[') {
1116 } else if(ch
== ']') {
1120 } else if(ch
== '.') {
1121 } else if(spec
[idx
] >= '0' && spec
[idx
] <= '9') {
1124 while(spec
[idx
+ i
] >= '0' && spec
[idx
+ i
] <= '9') {
1125 rep
= 10 * rep
+ (spec
[idx
+ i
] - '0');
1129 //This has special meaning: Axis transform.
1130 //Rep is the axis pair to operate on.
1131 if(spec
[idx
+ i
] != ':')
1134 while(idx
+ i
< len
&& spec
[idx
+ i
] != '@')
1141 std::string aexpr
= spec
.substr(idx
+ sep
+ 1, i
- sep
- 1);
1142 axis_transform
x(aexpr
);
1151 idx
= idx
+ (i
- 1);
1154 for(auto i
= desc
.begin(); i
!= desc
.end(); ++i
) {
1155 if(i
->type() != JSON::string
)
1157 std::string key
= i
->as_string8();
1159 for(j
= 0; idx
+ j
< len
&& j
< key
.length(); j
++)
1160 if(spec
[idx
+ j
] != key
[j
])
1162 if(j
== key
.length()) {
1163 idx
+= key
.length() - 1;
1169 btn_token_next
= true;
1181 void controller_macro_data::write(controller_frame
& frame
, unsigned port
, unsigned controller
, int64_t nframe
,
1186 if(autoterminate
&& (nframe
< 0 || nframe
>= (int64_t)get_frames()))
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
];
1195 st
= macro_random_bit();
1200 frame
.axis3(port
, controller
, lb
, 1);
1203 frame
.axis3(port
, controller
, lb
, frame
.axis3(port
, controller
, lb
) ^ 1);
1209 frame
.axis3(port
, controller
, lb
, 0);
1216 const port_controller
* _ctrl
= frame
.porttypes().port_type(port
).controller_info
->get(controller
);
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
);
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
++) {
1244 for(size_t j
= 0; j
< aaxes
.size(); j
++) {
1245 controller_macro_data::axis_transform
& t
= adata
[i
* aaxes
.size() + 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
== "")
1255 o
<< ctrl
.buttons
[j
].macro
;
1257 o
<< ctrl
.buttons
[j
].macro
<< "?";
1266 void controller_macro::write(controller_frame
& frame
, int64_t nframe
)
1268 for(auto& i
: macros
) {
1270 unsigned controller
;
1272 auto g
= frame
.porttypes().lcid_to_pcid(i
.first
);
1274 controller
= g
.second
;
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];
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.
1303 auto g
= std::make_pair(scale_axis(b1
, u
), scale_axis(b2
, v
));
1307 double controller_macro_data::axis_transform::unscale_axis(const port_controller_button
& b
, int16_t v
)
1310 int32_t center
= ((int32_t)b
.rmin
+ (int32_t)b
.rmax
) / 2;
1314 return -(center
- (double)v
) / (center
- b
.rmin
);
1318 return ((double)v
- center
) / (b
.rmax
- center
);
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
)
1332 int32_t center
= ((int32_t)b
.rmin
+ (int32_t)b
.rmax
) / 2;
1336 double v2
= v
* (center
- b
.rmin
) + center
;
1341 double v2
= v
* (b
.rmax
- center
) + center
;
1346 double v2
= v
* (b
.rmax
- b
.rmin
) + b
.rmin
;
1357 std::complex<double> parse_complex(const std::string
& expr
)
1360 if(r
= regex("\\((.*),(.*)\\)", expr
)) {
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);
1366 return std::complex<double>(parse_value
<double>(expr
), 0.0);
1371 controller_macro_data::axis_transform::axis_transform(const std::string
& expr
)
1374 if(r
= regex("\\*(.*)\\+(.*)", expr
)) {
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
)) {
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();
1393 } else if(r
= regex("\\+(.*)", expr
)) {
1395 std::complex<double> b
= parse_complex(r
[1]);
1400 coeffs
[4] = b
.real();
1401 coeffs
[5] = b
.imag();
1402 } else if(r
= regex("(.*),(.*),(.*),(.*),(.*),(.*)", expr
)) {
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]);
1412 std::complex<double> b
= parse_complex(expr
);
1417 coeffs
[4] = b
.real();
1418 coeffs
[5] = b
.imag();
1422 JSON::node
controller_macro::serialize()
1424 JSON::node
v(JSON::object
);
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()));
1439 void controller_macro_data::serialize(JSON::node
& v
)
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
));
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
);
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());
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");