text
stringlengths 5
1.04M
|
|---|
#ifndef _INT_GL_2_1_REM_3_1_HPP
#define _INT_GL_2_1_REM_3_1_HPP
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
#ifdef __cplusplus
}
#endif //__cplusplus
namespace gl
{
enum _int_gl_2_1_rem_3_1
{
GL_CURRENT_RASTER_SECONDARY_COLOR = 0x845F,
GL_SLUMINANCE_ALPHA = 0x8C44,
GL_SLUMINANCE8_ALPHA8 = 0x8C45,
GL_SLUMINANCE = 0x8C46,
GL_SLUMINANCE8 = 0x8C47,
GL_COMPRESSED_SLUMINANCE = 0x8C4A,
GL_COMPRESSED_SLUMINANCE_ALPHA = 0x8C4B,
};
}
#endif //_INT_GL_2_1_REM_3_1_HPP
|
int Solution::maximumGap(const vector<int> &A)
{
int n = A.size();
vector<int> lmin(n,INT_MAX);
vector<int> rmax(n,INT_MIN);
lmin[0] = A[0];
rmax[n-1] = A[n-1];
for(int i=1;i<n;i++)
lmin[i] = min(A[i],lmin[i-1]);
for(int i=n-2;i>=0;i--)
rmax[i] = max(A[i],rmax[i+1]);
int i=0,j=0,maxxdiff=-1;
while(j<n && i<n)
{
if(lmin[i]<=rmax[j])
{
maxxdiff = max(maxxdiff,j-i);
j++;
}
else
i++;
}
return maxxdiff;
}
|
/**
@copyright
<pre>
Copyright 2018 Infineon Technologies AG
This file is part of ETISS tool, see <https://github.com/tum-ei-eda/etiss>.
The initial version of this software has been created with the funding support by the German Federal
Ministry of Education and Research (BMBF) in the project EffektiV under grant 01IS13022.
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
</pre>
@author Marc Greim <marc.greim@mytum.de>, Chair of Electronic Design Automation, TUM
@date July 29, 2014
@version 0.1
*/
/**
@file
@brief implementation of etiss/IntegratedLibrary/gdb/GDBServer.h
@detail
*/
#include "etiss/IntegratedLibrary/gdb/GDBServer.h"
#include "etiss/CPUCore.h"
#include "etiss/IntegratedLibrary/gdb/Hex.h"
#include "etiss/IntegratedLibrary/gdb/UnixTCPGDBConnection.h"
#include "etiss/jit/types.h"
#include <chrono>
#include <cstring>
#include <thread>
using namespace etiss::plugin::gdb;
BreakpointDB::BreakpointDB()
{
instrbrkpt_ = 0;
}
void BreakpointDB::set(etiss::uint64 addr, etiss::uint32 val)
{
if (instrbrkpt_ == 0)
{
if (val == 0)
return;
instrbrkpt_ = new etiss::uint32 ***[1 << 16];
memset(instrbrkpt_, 0, sizeof(etiss::uint32 * **[1 << 16]));
}
unsigned a1 = (addr)&0xFFFF;
if (instrbrkpt_[a1] == 0)
{
if (val == 0)
return;
instrbrkpt_[a1] = new etiss::uint32 **[1 << 16];
memset(instrbrkpt_[a1], 0, sizeof(etiss::uint32 * *[1 << 16]));
}
unsigned a2 = (addr >> 16) & 0xFFFF;
if (instrbrkpt_[a1][a2] == 0)
{
if (val == 0)
return;
instrbrkpt_[a1][a2] = new etiss::uint32 *[1 << 16];
memset(instrbrkpt_[a1][a2], 0, sizeof(etiss::uint32 * [1 << 16]));
}
unsigned a3 = (addr >> 32) & 0xFFFF;
if (instrbrkpt_[a1][a2][a3] == 0)
{
if (val == 0)
return;
instrbrkpt_[a1][a2][a3] = new etiss::uint32[1 << 16];
memset(instrbrkpt_[a1][a2][a3], 0, sizeof(etiss::uint32[1 << 16]));
}
unsigned a4 = (addr >> 48) & 0xFFFF;
instrbrkpt_[a1][a2][a3][a4] = val;
if (val == 0)
{ // cleanup
bool empty = true;
for (unsigned i = 0; i < (1 << 16); i++)
{
if (instrbrkpt_[a1][a2][a3][i] != 0)
{
empty = false;
break;
}
}
if (!empty)
return;
delete instrbrkpt_[a1][a2][a3];
instrbrkpt_[a1][a2][a3] = 0;
for (unsigned i = 0; i < (1 << 16); i++)
{
if (instrbrkpt_[a1][a2][i] != 0)
{
empty = false;
break;
}
}
if (!empty)
return;
delete instrbrkpt_[a1][a2];
instrbrkpt_[a1][a2] = 0;
for (unsigned i = 0; i < (1 << 16); i++)
{
if (instrbrkpt_[a1][i] != 0)
{
empty = false;
break;
}
}
if (!empty)
return;
delete instrbrkpt_[a1];
instrbrkpt_[a1] = 0;
for (unsigned i = 0; i < (1 << 16); i++)
{
if (instrbrkpt_[i] != 0)
{
empty = false;
break;
}
}
if (!empty)
return;
delete instrbrkpt_;
instrbrkpt_ = 0;
}
}
Server::Server(etiss::plugin::gdb::PacketProtocol &pp) : con_(pp)
{
status_paused_ = true;
gdb_status_paused_ = true;
status_step_ = false;
status_pending_jump_ = false;
status_pending_kill_ = false;
status_jumpaddr_ = false;
arch_ = nullptr;
cpu_ = nullptr;
system_ = nullptr;
execute_skip_count = 25;
execute_skip_index = 0;
minimal_pc_alignment = 2;
}
etiss::int32 Server::preInstructionCallback()
{
// check for instruction breakpoints
if (unlikely(!breakpoints_.isEmpty()))
{
etiss::uint32 bp = breakpoints_.get(arch_->getGDBCore().getInstructionPointer(cpu_) >> minimal_pc_alignment);
if (unlikely(bp != 0))
{
if ((bp & (BreakpointDB::BPTYPE_BREAK_HW | BreakpointDB::BPTYPE_BREAK_MEM)) != 0)
{
status_paused_ = true;
}
}
}
// apply single step pause
if (unlikely(status_step_ > 0))
{
status_paused_ = true;
status_step_--;
}
if (unlikely(status_pending_kill_))
{
return RETURNCODE::CPUTERMINATED;
}
// check paused state (due to singlestep,ctrl+c)
if (unlikely(status_paused_))
{
if (!gdb_status_paused_)
{ // answer pending 'c'/'s' command
// std::cout << "GDB: answer: " << "T"<<hex::fromByte(5) << std::endl;
con_.snd("T" + hex::fromByte(5), false);
gdb_status_paused_ = true;
}
while (unlikely(status_paused_))
{
handlePacket(true);
if (unlikely(status_pending_kill_))
{
return RETURNCODE::CPUTERMINATED;
}
if (status_pending_jump_)
{
cpu_->instructionPointer = status_jumpaddr_;
status_pending_jump_ = false;
}
}
}
return RETURNCODE::NOERROR;
}
etiss::int32 Server::execute()
{
if (unlikely(status_pending_kill_))
{
return RETURNCODE::CPUTERMINATED;
}
if ((execute_skip_index++) > execute_skip_count)
{ // connections such as tcp sockets have a large overhead. to provide acceptable performance packet checks may not
// be performed too frequent
execute_skip_index = 0;
// check for BREAK event in between blocks
handlePacket(false);
}
if (unlikely(status_pending_kill_))
{
return RETURNCODE::CPUTERMINATED;
}
return 0;
}
static void Server_finalizeInstrSet(etiss::instr::InstructionSet *set, std::string pcode)
{
if (set == nullptr)
return;
set->foreach ([pcode](etiss::instr::Instruction &instr) {
instr.addCallback(
[pcode](etiss::instr::BitArray &, etiss::CodeSet &cs, etiss::instr::InstructionContext &) {
etiss::CodePart &cp = cs.prepend(etiss::CodePart::PREINITIALDEBUGRETURNING);
cp.code() = std::string("{\n"
"\tetiss_int32 _gdb_exception = gdb_pre_instruction(cpu,system,") +
pcode +
");\n"
"\tif (_gdb_exception != 0)\n\t return _gdb_exception==-16?0:_gdb_exception;\n"
"}";
return true;
},
0);
/// TODO? ensure instruction pointer update
});
}
void Server::finalizeInstrSet(etiss::instr::ModedInstructionSet &mis) const
{
std::string pcode = getPointerCode();
mis.foreach ([pcode](etiss::instr::VariableInstructionSet &vis) {
vis.foreach ([pcode](etiss::instr::InstructionSet &set) { Server_finalizeInstrSet(&set, pcode); });
});
}
void Server::finalizeCodeBlock(etiss::CodeBlock &cb) const
{
cb.fileglobalCode().insert("extern etiss_int32 gdb_pre_instruction(ETISS_CPU * ,ETISS_System * ,void * );extern "
"void gdb_pre_instruction_noreturn(ETISS_CPU * ,ETISS_System * ,void * );");
}
void Server::handlePacket(bool block)
{
if (con_.available(block))
{
bool isnotification;
std::string command = con_.rcv(isnotification);
if (command.length() > 0)
{
if (!status_paused_)
{
if (!gdb_status_paused_)
{ // answer pending 'c'/'s' command
// std::cout << "GDB: answer: " << "T"<<hex::fromByte(5) << std::endl;
con_.snd("T" + hex::fromByte(5), false);
gdb_status_paused_ = true;
}
status_paused_ = true;
}
bool nodbgaction = false;
std::string answer;
bool answerisnotification = false;
switch (command[0])
{
case 'g': // read registers
{
for (unsigned i = 0; i < arch_->getGDBCore().mappedRegisterCount(); i++)
{
std::string regname = arch_->getGDBCore().mapRegister(i);
auto f = plugin_core_->getStruct()->findName(regname);
if (!f)
{
answer = "EFF";
etiss::log(etiss::ERROR, "Faulty implementation of the GDBCore: Register not found", regname,
*plugin_core_);
break;
}
switch (f->width_)
{
case 1:
hex::fromInt(answer, (uint8_t)f->read(), arch_->getGDBCore().isLittleEndian());
break;
case 2:
hex::fromInt(answer, (uint16_t)f->read(), arch_->getGDBCore().isLittleEndian());
break;
case 4:
hex::fromInt(answer, (uint32_t)f->read(), arch_->getGDBCore().isLittleEndian());
break;
case 8:
hex::fromInt(answer, (uint64_t)f->read(), arch_->getGDBCore().isLittleEndian());
break;
default:
answer = "EFF";
etiss::log(etiss::ERROR, "GDB g: Invalid read length");
}
}
}
break;
case 'G': // write registers
{
size_t treglen = 0;
for (unsigned i = 0; i < arch_->getGDBCore().mappedRegisterCount(); i++)
{
auto f = plugin_core_->getStruct()->findName(arch_->getGDBCore().mapRegister(i));
if (!f)
{
answer = "EFF";
etiss::log(etiss::ERROR, "Faulty implementation of the GDBCore: Register not found",
arch_->getGDBCore().mapRegister(i), *plugin_core_);
break;
}
treglen += f->width_;
}
if (command.length() == (treglen * 2) + 1)
{
answer = "OK";
size_t off = 1;
for (unsigned i = 0; i < arch_->getGDBCore().mappedRegisterCount(); i++)
{
std::string regname = arch_->getGDBCore().mapRegister(i);
auto f = plugin_core_->getStruct()->findName(regname);
if (!f)
{
answer = "EFF";
etiss::log(etiss::ERROR, "Faulty implementation of the GDBCore: Register not found",
regname, *plugin_core_);
break;
}
switch (f->width_)
{
case 1:
f->write(hex::toInt<uint8_t>(command, arch_->getGDBCore().isLittleEndian(), off));
break;
case 2:
f->write(hex::toInt<uint16_t>(command, arch_->getGDBCore().isLittleEndian(), off));
break;
case 4:
f->write(hex::toInt<uint32_t>(command, arch_->getGDBCore().isLittleEndian(), off));
break;
case 8:
f->write(hex::toInt<uint64_t>(command, arch_->getGDBCore().isLittleEndian(), off));
break;
default:
answer = "EFF";
etiss::log(etiss::ERROR, "GDB G: Invalid write length");
}
off += f->width_ * 2;
}
}
else
{
answer = "E11";
}
}
break;
case 'P': // write a register
{
size_t off = 1;
unsigned regIndex = 0;
std::string valToWrite;
if (command.length() > 1)
{
for (size_t i = 1; i < command.length(); ++i)
{
if (command[i] == '=' && command.length() > i + 1)
{
valToWrite = command.substr(i + 1);
break;
}
regIndex = (regIndex << 4) | hex::fromHex(command[i]);
answer = "OK";
}
}
auto f = plugin_core_->getStruct()->findName(arch_->getGDBCore().mapRegister(regIndex));
if (!f)
{
answer = "EFF";
etiss::log(etiss::ERROR, "Faulty implementation of the GDBCore: Register not found",
arch_->getGDBCore().mapRegister(regIndex), *plugin_core_);
break;
}
switch (f->width_)
{
case 1:
f->write(hex::toInt<uint8_t>(valToWrite, arch_->getGDBCore().isLittleEndian(), off));
break;
case 2:
f->write(hex::toInt<uint16_t>(valToWrite, arch_->getGDBCore().isLittleEndian(), off));
break;
case 4:
f->write(hex::toInt<uint32_t>(valToWrite, arch_->getGDBCore().isLittleEndian(), off));
break;
case 8:
f->write(hex::toInt<uint64_t>(valToWrite, arch_->getGDBCore().isLittleEndian(), off));
break;
default:
answer = "EFF";
etiss::log(etiss::ERROR, "GDB P: Invalid write length");
}
off += f->width_ * 2;
}
break;
case 'p': // read a register
{
unsigned regIndex = 0;
if (command.length() > 1)
{
for (size_t i = 1; i < command.length(); ++i)
{
regIndex = (regIndex << 4) | hex::fromHex(command[i]);
}
}
auto f = plugin_core_->getStruct()->findName(arch_->getGDBCore().mapRegister(regIndex));
if (!f)
{
answer = "EFF";
etiss::log(etiss::ERROR, "Faulty implementation of the GDBCore: Register not found",
arch_->getGDBCore().mapRegister(regIndex), *plugin_core_);
break;
}
switch (f->width_)
{
case 1:
hex::fromInt(answer, (uint8_t)f->read(), arch_->getGDBCore().isLittleEndian());
break;
case 2:
hex::fromInt(answer, (uint16_t)f->read(), arch_->getGDBCore().isLittleEndian());
break;
case 4:
hex::fromInt(answer, (uint32_t)f->read(), arch_->getGDBCore().isLittleEndian());
break;
case 8:
hex::fromInt(answer, (uint64_t)f->read(), arch_->getGDBCore().isLittleEndian());
break;
default:
answer = "EFF";
etiss::log(etiss::ERROR, "GDB p: Invalid read length");
}
}
break;
case 'm': // read memory
{
unsigned pos = 1;
etiss::uint64 addr = hex::tryInt<etiss::uint64>(command, pos);
pos++;
etiss::uint32 length = hex::tryInt<etiss::uint32>(command, pos);
etiss::uint8 *buf = new etiss::uint8[length];
etiss::int32 exception = (*system_->dbg_read)(system_->handle, addr, buf, length);
if (exception != RETURNCODE::NOERROR)
{
answer = "EFF";
}
else
{
answer = hex::fromBytes(buf, length);
}
delete[] buf;
}
break;
case 'M': // writes memory
{
unsigned pos = 1;
etiss::uint64 addr = hex::tryInt<etiss::uint64>(command, pos);
pos++; // comma
etiss::uint32 length = hex::tryInt<etiss::uint32>(command, pos);
pos++; // colon
std::vector<etiss::uint8> buf(length);
for (etiss::uint32 i = 0; i < length; i++)
{
buf[i] = hex::tryInt<etiss::uint8>(command, pos);
}
etiss::int32 exception = (*system_->dbg_write)(system_->handle, addr, buf.data(), length);
if (exception != RETURNCODE::NOERROR)
{
answer = "EFF";
}
else
{
answer = "OK";
}
}
break;
case 'c': // continue
{
if (command.length() > 1)
{
etiss::uint64 addr = 0;
for (size_t i = 1; i < command.length(); i += 2)
{
addr = (addr << 8) | hex::toByte(command[i], command[i + 1]);
}
status_jumpaddr_ = addr;
status_pending_jump_ = true;
}
status_paused_ = false;
gdb_status_paused_ = false;
status_step_ = 0;
// std::cout << "GDB: command: " << command << std::endl;
return;
}
break;
case 's':
{
if (command.length() > 1)
{
etiss::uint64 addr = 0;
for (size_t i = 1; i < command.length(); i += 2)
{
addr = (addr << 8) | hex::toByte(command[i], command[i + 1]);
}
status_jumpaddr_ = addr;
status_pending_jump_ = true;
}
status_paused_ = false;
gdb_status_paused_ = false;
status_step_ = 1;
// std::cout << "GDB: command: " << command << std::endl;
return;
}
case '?':
{
answer = "T";
hex::fromByte(answer, 5);
}
break;
case 'v':
break;
case 'W': // custom break message; might be changed in future if W is used (apply changes also to
// Connection::BREAKMESSAGE)
{
status_paused_ = true;
return;
}
break;
case 'Z': // insert breakpoint
{
if (command.length() > 2 && command[2] == ',')
{
BreakpointDB *bpDB = nullptr;
etiss::uint32 requestedFlags = 0;
switch (command[1])
{
case '0':
bpDB = &breakpoints_;
requestedFlags = BreakpointDB::BPTYPE_BREAK_MEM;
break;
case '1':
bpDB = &breakpoints_;
requestedFlags = BreakpointDB::BPTYPE_BREAK_HW;
break;
case '2':
bpDB = &watchpoints_;
requestedFlags = BreakpointDB::BPTYPE_WATCH_WRITE;
break;
case '3':
bpDB = &watchpoints_;
requestedFlags = BreakpointDB::BPTYPE_WATCH_READ;
break;
case '4':
bpDB = &watchpoints_;
requestedFlags = BreakpointDB::BPTYPE_WATCH_READ | BreakpointDB::BPTYPE_WATCH_WRITE;
break;
}
if (bpDB)
{
unsigned pos = 3;
etiss::uint64 addr = hex::tryInt<etiss::uint64>(command, pos);
if (pos > 3)
{
if (bpDB == &breakpoints_)
{
addr = addr >> minimal_pc_alignment;
}
etiss::uint32 existingFlags = bpDB->get(addr);
if ((existingFlags & requestedFlags) != requestedFlags)
{
bpDB->set(addr, existingFlags | requestedFlags);
}
answer = "OK";
}
else
{
answer = "EFF";
}
}
}
}
break;
case 'z': // remove breakpoint
{
if (command.length() > 2 && command[2] == ',')
{
BreakpointDB *bpDB = nullptr;
etiss::uint32 flagsToDelete = 0;
switch (command[1])
{
case '0':
bpDB = &breakpoints_;
flagsToDelete = BreakpointDB::BPTYPE_BREAK_MEM;
break;
case '1':
bpDB = &breakpoints_;
flagsToDelete = BreakpointDB::BPTYPE_BREAK_HW;
break;
case '2':
bpDB = &watchpoints_;
flagsToDelete = BreakpointDB::BPTYPE_WATCH_WRITE;
break;
case '3':
bpDB = &watchpoints_;
flagsToDelete = BreakpointDB::BPTYPE_WATCH_READ;
break;
case '4':
bpDB = &watchpoints_;
flagsToDelete = BreakpointDB::BPTYPE_WATCH_READ | BreakpointDB::BPTYPE_WATCH_WRITE;
break;
}
if (bpDB)
{
unsigned pos = 3;
etiss::uint64 addr = hex::tryInt<etiss::uint64>(command, pos);
addr = addr >> minimal_pc_alignment;
if (pos > 3)
{
etiss::uint32 existingFlags = bpDB->get(addr);
if ((existingFlags & flagsToDelete) != 0)
{
bpDB->set(addr, existingFlags & ~flagsToDelete);
}
answer = "OK";
}
else
{
answer = "EFF";
}
}
}
}
break;
case 'q':
{
if (command.substr(1, 9) == "Supported")
{
answer = "";
}
else if (command.substr(1, 8) == "Attached")
{
answer = "0";
}
else if (command.substr(1, 8) == "Symbol::")
{
answer = "OK";
}
else if (command.substr(1, 1) == "C")
{
answer = "0";
}
else if (command.substr(1, 7) == "TStatus")
{
answer = "T0;tnotrun:0";
}
else if (command.substr(1, 11) == "fThreadInfo")
{
answer = "m1";
}
else if (command.substr(1, 11) == "sThreadInfo")
{
answer = "l";
}
}
break;
case 'k':
{
status_pending_kill_ = true;
return;
}
break;
case 'H':
if (command.length() > 1)
{
switch (command[1])
{
case 'c':
case 'g':
answer = "OK"; // only one thread. ignore thread selection and continue
break;
default:
std::cout << "GDB: unknown command: " << command << std::endl;
}
}
else
{
// std::cout << "GDB: unknown command: " << command << std::endl;
}
break;
default:
std::cout << "GDB: unknown command: " << command << std::endl;
break;
}
if (!nodbgaction)
{
// std::cout << "GDB: command: " << command << std::endl;
// std::cout << "GDB: answer: "<<answer << std::endl;
}
con_.snd(answer, answerisnotification);
}
}
}
void Server::preDReadCallback(etiss::uint64 addr)
{
if (!watchpoints_.isEmpty())
{
if (watchpoints_.get(addr) & BreakpointDB::BPTYPE_WATCH_READ)
{
status_paused_ = true;
}
}
}
void Server::preDWriteCallback(etiss::uint64 addr)
{
if (!watchpoints_.isEmpty())
{
if (watchpoints_.get(addr) & BreakpointDB::BPTYPE_WATCH_WRITE)
{
status_paused_ = true;
}
}
}
etiss::int32 Server::postMemAccessCallback(etiss::int32 exception)
{
if (exception)
{
status_paused_ = true;
}
if (status_paused_)
{
if (!gdb_status_paused_)
{
con_.snd("T" + hex::fromByte(5), false);
gdb_status_paused_ = true;
}
while (unlikely(status_paused_))
{
handlePacket(true);
if (unlikely(status_pending_kill_))
{
return RETURNCODE::CPUTERMINATED;
}
if (status_pending_jump_)
{
cpu_->instructionPointer = status_jumpaddr_;
status_pending_jump_ = false;
exception = RETURNCODE::NOERROR;
}
}
}
return exception;
}
std::string Server::_getPluginName() const
{
return "gdbserver";
}
void *Server::getPluginHandle()
{
return (void *)this;
}
void Server::init(ETISS_CPU *cpu, ETISS_System *system, etiss::CPUArch *arch)
{
arch_ = arch;
cpu_ = cpu;
system_ = system;
}
void Server::cleanup()
{
arch_ = nullptr;
cpu_ = nullptr;
system_ = nullptr;
}
Server *Server::createTCPServer(std::map<std::string, std::string> options)
{
int port = 2222;
{ // parse port
auto f = options.find("plugin.gdbserver.port");
if (f != options.end())
{
int tmp = atoi(f->second.c_str());
if (tmp > 0)
port = tmp;
else
etiss::log(etiss::ERROR,
std::string("etiss::plugin::gdb::Server: failed to parse port value for tcp socket: ") +
f->second);
}
}
Server *s = createTCPServer(port);
{ // parse skip count
auto f = options.find("skipcount");
if (f != options.end())
{
int tmp = atoi(f->second.c_str());
if (tmp >= 0)
s->execute_skip_count = tmp;
}
}
{ // parse Minimal pc alignment
auto f = options.find("minPcAlign");
if (f != options.end())
{
int tmp = atoi(f->second.c_str());
if (tmp >= 0)
s->minimal_pc_alignment = tmp;
}
}
return s;
}
Server *Server::createTCPServer(int port)
{
#if ETISS_USE_POSIX_SOCKET
etiss::log(etiss::VERBOSE,
std::string("etiss::plugin::gdb::Server: starting tcp server on port ") + etiss::toString(port));
std::shared_ptr<Connection> cs(new etiss::plugin::gdb::UnixTCPGDBConnection(port));
Server *s = new Server(cs.get()->getPacketProtocol());
s->cinst_ = cs;
return s;
#else
return 0;
#endif
}
extern "C"
{
etiss_int32 gdb_pre_instruction(ETISS_CPU *cpu, ETISS_System *system, void *gdbserver)
{
return ((etiss::plugin::gdb::Server *)gdbserver)->preInstructionCallback();
}
void gdb_pre_instruction_noreturn(ETISS_CPU *, ETISS_System *, void *gdbserver)
{
/// @todo fix possible exception loss
((etiss::plugin::gdb::Server *)gdbserver)->preInstructionCallback();
}
}
|
#include "gtest/gtest.h"
#include "TBTK/TBTK.h"
#include "TBTK/Test/MultiCounter.h"
int main(int argc, char **argv){
TBTK::Initialize();
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <net_processing.h>
#include <addrman.h>
#include <arith_uint256.h>
#include <blockencodings.h>
#include <chainparams.h>
#include <consensus/validation.h>
#include <hash.h>
#include <validation.h>
#include <merkleblock.h>
#include <netmessagemaker.h>
#include <netbase.h>
#include <policy/fees.h>
#include <policy/policy.h>
#include <primitives/block.h>
#include <primitives/transaction.h>
#include <random.h>
#include <reverse_iterator.h>
#include <scheduler.h>
#include <tinyformat.h>
#include <txmempool.h>
#include <ui_interface.h>
#include <util.h>
#include <utilmoneystr.h>
#include <utilstrencodings.h>
#include <memory>
#if defined(NDEBUG)
# error "Bitcoin cannot be compiled without assertions."
#endif
std::atomic<int64_t> nTimeBestReceived(0); // Used only to inform the wallet of when we last received a block
bool g_enable_bip61 = DEFAULT_ENABLE_BIP61;
struct IteratorComparator
{
template<typename I>
bool operator()(const I& a, const I& b) const
{
return &(*a) < &(*b);
}
};
struct COrphanTx {
// When modifying, adapt the copy of this definition in tests/DoS_tests.
CTransactionRef tx;
NodeId fromPeer;
int64_t nTimeExpire;
};
static CCriticalSection g_cs_orphans;
std::map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(g_cs_orphans);
std::map<COutPoint, std::set<std::map<uint256, COrphanTx>::iterator, IteratorComparator>> mapOrphanTransactionsByPrev GUARDED_BY(g_cs_orphans);
void EraseOrphansFor(NodeId peer);
static size_t vExtraTxnForCompactIt GUARDED_BY(g_cs_orphans) = 0;
static std::vector<std::pair<uint256, CTransactionRef>> vExtraTxnForCompact GUARDED_BY(g_cs_orphans);
static const uint64_t RANDOMIZER_ID_ADDRESS_RELAY = 0x3cac0035b5866b90ULL; // SHA256("main address relay")[0:8]
/// Age after which a stale block will no longer be served if requested as
/// protection against fingerprinting. Set to one month, denominated in seconds.
static const int STALE_RELAY_AGE_LIMIT = 30 * 24 * 60 * 60;
/// Age after which a block is considered historical for purposes of rate
/// limiting block relay. Set to one week, denominated in seconds.
static const int HISTORICAL_BLOCK_AGE = 7 * 24 * 60 * 60;
// Internal stuff
namespace {
/** Number of nodes with fSyncStarted. */
int nSyncStarted = 0;
/**
* Sources of received blocks, saved to be able to send them reject
* messages or ban them when processing happens afterwards. Protected by
* cs_main.
* Set mapBlockSource[hash].second to false if the node should not be
* punished if the block is invalid.
*/
std::map<uint256, std::pair<NodeId, bool>> mapBlockSource;
/**
* Filter for transactions that were recently rejected by
* AcceptToMemoryPool. These are not rerequested until the chain tip
* changes, at which point the entire filter is reset. Protected by
* cs_main.
*
* Without this filter we'd be re-requesting txs from each of our peers,
* increasing bandwidth consumption considerably. For instance, with 100
* peers, half of which relay a tx we don't accept, that might be a 50x
* bandwidth increase. A flooding attacker attempting to roll-over the
* filter using minimum-sized, 60byte, transactions might manage to send
* 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
* two minute window to send invs to us.
*
* Decreasing the false positive rate is fairly cheap, so we pick one in a
* million to make it highly unlikely for users to have issues with this
* filter.
*
* Memory used: 1.3 MB
*/
std::unique_ptr<CRollingBloomFilter> recentRejects;
uint256 hashRecentRejectsChainTip;
/** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
struct QueuedBlock {
uint256 hash;
const CBlockIndex* pindex; //!< Optional.
bool fValidatedHeaders; //!< Whether this block has validated headers at the time of request.
std::unique_ptr<PartiallyDownloadedBlock> partialBlock; //!< Optional, used for CMPCTBLOCK downloads
};
std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> > mapBlocksInFlight;
/** Stack of nodes which we have set to announce using compact blocks */
std::list<NodeId> lNodesAnnouncingHeaderAndIDs;
/** Number of preferable block download peers. */
int nPreferredDownload = 0;
/** Number of peers from which we're downloading blocks. */
int nPeersWithValidatedDownloads = 0;
/** Number of outbound peers with m_chain_sync.m_protect. */
int g_outbound_peers_with_protect_from_disconnect = 0;
/** When our tip was last updated. */
std::atomic<int64_t> g_last_tip_update(0);
/** Relay map, protected by cs_main. */
typedef std::map<uint256, CTransactionRef> MapRelay;
MapRelay mapRelay;
/** Expiration-time ordered list of (expire time, relay map entry) pairs, protected by cs_main). */
std::deque<std::pair<int64_t, MapRelay::iterator>> vRelayExpiration;
} // namespace
namespace {
struct CBlockReject {
unsigned char chRejectCode;
std::string strRejectReason;
uint256 hashBlock;
};
/**
* Maintain validation-specific state about nodes, protected by cs_main, instead
* by CNode's own locks. This simplifies asynchronous operation, where
* processing of incoming data is done after the ProcessMessage call returns,
* and we're no longer holding the node's locks.
*/
struct CNodeState {
//! The peer's address
const CService address;
//! Whether we have a fully established connection.
bool fCurrentlyConnected;
//! Accumulated misbehaviour score for this peer.
int nMisbehavior;
//! Whether this peer should be disconnected and banned (unless whitelisted).
bool fShouldBan;
//! String name of this peer (debugging/logging purposes).
const std::string name;
//! List of asynchronously-determined block rejections to notify this peer about.
std::vector<CBlockReject> rejects;
//! The best known block we know this peer has announced.
const CBlockIndex *pindexBestKnownBlock;
//! The hash of the last unknown block this peer has announced.
uint256 hashLastUnknownBlock;
//! The last full block we both have.
const CBlockIndex *pindexLastCommonBlock;
//! The best header we have sent our peer.
const CBlockIndex *pindexBestHeaderSent;
//! Length of current-streak of unconnecting headers announcements
int nUnconnectingHeaders;
//! Whether we've started headers synchronization with this peer.
bool fSyncStarted;
//! When to potentially disconnect peer for stalling headers download
int64_t nHeadersSyncTimeout;
//! Since when we're stalling block download progress (in microseconds), or 0.
int64_t nStallingSince;
std::list<QueuedBlock> vBlocksInFlight;
//! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty.
int64_t nDownloadingSince;
int nBlocksInFlight;
int nBlocksInFlightValidHeaders;
//! Whether we consider this a preferred download peer.
bool fPreferredDownload;
//! Whether this peer wants invs or headers (when possible) for block announcements.
bool fPreferHeaders;
//! Whether this peer wants invs or cmpctblocks (when possible) for block announcements.
bool fPreferHeaderAndIDs;
/**
* Whether this peer will send us cmpctblocks if we request them.
* This is not used to gate request logic, as we really only care about fSupportsDesiredCmpctVersion,
* but is used as a flag to "lock in" the version of compact blocks (fWantsCmpctWitness) we send.
*/
bool fProvidesHeaderAndIDs;
//! Whether this peer can give us witnesses
bool fHaveWitness;
//! Whether this peer wants witnesses in cmpctblocks/blocktxns
bool fWantsCmpctWitness;
/**
* If we've announced NODE_WITNESS to this peer: whether the peer sends witnesses in cmpctblocks/blocktxns,
* otherwise: whether this peer sends non-witnesses in cmpctblocks/blocktxns.
*/
bool fSupportsDesiredCmpctVersion;
/** State used to enforce CHAIN_SYNC_TIMEOUT
* Only in effect for outbound, non-manual connections, with
* m_protect == false
* Algorithm: if a peer's best known block has less work than our tip,
* set a timeout CHAIN_SYNC_TIMEOUT seconds in the future:
* - If at timeout their best known block now has more work than our tip
* when the timeout was set, then either reset the timeout or clear it
* (after comparing against our current tip's work)
* - If at timeout their best known block still has less work than our
* tip did when the timeout was set, then send a getheaders message,
* and set a shorter timeout, HEADERS_RESPONSE_TIME seconds in future.
* If their best known block is still behind when that new timeout is
* reached, disconnect.
*/
struct ChainSyncTimeoutState {
//! A timeout used for checking whether our peer has sufficiently synced
int64_t m_timeout;
//! A header with the work we require on our peer's chain
const CBlockIndex * m_work_header;
//! After timeout is reached, set to true after sending getheaders
bool m_sent_getheaders;
//! Whether this peer is protected from disconnection due to a bad/slow chain
bool m_protect;
};
ChainSyncTimeoutState m_chain_sync;
//! Time of last new block announcement
int64_t m_last_block_announcement;
CNodeState(CAddress addrIn, std::string addrNameIn) : address(addrIn), name(addrNameIn) {
fCurrentlyConnected = false;
nMisbehavior = 0;
fShouldBan = false;
pindexBestKnownBlock = nullptr;
hashLastUnknownBlock.SetNull();
pindexLastCommonBlock = nullptr;
pindexBestHeaderSent = nullptr;
nUnconnectingHeaders = 0;
fSyncStarted = false;
nHeadersSyncTimeout = 0;
nStallingSince = 0;
nDownloadingSince = 0;
nBlocksInFlight = 0;
nBlocksInFlightValidHeaders = 0;
fPreferredDownload = false;
fPreferHeaders = false;
fPreferHeaderAndIDs = false;
fProvidesHeaderAndIDs = false;
fHaveWitness = false;
fWantsCmpctWitness = false;
fSupportsDesiredCmpctVersion = false;
m_chain_sync = { 0, nullptr, false, false };
m_last_block_announcement = 0;
}
};
/** Map maintaining per-node state. Requires cs_main. */
std::map<NodeId, CNodeState> mapNodeState;
// Requires cs_main.
CNodeState *State(NodeId pnode) {
std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
if (it == mapNodeState.end())
return nullptr;
return &it->second;
}
static void UpdatePreferredDownload(CNode* node, CNodeState* state)
{
nPreferredDownload -= state->fPreferredDownload;
// Whether this node should be marked as a preferred download node.
state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
nPreferredDownload += state->fPreferredDownload;
}
static void PushNodeVersion(CNode *pnode, CConnman* connman, int64_t nTime)
{
ServiceFlags nLocalNodeServices = pnode->GetLocalServices();
uint64_t nonce = pnode->GetLocalNonce();
int nNodeStartingHeight = pnode->GetMyStartingHeight();
NodeId nodeid = pnode->GetId();
CAddress addr = pnode->addr;
CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService(), addr.nServices));
CAddress addrMe = CAddress(CService(), nLocalNodeServices);
connman->PushMessage(pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERSION, PROTOCOL_VERSION, (uint64_t)nLocalNodeServices, nTime, addrYou, addrMe,
nonce, strSubVersion, nNodeStartingHeight, ::fRelayTxes));
if (fLogIPs) {
LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, addrMe.ToString(), addrYou.ToString(), nodeid);
} else {
LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, addrMe.ToString(), nodeid);
}
}
// Requires cs_main.
// Returns a bool indicating whether we requested this block.
// Also used if a block was /not/ received and timed out or started with another peer
static bool MarkBlockAsReceived(const uint256& hash) {
std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
if (itInFlight != mapBlocksInFlight.end()) {
CNodeState *state = State(itInFlight->second.first);
assert(state != nullptr);
state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
if (state->nBlocksInFlightValidHeaders == 0 && itInFlight->second.second->fValidatedHeaders) {
// Last validated block on the queue was received.
nPeersWithValidatedDownloads--;
}
if (state->vBlocksInFlight.begin() == itInFlight->second.second) {
// First block on the queue was received, update the start download time for the next one
state->nDownloadingSince = std::max(state->nDownloadingSince, GetTimeMicros());
}
state->vBlocksInFlight.erase(itInFlight->second.second);
state->nBlocksInFlight--;
state->nStallingSince = 0;
mapBlocksInFlight.erase(itInFlight);
return true;
}
return false;
}
// Requires cs_main.
// returns false, still setting pit, if the block was already in flight from the same peer
// pit will only be valid as long as the same cs_main lock is being held
static bool MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const CBlockIndex* pindex = nullptr, std::list<QueuedBlock>::iterator** pit = nullptr) {
CNodeState *state = State(nodeid);
assert(state != nullptr);
// Short-circuit most stuff in case it is from the same node
std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
if (itInFlight != mapBlocksInFlight.end() && itInFlight->second.first == nodeid) {
if (pit) {
*pit = &itInFlight->second.second;
}
return false;
}
// Make sure it's not listed somewhere already.
MarkBlockAsReceived(hash);
std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(),
{hash, pindex, pindex != nullptr, std::unique_ptr<PartiallyDownloadedBlock>(pit ? new PartiallyDownloadedBlock(&mempool) : nullptr)});
state->nBlocksInFlight++;
state->nBlocksInFlightValidHeaders += it->fValidatedHeaders;
if (state->nBlocksInFlight == 1) {
// We're starting a block download (batch) from this peer.
state->nDownloadingSince = GetTimeMicros();
}
if (state->nBlocksInFlightValidHeaders == 1 && pindex != nullptr) {
nPeersWithValidatedDownloads++;
}
itInFlight = mapBlocksInFlight.insert(std::make_pair(hash, std::make_pair(nodeid, it))).first;
if (pit)
*pit = &itInFlight->second.second;
return true;
}
/** Check whether the last unknown block a peer advertised is not yet known. */
static void ProcessBlockAvailability(NodeId nodeid) {
CNodeState *state = State(nodeid);
assert(state != nullptr);
if (!state->hashLastUnknownBlock.IsNull()) {
const CBlockIndex* pindex = LookupBlockIndex(state->hashLastUnknownBlock);
if (pindex && pindex->nChainWork > 0) {
if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
state->pindexBestKnownBlock = pindex;
}
state->hashLastUnknownBlock.SetNull();
}
}
}
/** Update tracking information about which blocks a peer is assumed to have. */
static void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
CNodeState *state = State(nodeid);
assert(state != nullptr);
ProcessBlockAvailability(nodeid);
const CBlockIndex* pindex = LookupBlockIndex(hash);
if (pindex && pindex->nChainWork > 0) {
// An actually better block was announced.
if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
state->pindexBestKnownBlock = pindex;
}
} else {
// An unknown block was announced; just assume that the latest one is the best one.
state->hashLastUnknownBlock = hash;
}
}
/**
* When a peer sends us a valid block, instruct it to announce blocks to us
* using CMPCTBLOCK if possible by adding its nodeid to the end of
* lNodesAnnouncingHeaderAndIDs, and keeping that list under a certain size by
* removing the first element if necessary.
*/
static void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid, CConnman* connman) {
AssertLockHeld(cs_main);
CNodeState* nodestate = State(nodeid);
if (!nodestate || !nodestate->fSupportsDesiredCmpctVersion) {
// Never ask from peers who can't provide witnesses.
return;
}
if (nodestate->fProvidesHeaderAndIDs) {
for (std::list<NodeId>::iterator it = lNodesAnnouncingHeaderAndIDs.begin(); it != lNodesAnnouncingHeaderAndIDs.end(); it++) {
if (*it == nodeid) {
lNodesAnnouncingHeaderAndIDs.erase(it);
lNodesAnnouncingHeaderAndIDs.push_back(nodeid);
return;
}
}
connman->ForNode(nodeid, [connman](CNode* pfrom){
uint64_t nCMPCTBLOCKVersion = (pfrom->GetLocalServices() & NODE_WITNESS) ? 2 : 1;
if (lNodesAnnouncingHeaderAndIDs.size() >= 3) {
// As per BIP152, we only get 3 of our peers to announce
// blocks using compact encodings.
connman->ForNode(lNodesAnnouncingHeaderAndIDs.front(), [connman, nCMPCTBLOCKVersion](CNode* pnodeStop){
connman->PushMessage(pnodeStop, CNetMsgMaker(pnodeStop->GetSendVersion()).Make(NetMsgType::SENDCMPCT, /*fAnnounceUsingCMPCTBLOCK=*/false, nCMPCTBLOCKVersion));
return true;
});
lNodesAnnouncingHeaderAndIDs.pop_front();
}
connman->PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::SENDCMPCT, /*fAnnounceUsingCMPCTBLOCK=*/true, nCMPCTBLOCKVersion));
lNodesAnnouncingHeaderAndIDs.push_back(pfrom->GetId());
return true;
});
}
}
static bool TipMayBeStale(const Consensus::Params &consensusParams)
{
AssertLockHeld(cs_main);
if (g_last_tip_update == 0) {
g_last_tip_update = GetTime();
}
return g_last_tip_update < GetTime() - consensusParams.nPowTargetSpacing * 3 && mapBlocksInFlight.empty();
}
// Requires cs_main
static bool CanDirectFetch(const Consensus::Params &consensusParams)
{
return chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams.nPowTargetSpacing * 20;
}
// Requires cs_main
static bool PeerHasHeader(CNodeState *state, const CBlockIndex *pindex)
{
if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight))
return true;
if (state->pindexBestHeaderSent && pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight))
return true;
return false;
}
/** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
* at most count entries. */
static void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller, const Consensus::Params& consensusParams) {
if (count == 0)
return;
vBlocks.reserve(vBlocks.size() + count);
CNodeState *state = State(nodeid);
assert(state != nullptr);
// Make sure pindexBestKnownBlock is up to date, we'll need it.
ProcessBlockAvailability(nodeid);
if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork || state->pindexBestKnownBlock->nChainWork < nMinimumChainWork) {
// This peer has nothing interesting.
return;
}
if (state->pindexLastCommonBlock == nullptr) {
// Bootstrap quickly by guessing a parent of our best tip is the forking point.
// Guessing wrong in either direction is not a problem.
state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
}
// If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
// of its current tip anymore. Go back enough to fix that.
state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
return;
std::vector<const CBlockIndex*> vToFetch;
const CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
// Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
// linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
// download that next block if the window were 1 larger.
int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
NodeId waitingfor = -1;
while (pindexWalk->nHeight < nMaxHeight) {
// Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
// pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
// as iterating over ~100 CBlockIndex* entries anyway.
int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
vToFetch.resize(nToFetch);
pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
vToFetch[nToFetch - 1] = pindexWalk;
for (unsigned int i = nToFetch - 1; i > 0; i--) {
vToFetch[i - 1] = vToFetch[i]->pprev;
}
// Iterate over those blocks in vToFetch (in forward direction), adding the ones that
// are not yet downloaded and not in flight to vBlocks. In the meantime, update
// pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
// already part of our chain (and therefore don't need it even if pruned).
for (const CBlockIndex* pindex : vToFetch) {
if (!pindex->IsValid(BLOCK_VALID_TREE)) {
// We consider the chain that this peer is on invalid.
return;
}
if (!State(nodeid)->fHaveWitness && IsWitnessEnabled(pindex->pprev, consensusParams)) {
// We wouldn't download this block or its descendants from this peer.
return;
}
if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
if (pindex->nChainTx)
state->pindexLastCommonBlock = pindex;
} else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
// The block is not already downloaded, and not yet in flight.
if (pindex->nHeight > nWindowEnd) {
// We reached the end of the window.
if (vBlocks.size() == 0 && waitingfor != nodeid) {
// We aren't able to fetch anything, but we would be if the download window was one larger.
nodeStaller = waitingfor;
}
return;
}
vBlocks.push_back(pindex);
if (vBlocks.size() == count) {
return;
}
} else if (waitingfor == -1) {
// This is the first already-in-flight block.
waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
}
}
}
}
} // namespace
// This function is used for testing the stale tip eviction logic, see
// denialofservice_tests.cpp
void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds)
{
LOCK(cs_main);
CNodeState *state = State(node);
if (state) state->m_last_block_announcement = time_in_seconds;
}
// Returns true for outbound peers, excluding manual connections, feelers, and
// one-shots
static bool IsOutboundDisconnectionCandidate(const CNode *node)
{
return !(node->fInbound || node->m_manual_connection || node->fFeeler || node->fOneShot);
}
void PeerLogicValidation::InitializeNode(CNode *pnode) {
CAddress addr = pnode->addr;
std::string addrName = pnode->GetAddrName();
NodeId nodeid = pnode->GetId();
{
LOCK(cs_main);
mapNodeState.emplace_hint(mapNodeState.end(), std::piecewise_construct, std::forward_as_tuple(nodeid), std::forward_as_tuple(addr, std::move(addrName)));
}
if(!pnode->fInbound)
PushNodeVersion(pnode, connman, GetTime());
}
void PeerLogicValidation::FinalizeNode(NodeId nodeid, bool& fUpdateConnectionTime) {
fUpdateConnectionTime = false;
LOCK(cs_main);
CNodeState *state = State(nodeid);
assert(state != nullptr);
if (state->fSyncStarted)
nSyncStarted--;
if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
fUpdateConnectionTime = true;
}
for (const QueuedBlock& entry : state->vBlocksInFlight) {
mapBlocksInFlight.erase(entry.hash);
}
EraseOrphansFor(nodeid);
nPreferredDownload -= state->fPreferredDownload;
nPeersWithValidatedDownloads -= (state->nBlocksInFlightValidHeaders != 0);
assert(nPeersWithValidatedDownloads >= 0);
g_outbound_peers_with_protect_from_disconnect -= state->m_chain_sync.m_protect;
assert(g_outbound_peers_with_protect_from_disconnect >= 0);
mapNodeState.erase(nodeid);
if (mapNodeState.empty()) {
// Do a consistency check after the last peer is removed.
assert(mapBlocksInFlight.empty());
assert(nPreferredDownload == 0);
assert(nPeersWithValidatedDownloads == 0);
assert(g_outbound_peers_with_protect_from_disconnect == 0);
}
LogPrint(BCLog::NET, "Cleared nodestate for peer=%d\n", nodeid);
}
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
LOCK(cs_main);
CNodeState *state = State(nodeid);
if (state == nullptr)
return false;
stats.nMisbehavior = state->nMisbehavior;
stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
for (const QueuedBlock& queue : state->vBlocksInFlight) {
if (queue.pindex)
stats.vHeightInFlight.push_back(queue.pindex->nHeight);
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
//
// mapOrphanTransactions
//
static void AddToCompactExtraTransactions(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(g_cs_orphans)
{
size_t max_extra_txn = gArgs.GetArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN);
if (max_extra_txn <= 0)
return;
if (!vExtraTxnForCompact.size())
vExtraTxnForCompact.resize(max_extra_txn);
vExtraTxnForCompact[vExtraTxnForCompactIt] = std::make_pair(tx->GetWitnessHash(), tx);
vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % max_extra_txn;
}
bool AddOrphanTx(const CTransactionRef& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(g_cs_orphans)
{
const uint256& hash = tx->GetHash();
if (mapOrphanTransactions.count(hash))
return false;
// Ignore big transactions, to avoid a
// send-big-orphans memory exhaustion attack. If a peer has a legitimate
// large transaction with a missing parent then we assume
// it will rebroadcast it later, after the parent transaction(s)
// have been mined or received.
// 100 orphans, each of which is at most 100,000 bytes big is
// at most 10 megabytes of orphans and somewhat more byprev index (in the worst case):
unsigned int sz = GetTransactionWeight(*tx);
if (sz > MAX_STANDARD_TX_WEIGHT)
{
LogPrint(BCLog::MEMPOOL, "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
return false;
}
auto ret = mapOrphanTransactions.emplace(hash, COrphanTx{tx, peer, GetTime() + ORPHAN_TX_EXPIRE_TIME});
assert(ret.second);
for (const CTxIn& txin : tx->vin) {
mapOrphanTransactionsByPrev[txin.prevout].insert(ret.first);
}
AddToCompactExtraTransactions(tx);
LogPrint(BCLog::MEMPOOL, "stored orphan tx %s (mapsz %u outsz %u)\n", hash.ToString(),
mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
return true;
}
int static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(g_cs_orphans)
{
std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
if (it == mapOrphanTransactions.end())
return 0;
for (const CTxIn& txin : it->second.tx->vin)
{
auto itPrev = mapOrphanTransactionsByPrev.find(txin.prevout);
if (itPrev == mapOrphanTransactionsByPrev.end())
continue;
itPrev->second.erase(it);
if (itPrev->second.empty())
mapOrphanTransactionsByPrev.erase(itPrev);
}
mapOrphanTransactions.erase(it);
return 1;
}
void EraseOrphansFor(NodeId peer)
{
LOCK(g_cs_orphans);
int nErased = 0;
std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
while (iter != mapOrphanTransactions.end())
{
std::map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
if (maybeErase->second.fromPeer == peer)
{
nErased += EraseOrphanTx(maybeErase->second.tx->GetHash());
}
}
if (nErased > 0) LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx from peer=%d\n", nErased, peer);
}
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
{
LOCK(g_cs_orphans);
unsigned int nEvicted = 0;
static int64_t nNextSweep;
int64_t nNow = GetTime();
if (nNextSweep <= nNow) {
// Sweep out expired orphan pool entries:
int nErased = 0;
int64_t nMinExpTime = nNow + ORPHAN_TX_EXPIRE_TIME - ORPHAN_TX_EXPIRE_INTERVAL;
std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
while (iter != mapOrphanTransactions.end())
{
std::map<uint256, COrphanTx>::iterator maybeErase = iter++;
if (maybeErase->second.nTimeExpire <= nNow) {
nErased += EraseOrphanTx(maybeErase->second.tx->GetHash());
} else {
nMinExpTime = std::min(maybeErase->second.nTimeExpire, nMinExpTime);
}
}
// Sweep again 5 minutes after the next entry that expires in order to batch the linear scan.
nNextSweep = nMinExpTime + ORPHAN_TX_EXPIRE_INTERVAL;
if (nErased > 0) LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx due to expiration\n", nErased);
}
while (mapOrphanTransactions.size() > nMaxOrphans)
{
// Evict a random orphan:
uint256 randomhash = GetRandHash();
std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin();
EraseOrphanTx(it->first);
++nEvicted;
}
return nEvicted;
}
/**
* Mark a misbehaving peer to be banned depending upon the value of `-banscore`.
*
* Requires cs_main.
*/
void Misbehaving(NodeId pnode, int howmuch, const std::string& message)
{
if (howmuch == 0)
return;
CNodeState *state = State(pnode);
if (state == nullptr)
return;
state->nMisbehavior += howmuch;
int banscore = gArgs.GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD);
std::string message_prefixed = message.empty() ? "" : (": " + message);
if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
{
LogPrint(BCLog::NET, "%s: %s peer=%d (%d -> %d) BAN THRESHOLD EXCEEDED%s\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior, message_prefixed);
state->fShouldBan = true;
} else
LogPrint(BCLog::NET, "%s: %s peer=%d (%d -> %d)%s\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior, message_prefixed);
}
//////////////////////////////////////////////////////////////////////////////
//
// blockchain -> download logic notification
//
// To prevent fingerprinting attacks, only send blocks/headers outside of the
// active chain if they are no more than a month older (both in time, and in
// best equivalent proof of work) than the best header chain we know about and
// we fully-validated them at some point.
static bool BlockRequestAllowed(const CBlockIndex* pindex, const Consensus::Params& consensusParams)
{
AssertLockHeld(cs_main);
if (chainActive.Contains(pindex)) return true;
return pindex->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != nullptr) &&
(pindexBestHeader->GetBlockTime() - pindex->GetBlockTime() < STALE_RELAY_AGE_LIMIT) &&
(GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, consensusParams) < STALE_RELAY_AGE_LIMIT);
}
PeerLogicValidation::PeerLogicValidation(CConnman* connmanIn, CScheduler &scheduler) : connman(connmanIn), m_stale_tip_check_time(0) {
// Initialize global variables that cannot be constructed at startup.
recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
const Consensus::Params& consensusParams = Params().GetConsensus();
// Stale tip checking and peer eviction are on two different timers, but we
// don't want them to get out of sync due to drift in the scheduler, so we
// combine them in one function and schedule at the quicker (peer-eviction)
// timer.
static_assert(EXTRA_PEER_CHECK_INTERVAL < STALE_CHECK_INTERVAL, "peer eviction timer should be less than stale tip check timer");
scheduler.scheduleEvery(std::bind(&PeerLogicValidation::CheckForStaleTipAndEvictPeers, this, consensusParams), EXTRA_PEER_CHECK_INTERVAL * 1000);
}
/**
* Evict orphan txn pool entries (EraseOrphanTx) based on a newly connected
* block. Also save the time of the last tip update.
*/
void PeerLogicValidation::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindex, const std::vector<CTransactionRef>& vtxConflicted) {
LOCK(g_cs_orphans);
std::vector<uint256> vOrphanErase;
for (const CTransactionRef& ptx : pblock->vtx) {
const CTransaction& tx = *ptx;
// Which orphan pool entries must we evict?
for (const auto& txin : tx.vin) {
auto itByPrev = mapOrphanTransactionsByPrev.find(txin.prevout);
if (itByPrev == mapOrphanTransactionsByPrev.end()) continue;
for (auto mi = itByPrev->second.begin(); mi != itByPrev->second.end(); ++mi) {
const CTransaction& orphanTx = *(*mi)->second.tx;
const uint256& orphanHash = orphanTx.GetHash();
vOrphanErase.push_back(orphanHash);
}
}
}
// Erase orphan transactions included or precluded by this block
if (vOrphanErase.size()) {
int nErased = 0;
for (uint256 &orphanHash : vOrphanErase) {
nErased += EraseOrphanTx(orphanHash);
}
LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx included or conflicted by block\n", nErased);
}
g_last_tip_update = GetTime();
}
// All of the following cache a recent block, and are protected by cs_most_recent_block
static CCriticalSection cs_most_recent_block;
static std::shared_ptr<const CBlock> most_recent_block;
static std::shared_ptr<const CBlockHeaderAndShortTxIDs> most_recent_compact_block;
static uint256 most_recent_block_hash;
static bool fWitnessesPresentInMostRecentCompactBlock;
/**
* Maintain state about the best-seen block and fast-announce a compact block
* to compatible peers.
*/
void PeerLogicValidation::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock) {
std::shared_ptr<const CBlockHeaderAndShortTxIDs> pcmpctblock = std::make_shared<const CBlockHeaderAndShortTxIDs> (*pblock, true);
const CNetMsgMaker msgMaker(PROTOCOL_VERSION);
LOCK(cs_main);
static int nHighestFastAnnounce = 0;
if (pindex->nHeight <= nHighestFastAnnounce)
return;
nHighestFastAnnounce = pindex->nHeight;
bool fWitnessEnabled = IsWitnessEnabled(pindex->pprev, Params().GetConsensus());
uint256 hashBlock(pblock->GetHash());
{
LOCK(cs_most_recent_block);
most_recent_block_hash = hashBlock;
most_recent_block = pblock;
most_recent_compact_block = pcmpctblock;
fWitnessesPresentInMostRecentCompactBlock = fWitnessEnabled;
}
connman->ForEachNode([this, &pcmpctblock, pindex, &msgMaker, fWitnessEnabled, &hashBlock](CNode* pnode) {
// TODO: Avoid the repeated-serialization here
if (pnode->nVersion < INVALID_CB_NO_BAN_VERSION || pnode->fDisconnect)
return;
ProcessBlockAvailability(pnode->GetId());
CNodeState &state = *State(pnode->GetId());
// If the peer has, or we announced to them the previous block already,
// but we don't think they have this one, go ahead and announce it
if (state.fPreferHeaderAndIDs && (!fWitnessEnabled || state.fWantsCmpctWitness) &&
!PeerHasHeader(&state, pindex) && PeerHasHeader(&state, pindex->pprev)) {
LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", "PeerLogicValidation::NewPoWValidBlock",
hashBlock.ToString(), pnode->GetId());
connman->PushMessage(pnode, msgMaker.Make(NetMsgType::CMPCTBLOCK, *pcmpctblock));
state.pindexBestHeaderSent = pindex;
}
});
}
/**
* Update our best height and announce any block hashes which weren't previously
* in chainActive to our peers.
*/
void PeerLogicValidation::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) {
const int nNewHeight = pindexNew->nHeight;
connman->SetBestHeight(nNewHeight);
SetServiceFlagsIBDCache(!fInitialDownload);
if (!fInitialDownload) {
// Find the hashes of all blocks that weren't previously in the best chain.
std::vector<uint256> vHashes;
const CBlockIndex *pindexToAnnounce = pindexNew;
while (pindexToAnnounce != pindexFork) {
vHashes.push_back(pindexToAnnounce->GetBlockHash());
pindexToAnnounce = pindexToAnnounce->pprev;
if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) {
// Limit announcements in case of a huge reorganization.
// Rely on the peer's synchronization mechanism in that case.
break;
}
}
// Relay inventory, but don't relay old inventory during initial block download.
connman->ForEachNode([nNewHeight, &vHashes](CNode* pnode) {
if (nNewHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 0)) {
for (const uint256& hash : reverse_iterate(vHashes)) {
pnode->PushBlockHash(hash);
}
}
});
connman->WakeMessageHandler();
}
nTimeBestReceived = GetTime();
}
/**
* Handle invalid block rejection and consequent peer banning, maintain which
* peers announce compact blocks.
*/
void PeerLogicValidation::BlockChecked(const CBlock& block, const CValidationState& state) {
LOCK(cs_main);
const uint256 hash(block.GetHash());
std::map<uint256, std::pair<NodeId, bool>>::iterator it = mapBlockSource.find(hash);
int nDoS = 0;
if (state.IsInvalid(nDoS)) {
// Don't send reject message with code 0 or an internal reject code.
if (it != mapBlockSource.end() && State(it->second.first) && state.GetRejectCode() > 0 && state.GetRejectCode() < REJECT_INTERNAL) {
CBlockReject reject = {(unsigned char)state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), hash};
State(it->second.first)->rejects.push_back(reject);
if (nDoS > 0 && it->second.second)
Misbehaving(it->second.first, nDoS);
}
}
// Check that:
// 1. The block is valid
// 2. We're not in initial block download
// 3. This is currently the best block we're aware of. We haven't updated
// the tip yet so we have no way to check this directly here. Instead we
// just check that there are currently no other blocks in flight.
else if (state.IsValid() &&
!IsInitialBlockDownload() &&
mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) {
if (it != mapBlockSource.end()) {
MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first, connman);
}
}
if (it != mapBlockSource.end())
mapBlockSource.erase(it);
}
//////////////////////////////////////////////////////////////////////////////
//
// Messages
//
bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
{
switch (inv.type)
{
case MSG_TX:
case MSG_WITNESS_TX:
{
assert(recentRejects);
if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
{
// If the chain tip has changed previously rejected transactions
// might be now valid, e.g. due to a nLockTime'd tx becoming valid,
// or a double-spend. Reset the rejects filter and give those
// txs a second chance.
hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
recentRejects->reset();
}
{
LOCK(g_cs_orphans);
if (mapOrphanTransactions.count(inv.hash)) return true;
}
return recentRejects->contains(inv.hash) ||
mempool.exists(inv.hash) ||
pcoinsTip->HaveCoinInCache(COutPoint(inv.hash, 0)) || // Best effort: only try output 0 and 1
pcoinsTip->HaveCoinInCache(COutPoint(inv.hash, 1));
}
case MSG_BLOCK:
case MSG_WITNESS_BLOCK:
return LookupBlockIndex(inv.hash) != nullptr;
}
// Don't know what it is, just say we already got one
return true;
}
static void RelayTransaction(const CTransaction& tx, CConnman* connman)
{
CInv inv(MSG_TX, tx.GetHash());
connman->ForEachNode([&inv](CNode* pnode)
{
pnode->PushInventory(inv);
});
}
static void RelayAddress(const CAddress& addr, bool fReachable, CConnman* connman)
{
unsigned int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
// Relay to a limited number of other nodes
// Use deterministic randomness to send to the same nodes for 24 hours
// at a time so the addrKnowns of the chosen nodes prevent repeats
uint64_t hashAddr = addr.GetHash();
const CSipHasher hasher = connman->GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY).Write(hashAddr << 32).Write((GetTime() + hashAddr) / (24*60*60));
FastRandomContext insecure_rand;
std::array<std::pair<uint64_t, CNode*>,2> best{{{0, nullptr}, {0, nullptr}}};
assert(nRelayNodes <= best.size());
auto sortfunc = [&best, &hasher, nRelayNodes](CNode* pnode) {
if (pnode->nVersion >= CADDR_TIME_VERSION) {
uint64_t hashKey = CSipHasher(hasher).Write(pnode->GetId()).Finalize();
for (unsigned int i = 0; i < nRelayNodes; i++) {
if (hashKey > best[i].first) {
std::copy(best.begin() + i, best.begin() + nRelayNodes - 1, best.begin() + i + 1);
best[i] = std::make_pair(hashKey, pnode);
break;
}
}
}
};
auto pushfunc = [&addr, &best, nRelayNodes, &insecure_rand] {
for (unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) {
best[i].second->PushAddress(addr, insecure_rand);
}
};
connman->ForEachNodeThen(std::move(sortfunc), std::move(pushfunc));
}
void static ProcessGetBlockData(CNode* pfrom, const CChainParams& chainparams, const CInv& inv, CConnman* connman, const std::atomic<bool>& interruptMsgProc)
{
bool send = false;
std::shared_ptr<const CBlock> a_recent_block;
std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block;
bool fWitnessesPresentInARecentCompactBlock;
const Consensus::Params& consensusParams = chainparams.GetConsensus();
{
LOCK(cs_most_recent_block);
a_recent_block = most_recent_block;
a_recent_compact_block = most_recent_compact_block;
fWitnessesPresentInARecentCompactBlock = fWitnessesPresentInMostRecentCompactBlock;
}
bool need_activate_chain = false;
{
LOCK(cs_main);
const CBlockIndex* pindex = LookupBlockIndex(inv.hash);
if (pindex) {
if (pindex->nChainTx && !pindex->IsValid(BLOCK_VALID_SCRIPTS) &&
pindex->IsValid(BLOCK_VALID_TREE)) {
// If we have the block and all of its parents, but have not yet validated it,
// we might be in the middle of connecting it (ie in the unlock of cs_main
// before ActivateBestChain but after AcceptBlock).
// In this case, we need to run ActivateBestChain prior to checking the relay
// conditions below.
need_activate_chain = true;
}
}
} // release cs_main before calling ActivateBestChain
if (need_activate_chain) {
CValidationState state;
if (!ActivateBestChain(state, Params(), a_recent_block)) {
LogPrint(BCLog::NET, "failed to activate chain (%s)\n", FormatStateMessage(state));
}
}
LOCK(cs_main);
const CBlockIndex* pindex = LookupBlockIndex(inv.hash);
if (pindex) {
send = BlockRequestAllowed(pindex, consensusParams);
if (!send) {
LogPrint(BCLog::NET, "%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
}
}
const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
// disconnect node in case we have reached the outbound limit for serving historical blocks
// never disconnect whitelisted nodes
if (send && connman->OutboundTargetReached(true) && ( ((pindexBestHeader != nullptr) && (pindexBestHeader->GetBlockTime() - pindex->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted)
{
LogPrint(BCLog::NET, "historical block serving limit reached, disconnect peer=%d\n", pfrom->GetId());
//disconnect node
pfrom->fDisconnect = true;
send = false;
}
// Avoid leaking prune-height by never sending blocks below the NODE_NETWORK_LIMITED threshold
if (send && !pfrom->fWhitelisted && (
(((pfrom->GetLocalServices() & NODE_NETWORK_LIMITED) == NODE_NETWORK_LIMITED) && ((pfrom->GetLocalServices() & NODE_NETWORK) != NODE_NETWORK) && (chainActive.Tip()->nHeight - pindex->nHeight > (int)NODE_NETWORK_LIMITED_MIN_BLOCKS + 2 /* add two blocks buffer extension for possible races */) )
)) {
LogPrint(BCLog::NET, "Ignore block request below NODE_NETWORK_LIMITED threshold from peer=%d\n", pfrom->GetId());
//disconnect node and prevent it from stalling (would otherwise wait for the missing block)
pfrom->fDisconnect = true;
send = false;
}
// Pruned nodes may have deleted the block, so check whether
// it's available before trying to send.
if (send && (pindex->nStatus & BLOCK_HAVE_DATA))
{
std::shared_ptr<const CBlock> pblock;
if (a_recent_block && a_recent_block->GetHash() == pindex->GetBlockHash()) {
pblock = a_recent_block;
} else if (inv.type == MSG_WITNESS_BLOCK) {
// Fast-path: in this case it is possible to serve the block directly from disk,
// as the network format matches the format on disk
std::vector<uint8_t> block_data;
if (!ReadRawBlockFromDisk(block_data, pindex, chainparams.MessageStart())) {
assert(!"cannot load block from disk");
}
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::BLOCK, MakeSpan(block_data)));
// Don't set pblock as we've sent the block
} else {
// Send block from disk
std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();
if (!ReadBlockFromDisk(*pblockRead, pindex, consensusParams))
assert(!"cannot load block from disk");
pblock = pblockRead;
}
if (pblock) {
if (inv.type == MSG_BLOCK)
connman->PushMessage(pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::BLOCK, *pblock));
else if (inv.type == MSG_WITNESS_BLOCK)
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::BLOCK, *pblock));
else if (inv.type == MSG_FILTERED_BLOCK)
{
bool sendMerkleBlock = false;
CMerkleBlock merkleBlock;
{
LOCK(pfrom->cs_filter);
if (pfrom->pfilter) {
sendMerkleBlock = true;
merkleBlock = CMerkleBlock(*pblock, *pfrom->pfilter);
}
}
if (sendMerkleBlock) {
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::MERKLEBLOCK, merkleBlock));
// CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
// This avoids hurting performance by pointlessly requiring a round-trip
// Note that there is currently no way for a node to request any single transactions we didn't send here -
// they must either disconnect and retry or request the full block.
// Thus, the protocol spec specified allows for us to provide duplicate txn here,
// however we MUST always provide at least what the remote peer needs
typedef std::pair<unsigned int, uint256> PairType;
for (PairType& pair : merkleBlock.vMatchedTxn)
connman->PushMessage(pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::TX, *pblock->vtx[pair.first]));
}
// else
// no response
}
else if (inv.type == MSG_CMPCT_BLOCK)
{
// If a peer is asking for old blocks, we're almost guaranteed
// they won't have a useful mempool to match against a compact block,
// and we don't feel like constructing the object for them, so
// instead we respond with the full, non-compact block.
bool fPeerWantsWitness = State(pfrom->GetId())->fWantsCmpctWitness;
int nSendFlags = fPeerWantsWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
if (CanDirectFetch(consensusParams) && pindex->nHeight >= chainActive.Height() - MAX_CMPCTBLOCK_DEPTH) {
if ((fPeerWantsWitness || !fWitnessesPresentInARecentCompactBlock) && a_recent_compact_block && a_recent_compact_block->header.GetHash() == pindex->GetBlockHash()) {
connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *a_recent_compact_block));
} else {
CBlockHeaderAndShortTxIDs cmpctblock(*pblock, fPeerWantsWitness);
connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
}
} else {
connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCK, *pblock));
}
}
}
// Trigger the peer node to send a getblocks request for the next batch of inventory
if (inv.hash == pfrom->hashContinue)
{
// Bypass PushInventory, this must send even if redundant,
// and we want it right after the last block so they don't
// wait for other stuff first.
std::vector<CInv> vInv;
vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::INV, vInv));
pfrom->hashContinue.SetNull();
}
}
}
void static ProcessGetData(CNode* pfrom, const CChainParams& chainparams, CConnman* connman, const std::atomic<bool>& interruptMsgProc)
{
AssertLockNotHeld(cs_main);
std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
std::vector<CInv> vNotFound;
const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
{
LOCK(cs_main);
while (it != pfrom->vRecvGetData.end() && (it->type == MSG_TX || it->type == MSG_WITNESS_TX)) {
if (interruptMsgProc)
return;
// Don't bother if send buffer is too full to respond anyway
if (pfrom->fPauseSend)
break;
const CInv &inv = *it;
it++;
// Send stream from relay memory
bool push = false;
auto mi = mapRelay.find(inv.hash);
int nSendFlags = (inv.type == MSG_TX ? SERIALIZE_TRANSACTION_NO_WITNESS : 0);
if (mi != mapRelay.end()) {
connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *mi->second));
push = true;
} else if (pfrom->timeLastMempoolReq) {
auto txinfo = mempool.info(inv.hash);
// To protect privacy, do not answer getdata using the mempool when
// that TX couldn't have been INVed in reply to a MEMPOOL request.
if (txinfo.tx && txinfo.nTime <= pfrom->timeLastMempoolReq) {
connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *txinfo.tx));
push = true;
}
}
if (!push) {
vNotFound.push_back(inv);
}
// Track requests for our stuff.
GetMainSignals().Inventory(inv.hash);
}
} // release cs_main
if (it != pfrom->vRecvGetData.end() && !pfrom->fPauseSend) {
const CInv &inv = *it;
if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK || inv.type == MSG_CMPCT_BLOCK || inv.type == MSG_WITNESS_BLOCK) {
it++;
ProcessGetBlockData(pfrom, chainparams, inv, connman, interruptMsgProc);
}
}
pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
if (!vNotFound.empty()) {
// Let the peer know that we didn't find what it asked for, so it doesn't
// have to wait around forever. Currently only SPV clients actually care
// about this message: it's needed when they are recursively walking the
// dependencies of relevant unconfirmed transactions. SPV clients want to
// do that because they want to know about (and store and rebroadcast and
// risk analyze) the dependencies of transactions relevant to them, without
// having to download the entire memory pool.
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::NOTFOUND, vNotFound));
}
}
static uint32_t GetFetchFlags(CNode* pfrom) {
uint32_t nFetchFlags = 0;
if ((pfrom->GetLocalServices() & NODE_WITNESS) && State(pfrom->GetId())->fHaveWitness) {
nFetchFlags |= MSG_WITNESS_FLAG;
}
return nFetchFlags;
}
inline void static SendBlockTransactions(const CBlock& block, const BlockTransactionsRequest& req, CNode* pfrom, CConnman* connman) {
BlockTransactions resp(req);
for (size_t i = 0; i < req.indexes.size(); i++) {
if (req.indexes[i] >= block.vtx.size()) {
LOCK(cs_main);
Misbehaving(pfrom->GetId(), 100, strprintf("Peer %d sent us a getblocktxn with out-of-bounds tx indices", pfrom->GetId()));
return;
}
resp.txn[i] = block.vtx[req.indexes[i]];
}
LOCK(cs_main);
const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
int nSendFlags = State(pfrom->GetId())->fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCKTXN, resp));
}
bool static ProcessHeadersMessage(CNode *pfrom, CConnman *connman, const std::vector<CBlockHeader>& headers, const CChainParams& chainparams, bool punish_duplicate_invalid)
{
const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
size_t nCount = headers.size();
if (nCount == 0) {
// Nothing interesting. Stop asking this peers for more headers.
return true;
}
bool received_new_header = false;
const CBlockIndex *pindexLast = nullptr;
{
LOCK(cs_main);
CNodeState *nodestate = State(pfrom->GetId());
// If this looks like it could be a block announcement (nCount <
// MAX_BLOCKS_TO_ANNOUNCE), use special logic for handling headers that
// don't connect:
// - Send a getheaders message in response to try to connect the chain.
// - The peer can send up to MAX_UNCONNECTING_HEADERS in a row that
// don't connect before giving DoS points
// - Once a headers message is received that is valid and does connect,
// nUnconnectingHeaders gets reset back to 0.
if (!LookupBlockIndex(headers[0].hashPrevBlock) && nCount < MAX_BLOCKS_TO_ANNOUNCE) {
nodestate->nUnconnectingHeaders++;
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256()));
LogPrint(BCLog::NET, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n",
headers[0].GetHash().ToString(),
headers[0].hashPrevBlock.ToString(),
pindexBestHeader->nHeight,
pfrom->GetId(), nodestate->nUnconnectingHeaders);
// Set hashLastUnknownBlock for this peer, so that if we
// eventually get the headers - even from a different peer -
// we can use this peer to download.
UpdateBlockAvailability(pfrom->GetId(), headers.back().GetHash());
if (nodestate->nUnconnectingHeaders % MAX_UNCONNECTING_HEADERS == 0) {
Misbehaving(pfrom->GetId(), 20);
}
return true;
}
uint256 hashLastBlock;
for (const CBlockHeader& header : headers) {
if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock) {
Misbehaving(pfrom->GetId(), 20, "non-continuous headers sequence");
return false;
}
hashLastBlock = header.GetHash();
}
// If we don't have the last header, then they'll have given us
// something new (if these headers are valid).
if (!LookupBlockIndex(hashLastBlock)) {
received_new_header = true;
}
}
CValidationState state;
CBlockHeader first_invalid_header;
if (!ProcessNewBlockHeaders(headers, state, chainparams, &pindexLast, &first_invalid_header, &received_new_header)) {
int nDoS;
if (state.IsInvalid(nDoS)) {
LOCK(cs_main);
if (nDoS > 0) {
Misbehaving(pfrom->GetId(), nDoS, "invalid header received");
} else {
LogPrint(BCLog::NET, "peer=%d: invalid header received\n", pfrom->GetId());
}
if (punish_duplicate_invalid && LookupBlockIndex(first_invalid_header.GetHash())) {
// Goal: don't allow outbound peers to use up our outbound
// connection slots if they are on incompatible chains.
//
// We ask the caller to set punish_invalid appropriately based
// on the peer and the method of header delivery (compact
// blocks are allowed to be invalid in some circumstances,
// under BIP 152).
// Here, we try to detect the narrow situation that we have a
// valid block header (ie it was valid at the time the header
// was received, and hence stored in mapBlockIndex) but know the
// block is invalid, and that a peer has announced that same
// block as being on its active chain.
// Disconnect the peer in such a situation.
//
// Note: if the header that is invalid was not accepted to our
// mapBlockIndex at all, that may also be grounds for
// disconnecting the peer, as the chain they are on is likely
// to be incompatible. However, there is a circumstance where
// that does not hold: if the header's timestamp is more than
// 2 hours ahead of our current time. In that case, the header
// may become valid in the future, and we don't want to
// disconnect a peer merely for serving us one too-far-ahead
// block header, to prevent an attacker from splitting the
// network by mining a block right at the 2 hour boundary.
//
// TODO: update the DoS logic (or, rather, rewrite the
// DoS-interface between validation and net_processing) so that
// the interface is cleaner, and so that we disconnect on all the
// reasons that a peer's headers chain is incompatible
// with ours (eg block->nVersion softforks, MTP violations,
// etc), and not just the duplicate-invalid case.
pfrom->fDisconnect = true;
}
return false;
}
}
{
LOCK(cs_main);
CNodeState *nodestate = State(pfrom->GetId());
if (nodestate->nUnconnectingHeaders > 0) {
LogPrint(BCLog::NET, "peer=%d: resetting nUnconnectingHeaders (%d -> 0)\n", pfrom->GetId(), nodestate->nUnconnectingHeaders);
}
nodestate->nUnconnectingHeaders = 0;
assert(pindexLast);
UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
// From here, pindexBestKnownBlock should be guaranteed to be non-null,
// because it is set in UpdateBlockAvailability. Some nullptr checks
// are still present, however, as belt-and-suspenders.
if (received_new_header && pindexLast->nChainWork > chainActive.Tip()->nChainWork) {
nodestate->m_last_block_announcement = GetTime();
}
if (nCount == MAX_HEADERS_RESULTS) {
// Headers message had its maximum size; the peer may have more headers.
// TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
// from there instead.
LogPrint(BCLog::NET, "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->GetId(), pfrom->nStartingHeight);
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexLast), uint256()));
}
bool fCanDirectFetch = CanDirectFetch(chainparams.GetConsensus());
// If this set of headers is valid and ends in a block with at least as
// much work as our tip, download as much as possible.
if (fCanDirectFetch && pindexLast->IsValid(BLOCK_VALID_TREE) && chainActive.Tip()->nChainWork <= pindexLast->nChainWork) {
std::vector<const CBlockIndex*> vToFetch;
const CBlockIndex *pindexWalk = pindexLast;
// Calculate all the blocks we'd need to switch to pindexLast, up to a limit.
while (pindexWalk && !chainActive.Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) &&
!mapBlocksInFlight.count(pindexWalk->GetBlockHash()) &&
(!IsWitnessEnabled(pindexWalk->pprev, chainparams.GetConsensus()) || State(pfrom->GetId())->fHaveWitness)) {
// We don't have this block, and it's not yet in flight.
vToFetch.push_back(pindexWalk);
}
pindexWalk = pindexWalk->pprev;
}
// If pindexWalk still isn't on our main chain, we're looking at a
// very large reorg at a time we think we're close to caught up to
// the main chain -- this shouldn't really happen. Bail out on the
// direct fetch and rely on parallel download instead.
if (!chainActive.Contains(pindexWalk)) {
LogPrint(BCLog::NET, "Large reorg, won't direct fetch to %s (%d)\n",
pindexLast->GetBlockHash().ToString(),
pindexLast->nHeight);
} else {
std::vector<CInv> vGetData;
// Download as much as possible, from earliest to latest.
for (const CBlockIndex *pindex : reverse_iterate(vToFetch)) {
if (nodestate->nBlocksInFlight >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
// Can't download any more from this peer
break;
}
uint32_t nFetchFlags = GetFetchFlags(pfrom);
vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), pindex);
LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n",
pindex->GetBlockHash().ToString(), pfrom->GetId());
}
if (vGetData.size() > 1) {
LogPrint(BCLog::NET, "Downloading blocks toward %s (%d) via headers direct fetch\n",
pindexLast->GetBlockHash().ToString(), pindexLast->nHeight);
}
if (vGetData.size() > 0) {
if (nodestate->fSupportsDesiredCmpctVersion && vGetData.size() == 1 && mapBlocksInFlight.size() == 1 && pindexLast->pprev->IsValid(BLOCK_VALID_CHAIN)) {
// In any case, we want to download using a compact block, not a regular one
vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash);
}
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vGetData));
}
}
}
// If we're in IBD, we want outbound peers that will serve us a useful
// chain. Disconnect peers that are on chains with insufficient work.
if (IsInitialBlockDownload() && nCount != MAX_HEADERS_RESULTS) {
// When nCount < MAX_HEADERS_RESULTS, we know we have no more
// headers to fetch from this peer.
if (nodestate->pindexBestKnownBlock && nodestate->pindexBestKnownBlock->nChainWork < nMinimumChainWork) {
// This peer has too little work on their headers chain to help
// us sync -- disconnect if using an outbound slot (unless
// whitelisted or addnode).
// Note: We compare their tip to nMinimumChainWork (rather than
// chainActive.Tip()) because we won't start block download
// until we have a headers chain that has at least
// nMinimumChainWork, even if a peer has a chain past our tip,
// as an anti-DoS measure.
if (IsOutboundDisconnectionCandidate(pfrom)) {
LogPrintf("Disconnecting outbound peer %d -- headers chain has insufficient work\n", pfrom->GetId());
pfrom->fDisconnect = true;
}
}
}
if (!pfrom->fDisconnect && IsOutboundDisconnectionCandidate(pfrom) && nodestate->pindexBestKnownBlock != nullptr) {
// If this is an outbound peer, check to see if we should protect
// it from the bad/lagging chain logic.
if (g_outbound_peers_with_protect_from_disconnect < MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT && nodestate->pindexBestKnownBlock->nChainWork >= chainActive.Tip()->nChainWork && !nodestate->m_chain_sync.m_protect) {
LogPrint(BCLog::NET, "Protecting outbound peer=%d from eviction\n", pfrom->GetId());
nodestate->m_chain_sync.m_protect = true;
++g_outbound_peers_with_protect_from_disconnect;
}
}
}
return true;
}
bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, int64_t nTimeReceived, const CChainParams& chainparams, CConnman* connman, const std::atomic<bool>& interruptMsgProc)
{
LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->GetId());
if (gArgs.IsArgSet("-dropmessagestest") && GetRand(gArgs.GetArg("-dropmessagestest", 0)) == 0)
{
LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
return true;
}
if (!(pfrom->GetLocalServices() & NODE_BLOOM) &&
(strCommand == NetMsgType::FILTERLOAD ||
strCommand == NetMsgType::FILTERADD))
{
if (pfrom->nVersion >= NO_BLOOM_VERSION) {
LOCK(cs_main);
Misbehaving(pfrom->GetId(), 100);
return false;
} else {
pfrom->fDisconnect = true;
return false;
}
}
if (strCommand == NetMsgType::REJECT)
{
if (LogAcceptCategory(BCLog::NET)) {
try {
std::string strMsg; unsigned char ccode; std::string strReason;
vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
std::ostringstream ss;
ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
if (strMsg == NetMsgType::BLOCK || strMsg == NetMsgType::TX)
{
uint256 hash;
vRecv >> hash;
ss << ": hash " << hash.ToString();
}
LogPrint(BCLog::NET, "Reject %s\n", SanitizeString(ss.str()));
} catch (const std::ios_base::failure&) {
// Avoid feedback loops by preventing reject messages from triggering a new reject message.
LogPrint(BCLog::NET, "Unparseable reject message received\n");
}
}
return true;
}
else if (strCommand == NetMsgType::VERSION)
{
// Each connection can only send one version message
if (pfrom->nVersion != 0)
{
if (g_enable_bip61) {
connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_DUPLICATE, std::string("Duplicate version message")));
}
LOCK(cs_main);
Misbehaving(pfrom->GetId(), 1);
return false;
}
int64_t nTime;
CAddress addrMe;
CAddress addrFrom;
uint64_t nNonce = 1;
uint64_t nServiceInt;
ServiceFlags nServices;
int nVersion;
int nSendVersion;
std::string strSubVer;
std::string cleanSubVer;
int nStartingHeight = -1;
bool fRelay = true;
vRecv >> nVersion >> nServiceInt >> nTime >> addrMe;
nSendVersion = std::min(nVersion, PROTOCOL_VERSION);
nServices = ServiceFlags(nServiceInt);
if (!pfrom->fInbound)
{
connman->SetServices(pfrom->addr, nServices);
}
if (!pfrom->fInbound && !pfrom->fFeeler && !pfrom->m_manual_connection && !HasAllDesirableServiceFlags(nServices))
{
LogPrint(BCLog::NET, "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom->GetId(), nServices, GetDesirableServiceFlags(nServices));
if (g_enable_bip61) {
connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_NONSTANDARD,
strprintf("Expected to offer services %08x", GetDesirableServiceFlags(nServices))));
}
pfrom->fDisconnect = true;
return false;
}
if (nServices & ((1 << 7) | (1 << 5))) {
if (GetTime() < 1533096000) {
// Immediately disconnect peers that use service bits 6 or 8 until August 1st, 2018
// These bits have been used as a flag to indicate that a node is running incompatible
// consensus rules instead of changing the network magic, so we're stuck disconnecting
// based on these service bits, at least for a while.
pfrom->fDisconnect = true;
return false;
}
}
if (nVersion < MIN_PEER_PROTO_VERSION)
{
// disconnect from peers older than this proto version
LogPrint(BCLog::NET, "peer=%d using obsolete version %i; disconnecting\n", pfrom->GetId(), nVersion);
if (g_enable_bip61) {
connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE,
strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION)));
}
pfrom->fDisconnect = true;
return false;
}
if (nVersion == 10300)
nVersion = 300;
if (!vRecv.empty())
vRecv >> addrFrom >> nNonce;
if (!vRecv.empty()) {
vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH);
cleanSubVer = SanitizeString(strSubVer);
}
if (!vRecv.empty()) {
vRecv >> nStartingHeight;
}
if (!vRecv.empty())
vRecv >> fRelay;
// Disconnect if we connected to ourself
if (pfrom->fInbound && !connman->CheckIncomingNonce(nNonce))
{
LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
pfrom->fDisconnect = true;
return true;
}
if (pfrom->fInbound && addrMe.IsRoutable())
{
SeenLocal(addrMe);
}
// Be shy and don't send version until we hear
if (pfrom->fInbound)
PushNodeVersion(pfrom, connman, GetAdjustedTime());
connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERACK));
pfrom->nServices = nServices;
pfrom->SetAddrLocal(addrMe);
{
LOCK(pfrom->cs_SubVer);
pfrom->strSubVer = strSubVer;
pfrom->cleanSubVer = cleanSubVer;
}
pfrom->nStartingHeight = nStartingHeight;
// set nodes not relaying blocks and tx and not serving (parts) of the historical blockchain as "clients"
pfrom->fClient = (!(nServices & NODE_NETWORK) && !(nServices & NODE_NETWORK_LIMITED));
// set nodes not capable of serving the complete blockchain history as "limited nodes"
pfrom->m_limited_node = (!(nServices & NODE_NETWORK) && (nServices & NODE_NETWORK_LIMITED));
{
LOCK(pfrom->cs_filter);
pfrom->fRelayTxes = fRelay; // set to true after we get the first filter* message
}
// Change version
pfrom->SetSendVersion(nSendVersion);
pfrom->nVersion = nVersion;
if((nServices & NODE_WITNESS))
{
LOCK(cs_main);
State(pfrom->GetId())->fHaveWitness = true;
}
// Potentially mark this peer as a preferred download peer.
{
LOCK(cs_main);
UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
}
if (!pfrom->fInbound)
{
// Advertise our address
if (fListen && !IsInitialBlockDownload())
{
CAddress addr = GetLocalAddress(&pfrom->addr, pfrom->GetLocalServices());
FastRandomContext insecure_rand;
if (addr.IsRoutable())
{
LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
pfrom->PushAddress(addr, insecure_rand);
} else if (IsPeerAddrLocalGood(pfrom)) {
addr.SetIP(addrMe);
LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
pfrom->PushAddress(addr, insecure_rand);
}
}
// Get recent addresses
if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || connman->GetAddressCount() < 1000)
{
connman->PushMessage(pfrom, CNetMsgMaker(nSendVersion).Make(NetMsgType::GETADDR));
pfrom->fGetAddr = true;
}
connman->MarkAddressGood(pfrom->addr);
}
std::string remoteAddr;
if (fLogIPs)
remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
LogPrint(BCLog::NET, "receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
cleanSubVer, pfrom->nVersion,
pfrom->nStartingHeight, addrMe.ToString(), pfrom->GetId(),
remoteAddr);
int64_t nTimeOffset = nTime - GetTime();
pfrom->nTimeOffset = nTimeOffset;
AddTimeData(pfrom->addr, nTimeOffset);
// If the peer is old enough to have the old alert system, send it the final alert.
if (pfrom->nVersion <= 70012) {
CDataStream finalAlert(ParseHex("60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50"), SER_NETWORK, PROTOCOL_VERSION);
connman->PushMessage(pfrom, CNetMsgMaker(nSendVersion).Make("alert", finalAlert));
}
// Feeler connections exist only to verify if address is online.
if (pfrom->fFeeler) {
assert(pfrom->fInbound == false);
pfrom->fDisconnect = true;
}
return true;
}
else if (pfrom->nVersion == 0)
{
// Must have a version message before anything else
LOCK(cs_main);
Misbehaving(pfrom->GetId(), 1);
return false;
}
// At this point, the outgoing message serialization version can't change.
const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
if (strCommand == NetMsgType::VERACK)
{
pfrom->SetRecvVersion(std::min(pfrom->nVersion.load(), PROTOCOL_VERSION));
if (!pfrom->fInbound) {
// Mark this node as currently connected, so we update its timestamp later.
LOCK(cs_main);
State(pfrom->GetId())->fCurrentlyConnected = true;
LogPrintf("New outbound peer connected: version: %d, blocks=%d, peer=%d%s\n",
pfrom->nVersion.load(), pfrom->nStartingHeight, pfrom->GetId(),
(fLogIPs ? strprintf(", peeraddr=%s", pfrom->addr.ToString()) : ""));
}
if (pfrom->nVersion >= SENDHEADERS_VERSION) {
// Tell our peer we prefer to receive headers rather than inv's
// We send this to non-NODE NETWORK peers as well, because even
// non-NODE NETWORK peers can announce blocks (such as pruning
// nodes)
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDHEADERS));
}
if (pfrom->nVersion >= SHORT_IDS_BLOCKS_VERSION) {
// Tell our peer we are willing to provide version 1 or 2 cmpctblocks
// However, we do not request new block announcements using
// cmpctblock messages.
// We send this to non-NODE NETWORK peers as well, because
// they may wish to request compact blocks from us
bool fAnnounceUsingCMPCTBLOCK = false;
uint64_t nCMPCTBLOCKVersion = 2;
if (pfrom->GetLocalServices() & NODE_WITNESS)
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
nCMPCTBLOCKVersion = 1;
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
}
pfrom->fSuccessfullyConnected = true;
}
else if (!pfrom->fSuccessfullyConnected)
{
// Must have a verack message before anything else
LOCK(cs_main);
Misbehaving(pfrom->GetId(), 1);
return false;
}
else if (strCommand == NetMsgType::ADDR)
{
std::vector<CAddress> vAddr;
vRecv >> vAddr;
// Don't want addr from older versions unless seeding
if (pfrom->nVersion < CADDR_TIME_VERSION && connman->GetAddressCount() > 1000)
return true;
if (vAddr.size() > 1000)
{
LOCK(cs_main);
Misbehaving(pfrom->GetId(), 20, strprintf("message addr size() = %u", vAddr.size()));
return false;
}
// Store the new addresses
std::vector<CAddress> vAddrOk;
int64_t nNow = GetAdjustedTime();
int64_t nSince = nNow - 10 * 60;
for (CAddress& addr : vAddr)
{
if (interruptMsgProc)
return true;
// We only bother storing full nodes, though this may include
// things which we would not make an outbound connection to, in
// part because we may make feeler connections to them.
if (!MayHaveUsefulAddressDB(addr.nServices) && !HasAllDesirableServiceFlags(addr.nServices))
continue;
if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
addr.nTime = nNow - 5 * 24 * 60 * 60;
pfrom->AddAddressKnown(addr);
bool fReachable = IsReachable(addr);
if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
{
// Relay to a limited number of other nodes
RelayAddress(addr, fReachable, connman);
}
// Do not store addresses outside our network
if (fReachable)
vAddrOk.push_back(addr);
}
connman->AddNewAddresses(vAddrOk, pfrom->addr, 2 * 60 * 60);
if (vAddr.size() < 1000)
pfrom->fGetAddr = false;
if (pfrom->fOneShot)
pfrom->fDisconnect = true;
}
else if (strCommand == NetMsgType::SENDHEADERS)
{
LOCK(cs_main);
State(pfrom->GetId())->fPreferHeaders = true;
}
else if (strCommand == NetMsgType::SENDCMPCT)
{
bool fAnnounceUsingCMPCTBLOCK = false;
uint64_t nCMPCTBLOCKVersion = 0;
vRecv >> fAnnounceUsingCMPCTBLOCK >> nCMPCTBLOCKVersion;
if (nCMPCTBLOCKVersion == 1 || ((pfrom->GetLocalServices() & NODE_WITNESS) && nCMPCTBLOCKVersion == 2)) {
LOCK(cs_main);
// fProvidesHeaderAndIDs is used to "lock in" version of compact blocks we send (fWantsCmpctWitness)
if (!State(pfrom->GetId())->fProvidesHeaderAndIDs) {
State(pfrom->GetId())->fProvidesHeaderAndIDs = true;
State(pfrom->GetId())->fWantsCmpctWitness = nCMPCTBLOCKVersion == 2;
}
if (State(pfrom->GetId())->fWantsCmpctWitness == (nCMPCTBLOCKVersion == 2)) // ignore later version announces
State(pfrom->GetId())->fPreferHeaderAndIDs = fAnnounceUsingCMPCTBLOCK;
if (!State(pfrom->GetId())->fSupportsDesiredCmpctVersion) {
if (pfrom->GetLocalServices() & NODE_WITNESS)
State(pfrom->GetId())->fSupportsDesiredCmpctVersion = (nCMPCTBLOCKVersion == 2);
else
State(pfrom->GetId())->fSupportsDesiredCmpctVersion = (nCMPCTBLOCKVersion == 1);
}
}
}
else if (strCommand == NetMsgType::INV)
{
std::vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ)
{
LOCK(cs_main);
Misbehaving(pfrom->GetId(), 20, strprintf("message inv size() = %u", vInv.size()));
return false;
}
bool fBlocksOnly = !fRelayTxes;
// Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true
if (pfrom->fWhitelisted && gArgs.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY))
fBlocksOnly = false;
LOCK(cs_main);
uint32_t nFetchFlags = GetFetchFlags(pfrom);
for (CInv &inv : vInv)
{
if (interruptMsgProc)
return true;
bool fAlreadyHave = AlreadyHave(inv);
LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->GetId());
if (inv.type == MSG_TX) {
inv.type |= nFetchFlags;
}
if (inv.type == MSG_BLOCK) {
UpdateBlockAvailability(pfrom->GetId(), inv.hash);
if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
// We used to request the full block here, but since headers-announcements are now the
// primary method of announcement on the network, and since, in the case that a node
// fell back to inv we probably have a reorg which we should get the headers for first,
// we now only provide a getheaders response here. When we receive the headers, we will
// then ask for the blocks we need.
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), inv.hash));
LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->GetId());
}
}
else
{
pfrom->AddInventoryKnown(inv);
if (fBlocksOnly) {
LogPrint(BCLog::NET, "transaction (%s) inv sent in violation of protocol peer=%d\n", inv.hash.ToString(), pfrom->GetId());
} else if (!fAlreadyHave && !fImporting && !fReindex && !IsInitialBlockDownload()) {
pfrom->AskFor(inv);
}
}
// Track requests for our stuff
GetMainSignals().Inventory(inv.hash);
}
}
else if (strCommand == NetMsgType::GETDATA)
{
std::vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ)
{
LOCK(cs_main);
Misbehaving(pfrom->GetId(), 20, strprintf("message getdata size() = %u", vInv.size()));
return false;
}
LogPrint(BCLog::NET, "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->GetId());
if (vInv.size() > 0) {
LogPrint(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->GetId());
}
pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
ProcessGetData(pfrom, chainparams, connman, interruptMsgProc);
}
else if (strCommand == NetMsgType::GETBLOCKS)
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
// We might have announced the currently-being-connected tip using a
// compact block, which resulted in the peer sending a getblocks
// request, which we would otherwise respond to without the new block.
// To avoid this situation we simply verify that we are on our best
// known chain now. This is super overkill, but we handle it better
// for getheaders requests, and there are no known nodes which support
// compact blocks but still use getblocks to request blocks.
{
std::shared_ptr<const CBlock> a_recent_block;
{
LOCK(cs_most_recent_block);
a_recent_block = most_recent_block;
}
CValidationState state;
if (!ActivateBestChain(state, Params(), a_recent_block)) {
LogPrint(BCLog::NET, "failed to activate chain (%s)\n", FormatStateMessage(state));
}
}
LOCK(cs_main);
// Find the last block the caller has in the main chain
const CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
// Send the rest of the chain
if (pindex)
pindex = chainActive.Next(pindex);
int nLimit = 500;
LogPrint(BCLog::NET, "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->GetId());
for (; pindex; pindex = chainActive.Next(pindex))
{
if (pindex->GetBlockHash() == hashStop)
{
LogPrint(BCLog::NET, " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
break;
}
// If pruning, don't inv blocks unless we have on disk and are likely to still have
// for some reasonable time window (1 hour) that block relay might require.
const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / chainparams.GetConsensus().nPowTargetSpacing;
if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= chainActive.Tip()->nHeight - nPrunedBlocksLikelyToHave))
{
LogPrint(BCLog::NET, " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
break;
}
pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
if (--nLimit <= 0)
{
// When this block is requested, we'll send an inv that'll
// trigger the peer to getblocks the next batch of inventory.
LogPrint(BCLog::NET, " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
pfrom->hashContinue = pindex->GetBlockHash();
break;
}
}
}
else if (strCommand == NetMsgType::GETBLOCKTXN)
{
BlockTransactionsRequest req;
vRecv >> req;
std::shared_ptr<const CBlock> recent_block;
{
LOCK(cs_most_recent_block);
if (most_recent_block_hash == req.blockhash)
recent_block = most_recent_block;
// Unlock cs_most_recent_block to avoid cs_main lock inversion
}
if (recent_block) {
SendBlockTransactions(*recent_block, req, pfrom, connman);
return true;
}
LOCK(cs_main);
const CBlockIndex* pindex = LookupBlockIndex(req.blockhash);
if (!pindex || !(pindex->nStatus & BLOCK_HAVE_DATA)) {
LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block we don't have\n", pfrom->GetId());
return true;
}
if (pindex->nHeight < chainActive.Height() - MAX_BLOCKTXN_DEPTH) {
// If an older block is requested (should never happen in practice,
// but can happen in tests) send a block response instead of a
// blocktxn response. Sending a full block response instead of a
// small blocktxn response is preferable in the case where a peer
// might maliciously send lots of getblocktxn requests to trigger
// expensive disk reads, because it will require the peer to
// actually receive all the data read from disk over the network.
LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block > %i deep\n", pfrom->GetId(), MAX_BLOCKTXN_DEPTH);
CInv inv;
inv.type = State(pfrom->GetId())->fWantsCmpctWitness ? MSG_WITNESS_BLOCK : MSG_BLOCK;
inv.hash = req.blockhash;
pfrom->vRecvGetData.push_back(inv);
// The message processing loop will go around again (without pausing) and we'll respond then (without cs_main)
return true;
}
CBlock block;
bool ret = ReadBlockFromDisk(block, pindex, chainparams.GetConsensus());
assert(ret);
SendBlockTransactions(block, req, pfrom, connman);
}
else if (strCommand == NetMsgType::GETHEADERS)
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
LOCK(cs_main);
if (IsInitialBlockDownload() && !pfrom->fWhitelisted) {
LogPrint(BCLog::NET, "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom->GetId());
return true;
}
CNodeState *nodestate = State(pfrom->GetId());
const CBlockIndex* pindex = nullptr;
if (locator.IsNull())
{
// If locator is null, return the hashStop block
pindex = LookupBlockIndex(hashStop);
if (!pindex) {
return true;
}
if (!BlockRequestAllowed(pindex, chainparams.GetConsensus())) {
LogPrint(BCLog::NET, "%s: ignoring request from peer=%i for old block header that isn't in the main chain\n", __func__, pfrom->GetId());
return true;
}
}
else
{
// Find the last block the caller has in the main chain
pindex = FindForkInGlobalIndex(chainActive, locator);
if (pindex)
pindex = chainActive.Next(pindex);
}
// we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
std::vector<CBlock> vHeaders;
int nLimit = MAX_HEADERS_RESULTS;
LogPrint(BCLog::NET, "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom->GetId());
for (; pindex; pindex = chainActive.Next(pindex))
{
vHeaders.push_back(pindex->GetBlockHeader());
if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
break;
}
// pindex can be nullptr either if we sent chainActive.Tip() OR
// if our peer has chainActive.Tip() (and thus we are sending an empty
// headers message). In both cases it's safe to update
// pindexBestHeaderSent to be our tip.
//
// It is important that we simply reset the BestHeaderSent value here,
// and not max(BestHeaderSent, newHeaderSent). We might have announced
// the currently-being-connected tip using a compact block, which
// resulted in the peer sending a headers request, which we respond to
// without the new block. By resetting the BestHeaderSent, we ensure we
// will re-announce the new block via headers (or compact blocks again)
// in the SendMessages logic.
nodestate->pindexBestHeaderSent = pindex ? pindex : chainActive.Tip();
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
}
else if (strCommand == NetMsgType::TX)
{
// Stop processing the transaction early if
// We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off
if (!fRelayTxes && (!pfrom->fWhitelisted || !gArgs.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)))
{
LogPrint(BCLog::NET, "transaction sent in violation of protocol peer=%d\n", pfrom->GetId());
return true;
}
std::deque<COutPoint> vWorkQueue;
std::vector<uint256> vEraseQueue;
CTransactionRef ptx;
vRecv >> ptx;
const CTransaction& tx = *ptx;
CInv inv(MSG_TX, tx.GetHash());
pfrom->AddInventoryKnown(inv);
bool fMissingInputs = false;
CValidationState state;
std::list<CTransactionRef> lRemovedTxn;
LOCK2(cs_main, g_cs_orphans);
pfrom->setAskFor.erase(inv.hash);
mapAlreadyAskedFor.erase(inv.hash);
if (!AlreadyHave(inv) &&
AcceptToMemoryPool(mempool, state, ptx, &fMissingInputs, &lRemovedTxn, false /* bypass_limits */, 0 /* nAbsurdFee */)) {
//mempool.check(pcoinsTip.get());
RelayTransaction(tx, connman);
for (unsigned int i = 0; i < tx.vout.size(); i++) {
vWorkQueue.emplace_back(inv.hash, i);
}
pfrom->nLastTXTime = GetTime();
LogPrint(BCLog::MEMPOOL, "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
pfrom->GetId(),
tx.GetHash().ToString(),
mempool.size(), mempool.DynamicMemoryUsage() / 1000);
// Recursively process any orphan transactions that depended on this one
std::set<NodeId> setMisbehaving;
while (!vWorkQueue.empty()) {
auto itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue.front());
vWorkQueue.pop_front();
if (itByPrev == mapOrphanTransactionsByPrev.end())
continue;
for (auto mi = itByPrev->second.begin();
mi != itByPrev->second.end();
++mi)
{
const CTransactionRef& porphanTx = (*mi)->second.tx;
const CTransaction& orphanTx = *porphanTx;
const uint256& orphanHash = orphanTx.GetHash();
NodeId fromPeer = (*mi)->second.fromPeer;
bool fMissingInputs2 = false;
// Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
// resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
// anyone relaying LegitTxX banned)
CValidationState stateDummy;
if (setMisbehaving.count(fromPeer))
continue;
if (AcceptToMemoryPool(mempool, stateDummy, porphanTx, &fMissingInputs2, &lRemovedTxn, false /* bypass_limits */, 0 /* nAbsurdFee */)) {
LogPrint(BCLog::MEMPOOL, " accepted orphan tx %s\n", orphanHash.ToString());
RelayTransaction(orphanTx, connman);
for (unsigned int i = 0; i < orphanTx.vout.size(); i++) {
vWorkQueue.emplace_back(orphanHash, i);
}
vEraseQueue.push_back(orphanHash);
}
else if (!fMissingInputs2)
{
int nDos = 0;
if (stateDummy.IsInvalid(nDos) && nDos > 0)
{
// Punish peer that gave us an invalid orphan tx
Misbehaving(fromPeer, nDos);
setMisbehaving.insert(fromPeer);
LogPrint(BCLog::MEMPOOL, " invalid orphan tx %s\n", orphanHash.ToString());
}
// Has inputs but not accepted to mempool
// Probably non-standard or insufficient fee
LogPrint(BCLog::MEMPOOL, " removed orphan tx %s\n", orphanHash.ToString());
vEraseQueue.push_back(orphanHash);
if (!orphanTx.HasWitness() && !stateDummy.CorruptionPossible()) {
// Do not use rejection cache for witness transactions or
// witness-stripped transactions, as they can have been malleated.
// See https://github.com/bitcoin/bitcoin/issues/8279 for details.
assert(recentRejects);
recentRejects->insert(orphanHash);
}
}
mempool.check(pcoinsTip.get());
}
}
for (uint256 hash : vEraseQueue)
EraseOrphanTx(hash);
}
else if (fMissingInputs)
{
bool fRejectedParents = false; // It may be the case that the orphans parents have all been rejected
for (const CTxIn& txin : tx.vin) {
if (recentRejects->contains(txin.prevout.hash)) {
fRejectedParents = true;
break;
}
}
if (!fRejectedParents) {
uint32_t nFetchFlags = GetFetchFlags(pfrom);
for (const CTxIn& txin : tx.vin) {
CInv _inv(MSG_TX | nFetchFlags, txin.prevout.hash);
pfrom->AddInventoryKnown(_inv);
if (!AlreadyHave(_inv)) pfrom->AskFor(_inv);
}
AddOrphanTx(ptx, pfrom->GetId());
// DoS prevention: do not allow mapOrphanTransactions to grow unbounded
unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, gArgs.GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
if (nEvicted > 0) {
LogPrint(BCLog::MEMPOOL, "mapOrphan overflow, removed %u tx\n", nEvicted);
}
} else {
LogPrint(BCLog::MEMPOOL, "not keeping orphan with rejected parents %s\n",tx.GetHash().ToString());
// We will continue to reject this tx since it has rejected
// parents so avoid re-requesting it from other peers.
recentRejects->insert(tx.GetHash());
}
} else {
if (!tx.HasWitness() && !state.CorruptionPossible()) {
// Do not use rejection cache for witness transactions or
// witness-stripped transactions, as they can have been malleated.
// See https://github.com/bitcoin/bitcoin/issues/8279 for details.
assert(recentRejects);
recentRejects->insert(tx.GetHash());
if (RecursiveDynamicUsage(*ptx) < 100000) {
AddToCompactExtraTransactions(ptx);
}
} else if (tx.HasWitness() && RecursiveDynamicUsage(*ptx) < 100000) {
AddToCompactExtraTransactions(ptx);
}
if (pfrom->fWhitelisted && gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
// Always relay transactions received from whitelisted peers, even
// if they were already in the mempool or rejected from it due
// to policy, allowing the node to function as a gateway for
// nodes hidden behind it.
//
// Never relay transactions that we would assign a non-zero DoS
// score for, as we expect peers to do the same with us in that
// case.
int nDoS = 0;
if (!state.IsInvalid(nDoS) || nDoS == 0) {
LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->GetId());
RelayTransaction(tx, connman);
} else {
LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s)\n", tx.GetHash().ToString(), pfrom->GetId(), FormatStateMessage(state));
}
}
}
for (const CTransactionRef& removedTx : lRemovedTxn)
AddToCompactExtraTransactions(removedTx);
int nDoS = 0;
if (state.IsInvalid(nDoS))
{
LogPrint(BCLog::MEMPOOLREJ, "%s from peer=%d was not accepted: %s\n", tx.GetHash().ToString(),
pfrom->GetId(),
FormatStateMessage(state));
if (g_enable_bip61 && state.GetRejectCode() > 0 && state.GetRejectCode() < REJECT_INTERNAL) { // Never send AcceptToMemoryPool's internal codes over P2P
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::REJECT, strCommand, (unsigned char)state.GetRejectCode(),
state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash));
}
if (nDoS > 0) {
Misbehaving(pfrom->GetId(), nDoS);
}
}
}
else if (strCommand == NetMsgType::CMPCTBLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
{
CBlockHeaderAndShortTxIDs cmpctblock;
vRecv >> cmpctblock;
bool received_new_header = false;
{
LOCK(cs_main);
if (!LookupBlockIndex(cmpctblock.header.hashPrevBlock)) {
// Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
if (!IsInitialBlockDownload())
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256()));
return true;
}
if (!LookupBlockIndex(cmpctblock.header.GetHash())) {
received_new_header = true;
}
}
const CBlockIndex *pindex = nullptr;
CValidationState state;
if (!ProcessNewBlockHeaders({cmpctblock.header}, state, chainparams, &pindex, nullptr, &received_new_header)) {
int nDoS;
if (state.IsInvalid(nDoS)) {
if (nDoS > 0) {
LOCK(cs_main);
Misbehaving(pfrom->GetId(), nDoS, strprintf("Peer %d sent us invalid header via cmpctblock\n", pfrom->GetId()));
} else {
LogPrint(BCLog::NET, "Peer %d sent us invalid header via cmpctblock\n", pfrom->GetId());
}
return true;
}
}
// When we succeed in decoding a block's txids from a cmpctblock
// message we typically jump to the BLOCKTXN handling code, with a
// dummy (empty) BLOCKTXN message, to re-use the logic there in
// completing processing of the putative block (without cs_main).
bool fProcessBLOCKTXN = false;
CDataStream blockTxnMsg(SER_NETWORK, PROTOCOL_VERSION);
// If we end up treating this as a plain headers message, call that as well
// without cs_main.
bool fRevertToHeaderProcessing = false;
// Keep a CBlock for "optimistic" compactblock reconstructions (see
// below)
std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
bool fBlockReconstructed = false;
{
LOCK2(cs_main, g_cs_orphans);
// If AcceptBlockHeader returned true, it set pindex
assert(pindex);
UpdateBlockAvailability(pfrom->GetId(), pindex->GetBlockHash());
CNodeState *nodestate = State(pfrom->GetId());
// If this was a new header with more work than our tip, update the
// peer's last block announcement time
if (received_new_header && pindex->nChainWork > chainActive.Tip()->nChainWork) {
nodestate->m_last_block_announcement = GetTime();
}
std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator blockInFlightIt = mapBlocksInFlight.find(pindex->GetBlockHash());
bool fAlreadyInFlight = blockInFlightIt != mapBlocksInFlight.end();
if (pindex->nStatus & BLOCK_HAVE_DATA) // Nothing to do here
return true;
if (pindex->nChainWork <= chainActive.Tip()->nChainWork || // We know something better
pindex->nTx != 0) { // We had this block at some point, but pruned it
if (fAlreadyInFlight) {
// We requested this block for some reason, but our mempool will probably be useless
// so we just grab the block via normal getdata
std::vector<CInv> vInv(1);
vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
}
return true;
}
// If we're not close to tip yet, give up and let parallel block fetch work its magic
if (!fAlreadyInFlight && !CanDirectFetch(chainparams.GetConsensus()))
return true;
if (IsWitnessEnabled(pindex->pprev, chainparams.GetConsensus()) && !nodestate->fSupportsDesiredCmpctVersion) {
// Don't bother trying to process compact blocks from v1 peers
// after segwit activates.
return true;
}
// We want to be a bit conservative just to be extra careful about DoS
// possibilities in compact block processing...
if (pindex->nHeight <= chainActive.Height() + 2) {
if ((!fAlreadyInFlight && nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) ||
(fAlreadyInFlight && blockInFlightIt->second.first == pfrom->GetId())) {
std::list<QueuedBlock>::iterator* queuedBlockIt = nullptr;
if (!MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), pindex, &queuedBlockIt)) {
if (!(*queuedBlockIt)->partialBlock)
(*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&mempool));
else {
// The block was already in flight using compact blocks from the same peer
LogPrint(BCLog::NET, "Peer sent us compact block we were already syncing!\n");
return true;
}
}
PartiallyDownloadedBlock& partialBlock = *(*queuedBlockIt)->partialBlock;
ReadStatus status = partialBlock.InitData(cmpctblock, vExtraTxnForCompact);
if (status == READ_STATUS_INVALID) {
MarkBlockAsReceived(pindex->GetBlockHash()); // Reset in-flight state in case of whitelist
Misbehaving(pfrom->GetId(), 100, strprintf("Peer %d sent us invalid compact block\n", pfrom->GetId()));
return true;
} else if (status == READ_STATUS_FAILED) {
// Duplicate txindexes, the block is now in-flight, so just request it
std::vector<CInv> vInv(1);
vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
return true;
}
BlockTransactionsRequest req;
for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++) {
if (!partialBlock.IsTxAvailable(i))
req.indexes.push_back(i);
}
if (req.indexes.empty()) {
// Dirty hack to jump to BLOCKTXN code (TODO: move message handling into their own functions)
BlockTransactions txn;
txn.blockhash = cmpctblock.header.GetHash();
blockTxnMsg << txn;
fProcessBLOCKTXN = true;
} else {
req.blockhash = pindex->GetBlockHash();
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETBLOCKTXN, req));
}
} else {
// This block is either already in flight from a different
// peer, or this peer has too many blocks outstanding to
// download from.
// Optimistically try to reconstruct anyway since we might be
// able to without any round trips.
PartiallyDownloadedBlock tempBlock(&mempool);
ReadStatus status = tempBlock.InitData(cmpctblock, vExtraTxnForCompact);
if (status != READ_STATUS_OK) {
// TODO: don't ignore failures
return true;
}
std::vector<CTransactionRef> dummy;
status = tempBlock.FillBlock(*pblock, dummy);
if (status == READ_STATUS_OK) {
fBlockReconstructed = true;
}
}
} else {
if (fAlreadyInFlight) {
// We requested this block, but its far into the future, so our
// mempool will probably be useless - request the block normally
std::vector<CInv> vInv(1);
vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
return true;
} else {
// If this was an announce-cmpctblock, we want the same treatment as a header message
fRevertToHeaderProcessing = true;
}
}
} // cs_main
if (fProcessBLOCKTXN)
return ProcessMessage(pfrom, NetMsgType::BLOCKTXN, blockTxnMsg, nTimeReceived, chainparams, connman, interruptMsgProc);
if (fRevertToHeaderProcessing) {
// Headers received from HB compact block peers are permitted to be
// relayed before full validation (see BIP 152), so we don't want to disconnect
// the peer if the header turns out to be for an invalid block.
// Note that if a peer tries to build on an invalid chain, that
// will be detected and the peer will be banned.
return ProcessHeadersMessage(pfrom, connman, {cmpctblock.header}, chainparams, /*punish_duplicate_invalid=*/false);
}
if (fBlockReconstructed) {
// If we got here, we were able to optimistically reconstruct a
// block that is in flight from some other peer.
{
LOCK(cs_main);
mapBlockSource.emplace(pblock->GetHash(), std::make_pair(pfrom->GetId(), false));
}
bool fNewBlock = false;
// Setting fForceProcessing to true means that we bypass some of
// our anti-DoS protections in AcceptBlock, which filters
// unrequested blocks that might be trying to waste our resources
// (eg disk space). Because we only try to reconstruct blocks when
// we're close to caught up (via the CanDirectFetch() requirement
// above, combined with the behavior of not requesting blocks until
// we have a chain with at least nMinimumChainWork), and we ignore
// compact blocks with less work than our tip, it is safe to treat
// reconstructed compact blocks as having been requested.
ProcessNewBlock(chainparams, pblock, /*fForceProcessing=*/true, &fNewBlock);
if (fNewBlock) {
pfrom->nLastBlockTime = GetTime();
} else {
LOCK(cs_main);
mapBlockSource.erase(pblock->GetHash());
}
LOCK(cs_main); // hold cs_main for CBlockIndex::IsValid()
if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS)) {
// Clear download state for this block, which is in
// process from some other peer. We do this after calling
// ProcessNewBlock so that a malleated cmpctblock announcement
// can't be used to interfere with block relay.
MarkBlockAsReceived(pblock->GetHash());
}
}
}
else if (strCommand == NetMsgType::BLOCKTXN && !fImporting && !fReindex) // Ignore blocks received while importing
{
BlockTransactions resp;
vRecv >> resp;
std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
bool fBlockRead = false;
{
LOCK(cs_main);
std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator it = mapBlocksInFlight.find(resp.blockhash);
if (it == mapBlocksInFlight.end() || !it->second.second->partialBlock ||
it->second.first != pfrom->GetId()) {
LogPrint(BCLog::NET, "Peer %d sent us block transactions for block we weren't expecting\n", pfrom->GetId());
return true;
}
PartiallyDownloadedBlock& partialBlock = *it->second.second->partialBlock;
ReadStatus status = partialBlock.FillBlock(*pblock, resp.txn);
if (status == READ_STATUS_INVALID) {
MarkBlockAsReceived(resp.blockhash); // Reset in-flight state in case of whitelist
Misbehaving(pfrom->GetId(), 100, strprintf("Peer %d sent us invalid compact block/non-matching block transactions\n", pfrom->GetId()));
return true;
} else if (status == READ_STATUS_FAILED) {
// Might have collided, fall back to getdata now :(
std::vector<CInv> invs;
invs.push_back(CInv(MSG_BLOCK | GetFetchFlags(pfrom), resp.blockhash));
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, invs));
} else {
// Block is either okay, or possibly we received
// READ_STATUS_CHECKBLOCK_FAILED.
// Note that CheckBlock can only fail for one of a few reasons:
// 1. bad-proof-of-work (impossible here, because we've already
// accepted the header)
// 2. merkleroot doesn't match the transactions given (already
// caught in FillBlock with READ_STATUS_FAILED, so
// impossible here)
// 3. the block is otherwise invalid (eg invalid coinbase,
// block is too big, too many legacy sigops, etc).
// So if CheckBlock failed, #3 is the only possibility.
// Under BIP 152, we don't DoS-ban unless proof of work is
// invalid (we don't require all the stateless checks to have
// been run). This is handled below, so just treat this as
// though the block was successfully read, and rely on the
// handling in ProcessNewBlock to ensure the block index is
// updated, reject messages go out, etc.
MarkBlockAsReceived(resp.blockhash); // it is now an empty pointer
fBlockRead = true;
// mapBlockSource is only used for sending reject messages and DoS scores,
// so the race between here and cs_main in ProcessNewBlock is fine.
// BIP 152 permits peers to relay compact blocks after validating
// the header only; we should not punish peers if the block turns
// out to be invalid.
mapBlockSource.emplace(resp.blockhash, std::make_pair(pfrom->GetId(), false));
}
} // Don't hold cs_main when we call into ProcessNewBlock
if (fBlockRead) {
bool fNewBlock = false;
// Since we requested this block (it was in mapBlocksInFlight), force it to be processed,
// even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc)
// This bypasses some anti-DoS logic in AcceptBlock (eg to prevent
// disk-space attacks), but this should be safe due to the
// protections in the compact block handler -- see related comment
// in compact block optimistic reconstruction handling.
ProcessNewBlock(chainparams, pblock, /*fForceProcessing=*/true, &fNewBlock);
if (fNewBlock) {
pfrom->nLastBlockTime = GetTime();
} else {
LOCK(cs_main);
mapBlockSource.erase(pblock->GetHash());
}
}
}
else if (strCommand == NetMsgType::HEADERS && !fImporting && !fReindex) // Ignore headers received while importing
{
std::vector<CBlockHeader> headers;
// Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
unsigned int nCount = ReadCompactSize(vRecv);
if (nCount > MAX_HEADERS_RESULTS) {
LOCK(cs_main);
Misbehaving(pfrom->GetId(), 20, strprintf("headers message size = %u", nCount));
return false;
}
headers.resize(nCount);
for (unsigned int n = 0; n < nCount; n++) {
vRecv >> headers[n];
ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
}
// Headers received via a HEADERS message should be valid, and reflect
// the chain the peer is on. If we receive a known-invalid header,
// disconnect the peer if it is using one of our outbound connection
// slots.
bool should_punish = !pfrom->fInbound && !pfrom->m_manual_connection;
return ProcessHeadersMessage(pfrom, connman, headers, chainparams, should_punish);
}
else if (strCommand == NetMsgType::BLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
{
std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
vRecv >> *pblock;
LogPrint(BCLog::NET, "received block %s peer=%d\n", pblock->GetHash().ToString(), pfrom->GetId());
bool forceProcessing = false;
const uint256 hash(pblock->GetHash());
{
LOCK(cs_main);
// Also always process if we requested the block explicitly, as we may
// need it even though it is not a candidate for a new best tip.
forceProcessing |= MarkBlockAsReceived(hash);
// mapBlockSource is only used for sending reject messages and DoS scores,
// so the race between here and cs_main in ProcessNewBlock is fine.
mapBlockSource.emplace(hash, std::make_pair(pfrom->GetId(), true));
}
bool fNewBlock = false;
ProcessNewBlock(chainparams, pblock, forceProcessing, &fNewBlock);
if (fNewBlock) {
pfrom->nLastBlockTime = GetTime();
} else {
LOCK(cs_main);
mapBlockSource.erase(pblock->GetHash());
}
}
else if (strCommand == NetMsgType::GETADDR)
{
// This asymmetric behavior for inbound and outbound connections was introduced
// to prevent a fingerprinting attack: an attacker can send specific fake addresses
// to users' AddrMan and later request them by sending getaddr messages.
// Making nodes which are behind NAT and can only make outgoing connections ignore
// the getaddr message mitigates the attack.
if (!pfrom->fInbound) {
LogPrint(BCLog::NET, "Ignoring \"getaddr\" from outbound connection. peer=%d\n", pfrom->GetId());
return true;
}
// Only send one GetAddr response per connection to reduce resource waste
// and discourage addr stamping of INV announcements.
if (pfrom->fSentAddr) {
LogPrint(BCLog::NET, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->GetId());
return true;
}
pfrom->fSentAddr = true;
pfrom->vAddrToSend.clear();
std::vector<CAddress> vAddr = connman->GetAddresses();
FastRandomContext insecure_rand;
for (const CAddress &addr : vAddr)
pfrom->PushAddress(addr, insecure_rand);
}
else if (strCommand == NetMsgType::MEMPOOL)
{
if (!(pfrom->GetLocalServices() & NODE_BLOOM) && !pfrom->fWhitelisted)
{
LogPrint(BCLog::NET, "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom->GetId());
pfrom->fDisconnect = true;
return true;
}
if (connman->OutboundTargetReached(false) && !pfrom->fWhitelisted)
{
LogPrint(BCLog::NET, "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom->GetId());
pfrom->fDisconnect = true;
return true;
}
LOCK(pfrom->cs_inventory);
pfrom->fSendMempool = true;
}
else if (strCommand == NetMsgType::PING)
{
if (pfrom->nVersion > BIP0031_VERSION)
{
uint64_t nonce = 0;
vRecv >> nonce;
// Echo the message back with the nonce. This allows for two useful features:
//
// 1) A remote node can quickly check if the connection is operational
// 2) Remote nodes can measure the latency of the network thread. If this node
// is overloaded it won't respond to pings quickly and the remote node can
// avoid sending us more work, like chain download requests.
//
// The nonce stops the remote getting confused between different pings: without
// it, if the remote node sends a ping once per second and this node takes 5
// seconds to respond to each, the 5th ping the remote sends would appear to
// return very quickly.
connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::PONG, nonce));
}
}
else if (strCommand == NetMsgType::PONG)
{
int64_t pingUsecEnd = nTimeReceived;
uint64_t nonce = 0;
size_t nAvail = vRecv.in_avail();
bool bPingFinished = false;
std::string sProblem;
if (nAvail >= sizeof(nonce)) {
vRecv >> nonce;
// Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
if (pfrom->nPingNonceSent != 0) {
if (nonce == pfrom->nPingNonceSent) {
// Matching pong received, this ping is no longer outstanding
bPingFinished = true;
int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
if (pingUsecTime > 0) {
// Successful ping time measurement, replace previous
pfrom->nPingUsecTime = pingUsecTime;
pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime.load(), pingUsecTime);
} else {
// This should never happen
sProblem = "Timing mishap";
}
} else {
// Nonce mismatches are normal when pings are overlapping
sProblem = "Nonce mismatch";
if (nonce == 0) {
// This is most likely a bug in another implementation somewhere; cancel this ping
bPingFinished = true;
sProblem = "Nonce zero";
}
}
} else {
sProblem = "Unsolicited pong without ping";
}
} else {
// This is most likely a bug in another implementation somewhere; cancel this ping
bPingFinished = true;
sProblem = "Short payload";
}
if (!(sProblem.empty())) {
LogPrint(BCLog::NET, "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
pfrom->GetId(),
sProblem,
pfrom->nPingNonceSent,
nonce,
nAvail);
}
if (bPingFinished) {
pfrom->nPingNonceSent = 0;
}
}
else if (strCommand == NetMsgType::FILTERLOAD)
{
CBloomFilter filter;
vRecv >> filter;
if (!filter.IsWithinSizeConstraints())
{
// There is no excuse for sending a too-large filter
LOCK(cs_main);
Misbehaving(pfrom->GetId(), 100);
}
else
{
LOCK(pfrom->cs_filter);
pfrom->pfilter.reset(new CBloomFilter(filter));
pfrom->pfilter->UpdateEmptyFull();
pfrom->fRelayTxes = true;
}
}
else if (strCommand == NetMsgType::FILTERADD)
{
std::vector<unsigned char> vData;
vRecv >> vData;
// Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
// and thus, the maximum size any matched object can have) in a filteradd message
bool bad = false;
if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
bad = true;
} else {
LOCK(pfrom->cs_filter);
if (pfrom->pfilter) {
pfrom->pfilter->insert(vData);
} else {
bad = true;
}
}
if (bad) {
LOCK(cs_main);
Misbehaving(pfrom->GetId(), 100);
}
}
else if (strCommand == NetMsgType::FILTERCLEAR)
{
LOCK(pfrom->cs_filter);
if (pfrom->GetLocalServices() & NODE_BLOOM) {
pfrom->pfilter.reset(new CBloomFilter());
}
pfrom->fRelayTxes = true;
}
else if (strCommand == NetMsgType::FEEFILTER) {
CAmount newFeeFilter = 0;
vRecv >> newFeeFilter;
if (MoneyRange(newFeeFilter)) {
{
LOCK(pfrom->cs_feeFilter);
pfrom->minFeeFilter = newFeeFilter;
}
LogPrint(BCLog::NET, "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter).ToString(), pfrom->GetId());
}
}
else if (strCommand == NetMsgType::NOTFOUND) {
// We do not care about the NOTFOUND message, but logging an Unknown Command
// message would be undesirable as we transmit it ourselves.
}
else {
// Ignore unknown commands for extensibility
LogPrint(BCLog::NET, "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->GetId());
}
return true;
}
static bool SendRejectsAndCheckIfBanned(CNode* pnode, CConnman* connman)
{
AssertLockHeld(cs_main);
CNodeState &state = *State(pnode->GetId());
if (g_enable_bip61) {
for (const CBlockReject& reject : state.rejects) {
connman->PushMessage(pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, std::string(NetMsgType::BLOCK), reject.chRejectCode, reject.strRejectReason, reject.hashBlock));
}
}
state.rejects.clear();
if (state.fShouldBan) {
state.fShouldBan = false;
if (pnode->fWhitelisted)
LogPrintf("Warning: not punishing whitelisted peer %s!\n", pnode->addr.ToString());
else if (pnode->m_manual_connection)
LogPrintf("Warning: not punishing manually-connected peer %s!\n", pnode->addr.ToString());
else {
pnode->fDisconnect = true;
if (pnode->addr.IsLocal())
LogPrintf("Warning: not banning local peer %s!\n", pnode->addr.ToString());
else
{
connman->Ban(pnode->addr, BanReasonNodeMisbehaving);
}
}
return true;
}
return false;
}
bool PeerLogicValidation::ProcessMessages(CNode* pfrom, std::atomic<bool>& interruptMsgProc)
{
const CChainParams& chainparams = Params();
//
// Message format
// (4) message start
// (12) command
// (4) size
// (4) checksum
// (x) data
//
bool fMoreWork = false;
if (!pfrom->vRecvGetData.empty())
ProcessGetData(pfrom, chainparams, connman, interruptMsgProc);
if (pfrom->fDisconnect)
return false;
// this maintains the order of responses
if (!pfrom->vRecvGetData.empty()) return true;
// Don't bother if send buffer is too full to respond anyway
if (pfrom->fPauseSend)
return false;
std::list<CNetMessage> msgs;
{
LOCK(pfrom->cs_vProcessMsg);
if (pfrom->vProcessMsg.empty())
return false;
// Just take one message
msgs.splice(msgs.begin(), pfrom->vProcessMsg, pfrom->vProcessMsg.begin());
pfrom->nProcessQueueSize -= msgs.front().vRecv.size() + CMessageHeader::HEADER_SIZE;
pfrom->fPauseRecv = pfrom->nProcessQueueSize > connman->GetReceiveFloodSize();
fMoreWork = !pfrom->vProcessMsg.empty();
}
CNetMessage& msg(msgs.front());
msg.SetVersion(pfrom->GetRecvVersion());
// Scan for message start
if (memcmp(msg.hdr.pchMessageStart, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE) != 0) {
LogPrint(BCLog::NET, "PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->GetId());
pfrom->fDisconnect = true;
return false;
}
// Read header
CMessageHeader& hdr = msg.hdr;
if (!hdr.IsValid(chainparams.MessageStart()))
{
LogPrint(BCLog::NET, "PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->GetId());
return fMoreWork;
}
std::string strCommand = hdr.GetCommand();
// Message size
unsigned int nMessageSize = hdr.nMessageSize;
// Checksum
CDataStream& vRecv = msg.vRecv;
const uint256& hash = msg.GetMessageHash();
if (memcmp(hash.begin(), hdr.pchChecksum, CMessageHeader::CHECKSUM_SIZE) != 0)
{
LogPrint(BCLog::NET, "%s(%s, %u bytes): CHECKSUM ERROR expected %s was %s\n", __func__,
SanitizeString(strCommand), nMessageSize,
HexStr(hash.begin(), hash.begin()+CMessageHeader::CHECKSUM_SIZE),
HexStr(hdr.pchChecksum, hdr.pchChecksum+CMessageHeader::CHECKSUM_SIZE));
return fMoreWork;
}
// Process message
bool fRet = false;
try
{
fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime, chainparams, connman, interruptMsgProc);
if (interruptMsgProc)
return false;
if (!pfrom->vRecvGetData.empty())
fMoreWork = true;
}
catch (const std::ios_base::failure& e)
{
if (g_enable_bip61) {
connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_MALFORMED, std::string("error parsing message")));
}
if (strstr(e.what(), "end of data"))
{
// Allow exceptions from under-length message on vRecv
LogPrint(BCLog::NET, "%s(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than its stated length\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
}
else if (strstr(e.what(), "size too large"))
{
// Allow exceptions from over-long size
LogPrint(BCLog::NET, "%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
}
else if (strstr(e.what(), "non-canonical ReadCompactSize()"))
{
// Allow exceptions from non-canonical encoding
LogPrint(BCLog::NET, "%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
}
else
{
PrintExceptionContinue(&e, "ProcessMessages()");
}
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "ProcessMessages()");
} catch (...) {
PrintExceptionContinue(nullptr, "ProcessMessages()");
}
if (!fRet) {
LogPrint(BCLog::NET, "%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->GetId());
}
LOCK(cs_main);
SendRejectsAndCheckIfBanned(pfrom, connman);
return fMoreWork;
}
void PeerLogicValidation::ConsiderEviction(CNode *pto, int64_t time_in_seconds)
{
AssertLockHeld(cs_main);
CNodeState &state = *State(pto->GetId());
const CNetMsgMaker msgMaker(pto->GetSendVersion());
if (!state.m_chain_sync.m_protect && IsOutboundDisconnectionCandidate(pto) && state.fSyncStarted) {
// This is an outbound peer subject to disconnection if they don't
// announce a block with as much work as the current tip within
// CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds (note: if
// their chain has more work than ours, we should sync to it,
// unless it's invalid, in which case we should find that out and
// disconnect from them elsewhere).
if (state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= chainActive.Tip()->nChainWork) {
if (state.m_chain_sync.m_timeout != 0) {
state.m_chain_sync.m_timeout = 0;
state.m_chain_sync.m_work_header = nullptr;
state.m_chain_sync.m_sent_getheaders = false;
}
} else if (state.m_chain_sync.m_timeout == 0 || (state.m_chain_sync.m_work_header != nullptr && state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= state.m_chain_sync.m_work_header->nChainWork)) {
// Our best block known by this peer is behind our tip, and we're either noticing
// that for the first time, OR this peer was able to catch up to some earlier point
// where we checked against our tip.
// Either way, set a new timeout based on current tip.
state.m_chain_sync.m_timeout = time_in_seconds + CHAIN_SYNC_TIMEOUT;
state.m_chain_sync.m_work_header = chainActive.Tip();
state.m_chain_sync.m_sent_getheaders = false;
} else if (state.m_chain_sync.m_timeout > 0 && time_in_seconds > state.m_chain_sync.m_timeout) {
// No evidence yet that our peer has synced to a chain with work equal to that
// of our tip, when we first detected it was behind. Send a single getheaders
// message to give the peer a chance to update us.
if (state.m_chain_sync.m_sent_getheaders) {
// They've run out of time to catch up!
LogPrintf("Disconnecting outbound peer %d for old chain, best known block = %s\n", pto->GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>");
pto->fDisconnect = true;
} else {
assert(state.m_chain_sync.m_work_header);
LogPrint(BCLog::NET, "sending getheaders to outbound peer=%d to verify chain work (current best known block:%s, benchmark blockhash: %s)\n", pto->GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>", state.m_chain_sync.m_work_header->GetBlockHash().ToString());
connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(state.m_chain_sync.m_work_header->pprev), uint256()));
state.m_chain_sync.m_sent_getheaders = true;
constexpr int64_t HEADERS_RESPONSE_TIME = 120; // 2 minutes
// Bump the timeout to allow a response, which could clear the timeout
// (if the response shows the peer has synced), reset the timeout (if
// the peer syncs to the required work but not to our tip), or result
// in disconnect (if we advance to the timeout and pindexBestKnownBlock
// has not sufficiently progressed)
state.m_chain_sync.m_timeout = time_in_seconds + HEADERS_RESPONSE_TIME;
}
}
}
}
void PeerLogicValidation::EvictExtraOutboundPeers(int64_t time_in_seconds)
{
// Check whether we have too many outbound peers
int extra_peers = connman->GetExtraOutboundCount();
if (extra_peers > 0) {
// If we have more outbound peers than we target, disconnect one.
// Pick the outbound peer that least recently announced
// us a new block, with ties broken by choosing the more recent
// connection (higher node id)
NodeId worst_peer = -1;
int64_t oldest_block_announcement = std::numeric_limits<int64_t>::max();
LOCK(cs_main);
connman->ForEachNode([&](CNode* pnode) {
// Ignore non-outbound peers, or nodes marked for disconnect already
if (!IsOutboundDisconnectionCandidate(pnode) || pnode->fDisconnect) return;
CNodeState *state = State(pnode->GetId());
if (state == nullptr) return; // shouldn't be possible, but just in case
// Don't evict our protected peers
if (state->m_chain_sync.m_protect) return;
if (state->m_last_block_announcement < oldest_block_announcement || (state->m_last_block_announcement == oldest_block_announcement && pnode->GetId() > worst_peer)) {
worst_peer = pnode->GetId();
oldest_block_announcement = state->m_last_block_announcement;
}
});
if (worst_peer != -1) {
bool disconnected = connman->ForNode(worst_peer, [&](CNode *pnode) {
// Only disconnect a peer that has been connected to us for
// some reasonable fraction of our check-frequency, to give
// it time for new information to have arrived.
// Also don't disconnect any peer we're trying to download a
// block from.
CNodeState &state = *State(pnode->GetId());
if (time_in_seconds - pnode->nTimeConnected > MINIMUM_CONNECT_TIME && state.nBlocksInFlight == 0) {
LogPrint(BCLog::NET, "disconnecting extra outbound peer=%d (last block announcement received at time %d)\n", pnode->GetId(), oldest_block_announcement);
pnode->fDisconnect = true;
return true;
} else {
LogPrint(BCLog::NET, "keeping outbound peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n", pnode->GetId(), pnode->nTimeConnected, state.nBlocksInFlight);
return false;
}
});
if (disconnected) {
// If we disconnected an extra peer, that means we successfully
// connected to at least one peer after the last time we
// detected a stale tip. Don't try any more extra peers until
// we next detect a stale tip, to limit the load we put on the
// network from these extra connections.
connman->SetTryNewOutboundPeer(false);
}
}
}
}
void PeerLogicValidation::CheckForStaleTipAndEvictPeers(const Consensus::Params &consensusParams)
{
if (connman == nullptr) return;
int64_t time_in_seconds = GetTime();
EvictExtraOutboundPeers(time_in_seconds);
if (time_in_seconds > m_stale_tip_check_time) {
LOCK(cs_main);
// Check whether our tip is stale, and if so, allow using an extra
// outbound peer
if (TipMayBeStale(consensusParams)) {
LogPrintf("Potential stale tip detected, will try using extra outbound peer (last tip update: %d seconds ago)\n", time_in_seconds - g_last_tip_update);
connman->SetTryNewOutboundPeer(true);
} else if (connman->GetTryNewOutboundPeer()) {
connman->SetTryNewOutboundPeer(false);
}
m_stale_tip_check_time = time_in_seconds + STALE_CHECK_INTERVAL;
}
}
class CompareInvMempoolOrder
{
CTxMemPool *mp;
public:
explicit CompareInvMempoolOrder(CTxMemPool *_mempool)
{
mp = _mempool;
}
bool operator()(std::set<uint256>::iterator a, std::set<uint256>::iterator b)
{
/* As std::make_heap produces a max-heap, we want the entries with the
* fewest ancestors/highest fee to sort later. */
return mp->CompareDepthAndScore(*b, *a);
}
};
bool PeerLogicValidation::SendMessages(CNode* pto, std::atomic<bool>& interruptMsgProc)
{
const Consensus::Params& consensusParams = Params().GetConsensus();
{
// Don't send anything until the version handshake is complete
if (!pto->fSuccessfullyConnected || pto->fDisconnect)
return true;
// If we get here, the outgoing message serialization version is set and can't change.
const CNetMsgMaker msgMaker(pto->GetSendVersion());
//
// Message: ping
//
bool pingSend = false;
if (pto->fPingQueued) {
// RPC ping request by user
pingSend = true;
}
if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
// Ping automatically sent as a latency probe & keepalive.
pingSend = true;
}
if (pingSend) {
uint64_t nonce = 0;
while (nonce == 0) {
GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
}
pto->fPingQueued = false;
pto->nPingUsecStart = GetTimeMicros();
if (pto->nVersion > BIP0031_VERSION) {
pto->nPingNonceSent = nonce;
connman->PushMessage(pto, msgMaker.Make(NetMsgType::PING, nonce));
} else {
// Peer is too old to support ping command with nonce, pong will never arrive.
pto->nPingNonceSent = 0;
connman->PushMessage(pto, msgMaker.Make(NetMsgType::PING));
}
}
TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
if (!lockMain)
return true;
if (SendRejectsAndCheckIfBanned(pto, connman))
return true;
CNodeState &state = *State(pto->GetId());
// Address refresh broadcast
int64_t nNow = GetTimeMicros();
if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) {
AdvertiseLocal(pto);
pto->nNextLocalAddrSend = PoissonNextSend(nNow, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL);
}
//
// Message: addr
//
if (pto->nNextAddrSend < nNow) {
pto->nNextAddrSend = PoissonNextSend(nNow, AVG_ADDRESS_BROADCAST_INTERVAL);
std::vector<CAddress> vAddr;
vAddr.reserve(pto->vAddrToSend.size());
for (const CAddress& addr : pto->vAddrToSend)
{
if (!pto->addrKnown.contains(addr.GetKey()))
{
pto->addrKnown.insert(addr.GetKey());
vAddr.push_back(addr);
// receiver rejects addr messages larger than 1000
if (vAddr.size() >= 1000)
{
connman->PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr));
vAddr.clear();
}
}
}
pto->vAddrToSend.clear();
if (!vAddr.empty())
connman->PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr));
// we only send the big addr message once
if (pto->vAddrToSend.capacity() > 40)
pto->vAddrToSend.shrink_to_fit();
}
// Start block sync
if (pindexBestHeader == nullptr)
pindexBestHeader = chainActive.Tip();
bool fFetch = state.fPreferredDownload || (nPreferredDownload == 0 && !pto->fClient && !pto->fOneShot); // Download if this is a nice peer, or we have no nice peers and this one might do.
if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
// Only actively request headers from a single peer, unless we're close to today.
if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
state.fSyncStarted = true;
state.nHeadersSyncTimeout = GetTimeMicros() + HEADERS_DOWNLOAD_TIMEOUT_BASE + HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER * (GetAdjustedTime() - pindexBestHeader->GetBlockTime())/(consensusParams.nPowTargetSpacing);
nSyncStarted++;
const CBlockIndex *pindexStart = pindexBestHeader;
/* If possible, start at the block preceding the currently
best known header. This ensures that we always get a
non-empty list of headers back as long as the peer
is up-to-date. With a non-empty response, we can initialise
the peer's known best block. This wouldn't be possible
if we requested starting at pindexBestHeader and
got back an empty response. */
if (pindexStart->pprev)
pindexStart = pindexStart->pprev;
LogPrint(BCLog::NET, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->GetId(), pto->nStartingHeight);
connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexStart), uint256()));
}
}
// Resend wallet transactions that haven't gotten in a block yet
// Except during reindex, importing and IBD, when old wallet
// transactions become unconfirmed and spams other nodes.
if (!fReindex && !fImporting && !IsInitialBlockDownload())
{
GetMainSignals().Broadcast(nTimeBestReceived, connman);
}
//
// Try sending block announcements via headers
//
{
// If we have less than MAX_BLOCKS_TO_ANNOUNCE in our
// list of block hashes we're relaying, and our peer wants
// headers announcements, then find the first header
// not yet known to our peer but would connect, and send.
// If no header would connect, or if we have too many
// blocks, or if the peer doesn't want headers, just
// add all to the inv queue.
LOCK(pto->cs_inventory);
std::vector<CBlock> vHeaders;
bool fRevertToInv = ((!state.fPreferHeaders &&
(!state.fPreferHeaderAndIDs || pto->vBlockHashesToAnnounce.size() > 1)) ||
pto->vBlockHashesToAnnounce.size() > MAX_BLOCKS_TO_ANNOUNCE);
const CBlockIndex *pBestIndex = nullptr; // last header queued for delivery
ProcessBlockAvailability(pto->GetId()); // ensure pindexBestKnownBlock is up-to-date
if (!fRevertToInv) {
bool fFoundStartingHeader = false;
// Try to find first header that our peer doesn't have, and
// then send all headers past that one. If we come across any
// headers that aren't on chainActive, give up.
for (const uint256 &hash : pto->vBlockHashesToAnnounce) {
const CBlockIndex* pindex = LookupBlockIndex(hash);
assert(pindex);
if (chainActive[pindex->nHeight] != pindex) {
// Bail out if we reorged away from this block
fRevertToInv = true;
break;
}
if (pBestIndex != nullptr && pindex->pprev != pBestIndex) {
// This means that the list of blocks to announce don't
// connect to each other.
// This shouldn't really be possible to hit during
// regular operation (because reorgs should take us to
// a chain that has some block not on the prior chain,
// which should be caught by the prior check), but one
// way this could happen is by using invalidateblock /
// reconsiderblock repeatedly on the tip, causing it to
// be added multiple times to vBlockHashesToAnnounce.
// Robustly deal with this rare situation by reverting
// to an inv.
fRevertToInv = true;
break;
}
pBestIndex = pindex;
if (fFoundStartingHeader) {
// add this to the headers message
vHeaders.push_back(pindex->GetBlockHeader());
} else if (PeerHasHeader(&state, pindex)) {
continue; // keep looking for the first new block
} else if (pindex->pprev == nullptr || PeerHasHeader(&state, pindex->pprev)) {
// Peer doesn't have this header but they do have the prior one.
// Start sending headers.
fFoundStartingHeader = true;
vHeaders.push_back(pindex->GetBlockHeader());
} else {
// Peer doesn't have this header or the prior one -- nothing will
// connect, so bail out.
fRevertToInv = true;
break;
}
}
}
if (!fRevertToInv && !vHeaders.empty()) {
if (vHeaders.size() == 1 && state.fPreferHeaderAndIDs) {
// We only send up to 1 block as header-and-ids, as otherwise
// probably means we're doing an initial-ish-sync or they're slow
LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", __func__,
vHeaders.front().GetHash().ToString(), pto->GetId());
int nSendFlags = state.fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
bool fGotBlockFromCache = false;
{
LOCK(cs_most_recent_block);
if (most_recent_block_hash == pBestIndex->GetBlockHash()) {
if (state.fWantsCmpctWitness || !fWitnessesPresentInMostRecentCompactBlock)
connman->PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *most_recent_compact_block));
else {
CBlockHeaderAndShortTxIDs cmpctblock(*most_recent_block, state.fWantsCmpctWitness);
connman->PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
}
fGotBlockFromCache = true;
}
}
if (!fGotBlockFromCache) {
CBlock block;
bool ret = ReadBlockFromDisk(block, pBestIndex, consensusParams);
assert(ret);
CBlockHeaderAndShortTxIDs cmpctblock(block, state.fWantsCmpctWitness);
connman->PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
}
state.pindexBestHeaderSent = pBestIndex;
} else if (state.fPreferHeaders) {
if (vHeaders.size() > 1) {
LogPrint(BCLog::NET, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__,
vHeaders.size(),
vHeaders.front().GetHash().ToString(),
vHeaders.back().GetHash().ToString(), pto->GetId());
} else {
LogPrint(BCLog::NET, "%s: sending header %s to peer=%d\n", __func__,
vHeaders.front().GetHash().ToString(), pto->GetId());
}
connman->PushMessage(pto, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
state.pindexBestHeaderSent = pBestIndex;
} else
fRevertToInv = true;
}
if (fRevertToInv) {
// If falling back to using an inv, just try to inv the tip.
// The last entry in vBlockHashesToAnnounce was our tip at some point
// in the past.
if (!pto->vBlockHashesToAnnounce.empty()) {
const uint256 &hashToAnnounce = pto->vBlockHashesToAnnounce.back();
const CBlockIndex* pindex = LookupBlockIndex(hashToAnnounce);
assert(pindex);
// Warn if we're announcing a block that is not on the main chain.
// This should be very rare and could be optimized out.
// Just log for now.
if (chainActive[pindex->nHeight] != pindex) {
LogPrint(BCLog::NET, "Announcing block %s not on main chain (tip=%s)\n",
hashToAnnounce.ToString(), chainActive.Tip()->GetBlockHash().ToString());
}
// If the peer's chain has this block, don't inv it back.
if (!PeerHasHeader(&state, pindex)) {
pto->PushInventory(CInv(MSG_BLOCK, hashToAnnounce));
LogPrint(BCLog::NET, "%s: sending inv peer=%d hash=%s\n", __func__,
pto->GetId(), hashToAnnounce.ToString());
}
}
}
pto->vBlockHashesToAnnounce.clear();
}
//
// Message: inventory
//
std::vector<CInv> vInv;
{
LOCK(pto->cs_inventory);
vInv.reserve(std::max<size_t>(pto->vInventoryBlockToSend.size(), INVENTORY_BROADCAST_MAX));
// Add blocks
for (const uint256& hash : pto->vInventoryBlockToSend) {
vInv.push_back(CInv(MSG_BLOCK, hash));
if (vInv.size() == MAX_INV_SZ) {
connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
vInv.clear();
}
}
pto->vInventoryBlockToSend.clear();
// Check whether periodic sends should happen
bool fSendTrickle = pto->fWhitelisted;
if (pto->nNextInvSend < nNow) {
fSendTrickle = true;
// Use half the delay for outbound peers, as there is less privacy concern for them.
pto->nNextInvSend = PoissonNextSend(nNow, INVENTORY_BROADCAST_INTERVAL >> !pto->fInbound);
}
// Time to send but the peer has requested we not relay transactions.
if (fSendTrickle) {
LOCK(pto->cs_filter);
if (!pto->fRelayTxes) pto->setInventoryTxToSend.clear();
}
// Respond to BIP35 mempool requests
if (fSendTrickle && pto->fSendMempool) {
auto vtxinfo = mempool.infoAll();
pto->fSendMempool = false;
CAmount filterrate = 0;
{
LOCK(pto->cs_feeFilter);
filterrate = pto->minFeeFilter;
}
LOCK(pto->cs_filter);
for (const auto& txinfo : vtxinfo) {
const uint256& hash = txinfo.tx->GetHash();
CInv inv(MSG_TX, hash);
pto->setInventoryTxToSend.erase(hash);
if (filterrate) {
if (txinfo.feeRate.GetFeePerK() < filterrate)
continue;
}
if (pto->pfilter) {
if (!pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
}
pto->filterInventoryKnown.insert(hash);
vInv.push_back(inv);
if (vInv.size() == MAX_INV_SZ) {
connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
vInv.clear();
}
}
pto->timeLastMempoolReq = GetTime();
}
// Determine transactions to relay
if (fSendTrickle) {
// Produce a vector with all candidates for sending
std::vector<std::set<uint256>::iterator> vInvTx;
vInvTx.reserve(pto->setInventoryTxToSend.size());
for (std::set<uint256>::iterator it = pto->setInventoryTxToSend.begin(); it != pto->setInventoryTxToSend.end(); it++) {
vInvTx.push_back(it);
}
CAmount filterrate = 0;
{
LOCK(pto->cs_feeFilter);
filterrate = pto->minFeeFilter;
}
// Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
// A heap is used so that not all items need sorting if only a few are being sent.
CompareInvMempoolOrder compareInvMempoolOrder(&mempool);
std::make_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
// No reason to drain out at many times the network's capacity,
// especially since we have many peers and some will draw much shorter delays.
unsigned int nRelayedTransactions = 0;
LOCK(pto->cs_filter);
while (!vInvTx.empty() && nRelayedTransactions < INVENTORY_BROADCAST_MAX) {
// Fetch the top element from the heap
std::pop_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
std::set<uint256>::iterator it = vInvTx.back();
vInvTx.pop_back();
uint256 hash = *it;
// Remove it from the to-be-sent set
pto->setInventoryTxToSend.erase(it);
// Check if not in the filter already
if (pto->filterInventoryKnown.contains(hash)) {
continue;
}
// Not in the mempool anymore? don't bother sending it.
auto txinfo = mempool.info(hash);
if (!txinfo.tx) {
continue;
}
if (filterrate && txinfo.feeRate.GetFeePerK() < filterrate) {
continue;
}
if (pto->pfilter && !pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
// Send
vInv.push_back(CInv(MSG_TX, hash));
nRelayedTransactions++;
{
// Expire old relay messages
while (!vRelayExpiration.empty() && vRelayExpiration.front().first < nNow)
{
mapRelay.erase(vRelayExpiration.front().second);
vRelayExpiration.pop_front();
}
auto ret = mapRelay.insert(std::make_pair(hash, std::move(txinfo.tx)));
if (ret.second) {
vRelayExpiration.push_back(std::make_pair(nNow + 15 * 60 * 1000000, ret.first));
}
}
if (vInv.size() == MAX_INV_SZ) {
connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
vInv.clear();
}
pto->filterInventoryKnown.insert(hash);
}
}
}
if (!vInv.empty())
connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
// Detect whether we're stalling
nNow = GetTimeMicros();
if (state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
// Stalling only triggers when the block download window cannot move. During normal steady state,
// the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
// should only happen during initial block download.
LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->GetId());
pto->fDisconnect = true;
return true;
}
// In case there is a block that has been in flight from this peer for 2 + 0.5 * N times the block interval
// (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
// We compensate for other peers to prevent killing off peers due to our own downstream link
// being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
// to unreasonably increase our timeout.
if (state.vBlocksInFlight.size() > 0) {
QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
int nOtherPeersWithValidatedDownloads = nPeersWithValidatedDownloads - (state.nBlocksInFlightValidHeaders > 0);
if (nNow > state.nDownloadingSince + consensusParams.nPowTargetSpacing * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) {
LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->GetId());
pto->fDisconnect = true;
return true;
}
}
// Check for headers sync timeouts
if (state.fSyncStarted && state.nHeadersSyncTimeout < std::numeric_limits<int64_t>::max()) {
// Detect whether this is a stalling initial-headers-sync peer
if (pindexBestHeader->GetBlockTime() <= GetAdjustedTime() - 24*60*60) {
if (nNow > state.nHeadersSyncTimeout && nSyncStarted == 1 && (nPreferredDownload - state.fPreferredDownload >= 1)) {
// Disconnect a (non-whitelisted) peer if it is our only sync peer,
// and we have others we could be using instead.
// Note: If all our peers are inbound, then we won't
// disconnect our sync peer for stalling; we have bigger
// problems if we can't get any outbound peers.
if (!pto->fWhitelisted) {
LogPrintf("Timeout downloading headers from peer=%d, disconnecting\n", pto->GetId());
pto->fDisconnect = true;
return true;
} else {
LogPrintf("Timeout downloading headers from whitelisted peer=%d, not disconnecting\n", pto->GetId());
// Reset the headers sync state so that we have a
// chance to try downloading from a different peer.
// Note: this will also result in at least one more
// getheaders message to be sent to
// this peer (eventually).
state.fSyncStarted = false;
nSyncStarted--;
state.nHeadersSyncTimeout = 0;
}
}
} else {
// After we've caught up once, reset the timeout so we can't trigger
// disconnect later.
state.nHeadersSyncTimeout = std::numeric_limits<int64_t>::max();
}
}
// Check that outbound peers have reasonable chains
// GetTime() is used by this anti-DoS logic so we can test this using mocktime
ConsiderEviction(pto, GetTime());
//
// Message: getdata (blocks)
//
std::vector<CInv> vGetData;
if (!pto->fClient && ((fFetch && !pto->m_limited_node) || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
std::vector<const CBlockIndex*> vToDownload;
NodeId staller = -1;
FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller, consensusParams);
for (const CBlockIndex *pindex : vToDownload) {
uint32_t nFetchFlags = GetFetchFlags(pto);
vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex);
LogPrint(BCLog::NET, "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
pindex->nHeight, pto->GetId());
}
if (state.nBlocksInFlight == 0 && staller != -1) {
if (State(staller)->nStallingSince == 0) {
State(staller)->nStallingSince = nNow;
LogPrint(BCLog::NET, "Stall started peer=%d\n", staller);
}
}
}
//
// Message: getdata (non-blocks)
//
while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
{
const CInv& inv = (*pto->mapAskFor.begin()).second;
if (!AlreadyHave(inv))
{
LogPrint(BCLog::NET, "Requesting %s peer=%d\n", inv.ToString(), pto->GetId());
vGetData.push_back(inv);
if (vGetData.size() >= 1000)
{
connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
vGetData.clear();
}
} else {
//If we're not going to ask, don't expect a response.
pto->setAskFor.erase(inv.hash);
}
pto->mapAskFor.erase(pto->mapAskFor.begin());
}
if (!vGetData.empty())
connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
//
// Message: feefilter
//
// We don't want white listed peers to filter txs to us if we have -whitelistforcerelay
if (pto->nVersion >= FEEFILTER_VERSION && gArgs.GetBoolArg("-feefilter", DEFAULT_FEEFILTER) &&
!(pto->fWhitelisted && gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY))) {
CAmount currentFilter = mempool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK();
int64_t timeNow = GetTimeMicros();
if (timeNow > pto->nextSendTimeFeeFilter) {
static CFeeRate default_feerate(DEFAULT_MIN_RELAY_TX_FEE);
static FeeFilterRounder filterRounder(default_feerate);
CAmount filterToSend = filterRounder.round(currentFilter);
// We always have a fee filter of at least minRelayTxFee
filterToSend = std::max(filterToSend, ::minRelayTxFee.GetFeePerK());
if (filterToSend != pto->lastSentFeeFilter) {
connman->PushMessage(pto, msgMaker.Make(NetMsgType::FEEFILTER, filterToSend));
pto->lastSentFeeFilter = filterToSend;
}
pto->nextSendTimeFeeFilter = PoissonNextSend(timeNow, AVG_FEEFILTER_BROADCAST_INTERVAL);
}
// If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
// until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
else if (timeNow + MAX_FEEFILTER_CHANGE_DELAY * 1000000 < pto->nextSendTimeFeeFilter &&
(currentFilter < 3 * pto->lastSentFeeFilter / 4 || currentFilter > 4 * pto->lastSentFeeFilter / 3)) {
pto->nextSendTimeFeeFilter = timeNow + GetRandInt(MAX_FEEFILTER_CHANGE_DELAY) * 1000000;
}
}
}
return true;
}
class CNetProcessingCleanup
{
public:
CNetProcessingCleanup() {}
~CNetProcessingCleanup() {
// orphan transactions
mapOrphanTransactions.clear();
mapOrphanTransactionsByPrev.clear();
}
} instance_of_cnetprocessingcleanup;
|
/* SPDX-License-Identifier: MIT */
/**
@file ancillarydata_hdr_hlg.cpp
@brief Implements the AJAAncillaryData_HDR_HLG class.
@copyright (C) 2012-2021 AJA Video Systems, Inc.
**/
#include "ancillarydata_hdr_hlg.h"
#include <ios>
#include <iomanip>
using namespace std;
#define AJAAncillaryData_HDR_HLG_PayloadSize 0x1D
AJAAncillaryData_HDR_HLG::AJAAncillaryData_HDR_HLG ()
: AJAAncillaryData ()
{
Init();
}
AJAAncillaryData_HDR_HLG::AJAAncillaryData_HDR_HLG (const AJAAncillaryData_HDR_HLG & inClone)
: AJAAncillaryData ()
{
Init();
*this = inClone;
}
AJAAncillaryData_HDR_HLG::AJAAncillaryData_HDR_HLG (const AJAAncillaryData_HDR_HLG * pInClone)
: AJAAncillaryData ()
{
Init();
if (pInClone)
*this = *pInClone;
}
AJAAncillaryData_HDR_HLG::AJAAncillaryData_HDR_HLG (const AJAAncillaryData * pInData)
: AJAAncillaryData (pInData)
{
Init();
}
AJAAncillaryData_HDR_HLG::~AJAAncillaryData_HDR_HLG ()
{
}
void AJAAncillaryData_HDR_HLG::Init (void)
{
m_ancType = AJAAncillaryDataType_HDR_HLG;
m_coding = AJAAncillaryDataCoding_Digital;
m_DID = AJAAncillaryData_HDR_HLG_DID;
m_SID = AJAAncillaryData_HDR_HLG_SID;
m_location.SetDataLink(AJAAncillaryDataLink_A).SetDataChannel(AJAAncillaryDataChannel_Y).SetLineNumber(16).SetHorizontalOffset(AJAAncDataHorizOffset_AnyVanc);
uint8_t payload[29] = {0x08,0x03,0x00,0x0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
SetPayloadData(payload, 29);
}
void AJAAncillaryData_HDR_HLG::Clear (void)
{
AJAAncillaryData::Clear();
Init();
}
AJAAncillaryData_HDR_HLG & AJAAncillaryData_HDR_HLG::operator = (const AJAAncillaryData_HDR_HLG & rhs)
{
// Ignore self-assignment
if (this != &rhs)
{
// Copy the base class members
AJAAncillaryData::operator=(rhs);
}
return *this;
}
AJAStatus AJAAncillaryData_HDR_HLG::ParsePayloadData (void)
{
// The size is specific to Canon
if (GetDC() != AJAAncillaryData_HDR_HLG_PayloadSize)
{
// Load default values
Init();
m_rcvDataValid = false;
return AJA_STATUS_FAIL;
}
m_rcvDataValid = true;
return AJA_STATUS_SUCCESS;
}
AJAAncillaryDataType AJAAncillaryData_HDR_HLG::RecognizeThisAncillaryData (const AJAAncillaryData * pInAncData)
{
if (pInAncData->GetDataCoding() == AJAAncillaryDataCoding_Digital)
if (pInAncData->GetDID() == AJAAncillaryData_HDR_HLG_DID)
if (pInAncData->GetSID() == AJAAncillaryData_HDR_HLG_SID)
if (pInAncData->GetDC() == AJAAncillaryData_HDR_HLG_PayloadSize)
return AJAAncillaryDataType_HDR_HLG;
return AJAAncillaryDataType_Unknown;
}
ostream & AJAAncillaryData_HDR_HLG::Print (ostream & debugStream, const bool bShowDetail) const
{
AJAAncillaryData::Print (debugStream, bShowDetail);
debugStream << endl;
return debugStream;
}
|
// Copyright (c) 2011-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/guiutil.h>
#include <qt/utopiacoinaddressvalidator.h>
#include <qt/utopiacoinunits.h>
#include <qt/qvalidatedlineedit.h>
#include <qt/walletmodel.h>
#include <primitives/transaction.h>
#include <init.h>
#include <policy/policy.h>
#include <protocol.h>
#include <script/script.h>
#include <script/standard.h>
#include <util.h>
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <shellapi.h>
#include <shlobj.h>
#include <shlwapi.h>
#endif
#include <boost/scoped_array.hpp>
#include <QAbstractItemView>
#include <QApplication>
#include <QClipboard>
#include <QDateTime>
#include <QDesktopServices>
#include <QDesktopWidget>
#include <QDoubleValidator>
#include <QFileDialog>
#include <QFont>
#include <QLineEdit>
#include <QSettings>
#include <QTextDocument> // for Qt::mightBeRichText
#include <QThread>
#include <QMouseEvent>
#if QT_VERSION < 0x050000
#include <QUrl>
#else
#include <QUrlQuery>
#endif
#if QT_VERSION >= 0x50200
#include <QFontDatabase>
#endif
static fs::detail::utf8_codecvt_facet utf8;
#if defined(Q_OS_MAC)
extern double NSAppKitVersionNumber;
#if !defined(NSAppKitVersionNumber10_8)
#define NSAppKitVersionNumber10_8 1187
#endif
#if !defined(NSAppKitVersionNumber10_9)
#define NSAppKitVersionNumber10_9 1265
#endif
#endif
namespace GUIUtil {
QString dateTimeStr(const QDateTime &date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont fixedPitchFont()
{
#if QT_VERSION >= 0x50200
return QFontDatabase::systemFont(QFontDatabase::FixedFont);
#else
QFont font("Monospace");
#if QT_VERSION >= 0x040800
font.setStyleHint(QFont::Monospace);
#else
font.setStyleHint(QFont::TypeWriter);
#endif
return font;
#endif
}
// Just some dummy data to generate an convincing random-looking (but consistent) address
static const uint8_t dummydata[] = {0xeb,0x15,0x23,0x1d,0xfc,0xeb,0x60,0x92,0x58,0x86,0xb6,0x7d,0x06,0x52,0x99,0x92,0x59,0x15,0xae,0xb1,0x72,0xc0,0x66,0x47};
// Generate a dummy address with invalid CRC, starting with the network prefix.
static std::string DummyAddress(const CChainParams ¶ms)
{
std::vector<unsigned char> sourcedata = params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);
sourcedata.insert(sourcedata.end(), dummydata, dummydata + sizeof(dummydata));
for(int i=0; i<256; ++i) { // Try every trailing byte
std::string s = EncodeBase58(sourcedata.data(), sourcedata.data() + sourcedata.size());
if (!IsValidDestinationString(s)) {
return s;
}
sourcedata[sourcedata.size()-1] += 1;
}
return "";
}
void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent)
{
parent->setFocusProxy(widget);
widget->setFont(fixedPitchFont());
#if QT_VERSION >= 0x040700
// We don't want translators to use own addresses in translations
// and this is the only place, where this address is supplied.
widget->setPlaceholderText(QObject::tr("Enter a Utopiacoin address (e.g. %1)").arg(
QString::fromStdString(DummyAddress(Params()))));
#endif
widget->setValidator(new UtopiacoinAddressEntryValidator(parent));
widget->setCheckValidator(new UtopiacoinAddressCheckValidator(parent));
}
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
QDoubleValidator *amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}
bool parseUtopiacoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
// return if URI is not valid or is no utopiacoin: URI
if(!uri.isValid() || uri.scheme() != QString("utopiacoin"))
return false;
SendCoinsRecipient rv;
rv.address = uri.path();
// Trim any following forward slash which may have been added by the OS
if (rv.address.endsWith("/")) {
rv.address.truncate(rv.address.length() - 1);
}
rv.amount = 0;
#if QT_VERSION < 0x050000
QList<QPair<QString, QString> > items = uri.queryItems();
#else
QUrlQuery uriQuery(uri);
QList<QPair<QString, QString> > items = uriQuery.queryItems();
#endif
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
{
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-"))
{
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label")
{
rv.label = i->second;
fShouldReturnFalse = false;
}
if (i->first == "message")
{
rv.message = i->second;
fShouldReturnFalse = false;
}
else if (i->first == "amount")
{
if(!i->second.isEmpty())
{
if(!UtopiacoinUnits::parse(UtopiacoinUnits::UTC, i->second, &rv.amount))
{
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if(out)
{
*out = rv;
}
return true;
}
bool parseUtopiacoinURI(QString uri, SendCoinsRecipient *out)
{
// Convert utopiacoin:// to utopiacoin:
//
// Cannot handle this later, because utopiacoin:// will cause Qt to see the part after // as host,
// which will lower-case it (and thus invalidate the address).
if(uri.startsWith("utopiacoin://", Qt::CaseInsensitive))
{
uri.replace(0, 10, "utopiacoin:");
}
QUrl uriInstance(uri);
return parseUtopiacoinURI(uriInstance, out);
}
QString formatUtopiacoinURI(const SendCoinsRecipient &info)
{
QString ret = QString("utopiacoin:%1").arg(info.address);
int paramCount = 0;
if (info.amount)
{
ret += QString("?amount=%1").arg(UtopiacoinUnits::format(UtopiacoinUnits::UTC, info.amount, false, UtopiacoinUnits::separatorNever));
paramCount++;
}
if (!info.label.isEmpty())
{
QString lbl(QUrl::toPercentEncoding(info.label));
ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl);
paramCount++;
}
if (!info.message.isEmpty())
{
QString msg(QUrl::toPercentEncoding(info.message));
ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg);
paramCount++;
}
return ret;
}
bool isDust(const QString& address, const CAmount& amount)
{
CTxDestination dest = DecodeDestination(address.toStdString());
CScript script = GetScriptForDestination(dest);
CTxOut txOut(amount, script);
return IsDust(txOut, ::dustRelayFee);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
#if QT_VERSION < 0x050000
QString escaped = Qt::escape(str);
#else
QString escaped = str.toHtmlEscaped();
#endif
if(fMultiLine)
{
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty())
{
// Copy first item
setClipboard(selection.at(0).data(role).toString());
}
}
QList<QModelIndex> getEntryData(QAbstractItemView *view, int column)
{
if(!view || !view->selectionModel())
return QList<QModelIndex>();
return view->selectionModel()->selectedRows(column);
}
QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
#if QT_VERSION < 0x050000
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
#else
myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#endif
}
else
{
myDir = dir;
}
/* Directly convert path to native OS path separators */
QString result = QDir::toNativeSeparators(QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter));
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if(!result.isEmpty())
{
if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
{
/* No suffix specified, add selected suffix */
if(!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if(selectedSuffixOut)
{
*selectedSuffixOut = selectedSuffix;
}
return result;
}
QString getOpenFileName(QWidget *parent, const QString &caption, const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
#if QT_VERSION < 0x050000
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
#else
myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#endif
}
else
{
myDir = dir;
}
/* Directly convert path to native OS path separators */
QString result = QDir::toNativeSeparators(QFileDialog::getOpenFileName(parent, caption, myDir, filter, &selectedFilter));
if(selectedSuffixOut)
{
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if(QThread::currentThread() != qApp->thread())
{
return Qt::BlockingQueuedConnection;
}
else
{
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint &p, const QWidget *w)
{
QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p));
if (!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget *w)
{
return !(checkPoint(QPoint(0, 0), w)
&& checkPoint(QPoint(w->width() - 1, 0), w)
&& checkPoint(QPoint(0, w->height() - 1), w)
&& checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
&& checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
}
void openDebugLogfile()
{
fs::path pathDebug = GetDataDir() / "debug.log";
/* Open debug.log with the associated application */
if (fs::exists(pathDebug))
QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathDebug)));
}
bool openUtopiacoinConf()
{
boost::filesystem::path pathConfig = GetConfigFile(UTOPIACOIN_CONF_FILENAME);
/* Create the file */
boost::filesystem::ofstream configFile(pathConfig, std::ios_base::app);
if (!configFile.good())
return false;
configFile.close();
/* Open utopiacoin.conf with the associated application */
return QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathConfig)));
}
void SubstituteFonts(const QString& language)
{
#if defined(Q_OS_MAC)
// Background:
// OSX's default font changed in 10.9 and Qt is unable to find it with its
// usual fallback methods when building against the 10.7 sdk or lower.
// The 10.8 SDK added a function to let it find the correct fallback font.
// If this fallback is not properly loaded, some characters may fail to
// render correctly.
//
// The same thing happened with 10.10. .Helvetica Neue DeskInterface is now default.
//
// Solution: If building with the 10.7 SDK or lower and the user's platform
// is 10.9 or higher at runtime, substitute the correct font. This needs to
// happen before the QApplication is created.
#if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_8
if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_8)
{
if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_9)
/* On a 10.9 - 10.9.x system */
QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande");
else
{
/* 10.10 or later system */
if (language == "zh_CN" || language == "zh_TW" || language == "zh_HK") // traditional or simplified Chinese
QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Heiti SC");
else if (language == "ja") // Japanese
QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Songti SC");
else
QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Lucida Grande");
}
}
#endif
#endif
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int _size_threshold, QObject *parent) :
QObject(parent),
size_threshold(_size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
if(evt->type() == QEvent::ToolTipChange)
{
QWidget *widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt") && !Qt::mightBeRichText(tooltip))
{
// Envelop with <qt></qt> to make sure Qt detects this as rich text
// Escape the current message as HTML and replace \n by <br>
tooltip = "<qt>" + HtmlEscape(tooltip, true) + "</qt>";
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
void TableViewLastColumnResizingFixer::connectViewHeadersSignals()
{
connect(tableView->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(on_sectionResized(int,int,int)));
connect(tableView->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged()));
}
// We need to disconnect these while handling the resize events, otherwise we can enter infinite loops.
void TableViewLastColumnResizingFixer::disconnectViewHeadersSignals()
{
disconnect(tableView->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(on_sectionResized(int,int,int)));
disconnect(tableView->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged()));
}
// Setup the resize mode, handles compatibility for Qt5 and below as the method signatures changed.
// Refactored here for readability.
void TableViewLastColumnResizingFixer::setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode)
{
#if QT_VERSION < 0x050000
tableView->horizontalHeader()->setResizeMode(logicalIndex, resizeMode);
#else
tableView->horizontalHeader()->setSectionResizeMode(logicalIndex, resizeMode);
#endif
}
void TableViewLastColumnResizingFixer::resizeColumn(int nColumnIndex, int width)
{
tableView->setColumnWidth(nColumnIndex, width);
tableView->horizontalHeader()->resizeSection(nColumnIndex, width);
}
int TableViewLastColumnResizingFixer::getColumnsWidth()
{
int nColumnsWidthSum = 0;
for (int i = 0; i < columnCount; i++)
{
nColumnsWidthSum += tableView->horizontalHeader()->sectionSize(i);
}
return nColumnsWidthSum;
}
int TableViewLastColumnResizingFixer::getAvailableWidthForColumn(int column)
{
int nResult = lastColumnMinimumWidth;
int nTableWidth = tableView->horizontalHeader()->width();
if (nTableWidth > 0)
{
int nOtherColsWidth = getColumnsWidth() - tableView->horizontalHeader()->sectionSize(column);
nResult = std::max(nResult, nTableWidth - nOtherColsWidth);
}
return nResult;
}
// Make sure we don't make the columns wider than the table's viewport width.
void TableViewLastColumnResizingFixer::adjustTableColumnsWidth()
{
disconnectViewHeadersSignals();
resizeColumn(lastColumnIndex, getAvailableWidthForColumn(lastColumnIndex));
connectViewHeadersSignals();
int nTableWidth = tableView->horizontalHeader()->width();
int nColsWidth = getColumnsWidth();
if (nColsWidth > nTableWidth)
{
resizeColumn(secondToLastColumnIndex,getAvailableWidthForColumn(secondToLastColumnIndex));
}
}
// Make column use all the space available, useful during window resizing.
void TableViewLastColumnResizingFixer::stretchColumnWidth(int column)
{
disconnectViewHeadersSignals();
resizeColumn(column, getAvailableWidthForColumn(column));
connectViewHeadersSignals();
}
// When a section is resized this is a slot-proxy for ajustAmountColumnWidth().
void TableViewLastColumnResizingFixer::on_sectionResized(int logicalIndex, int oldSize, int newSize)
{
adjustTableColumnsWidth();
int remainingWidth = getAvailableWidthForColumn(logicalIndex);
if (newSize > remainingWidth)
{
resizeColumn(logicalIndex, remainingWidth);
}
}
// When the table's geometry is ready, we manually perform the stretch of the "Message" column,
// as the "Stretch" resize mode does not allow for interactive resizing.
void TableViewLastColumnResizingFixer::on_geometriesChanged()
{
if ((getColumnsWidth() - this->tableView->horizontalHeader()->width()) != 0)
{
disconnectViewHeadersSignals();
resizeColumn(secondToLastColumnIndex, getAvailableWidthForColumn(secondToLastColumnIndex));
connectViewHeadersSignals();
}
}
/**
* Initializes all internal variables and prepares the
* the resize modes of the last 2 columns of the table and
*/
TableViewLastColumnResizingFixer::TableViewLastColumnResizingFixer(QTableView* table, int lastColMinimumWidth, int allColsMinimumWidth, QObject *parent) :
QObject(parent),
tableView(table),
lastColumnMinimumWidth(lastColMinimumWidth),
allColumnsMinimumWidth(allColsMinimumWidth)
{
columnCount = tableView->horizontalHeader()->count();
lastColumnIndex = columnCount - 1;
secondToLastColumnIndex = columnCount - 2;
tableView->horizontalHeader()->setMinimumSectionSize(allColumnsMinimumWidth);
setViewHeaderResizeMode(secondToLastColumnIndex, QHeaderView::Interactive);
setViewHeaderResizeMode(lastColumnIndex, QHeaderView::Interactive);
}
#ifdef WIN32
fs::path static StartupShortcutPath()
{
std::string chain = ChainNameFromCommandLine();
if (chain == CBaseChainParams::MAIN)
return GetSpecialFolderPath(CSIDL_STARTUP) / "Utopiacoin.lnk";
if (chain == CBaseChainParams::TESTNET) // Remove this special case when CBaseChainParams::TESTNET = "testnet4"
return GetSpecialFolderPath(CSIDL_STARTUP) / "Utopiacoin (testnet).lnk";
return GetSpecialFolderPath(CSIDL_STARTUP) / strprintf("Utopiacoin (%s).lnk", chain);
}
bool GetStartOnSystemStartup()
{
// check for Utopiacoin*.lnk
return fs::exists(StartupShortcutPath());
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
// If the shortcut exists already, remove it for updating
fs::remove(StartupShortcutPath());
if (fAutoStart)
{
CoInitialize(nullptr);
// Get a pointer to the IShellLink interface.
IShellLink* psl = nullptr;
HRESULT hres = CoCreateInstance(CLSID_ShellLink, nullptr,
CLSCTX_INPROC_SERVER, IID_IShellLink,
reinterpret_cast<void**>(&psl));
if (SUCCEEDED(hres))
{
// Get the current executable path
TCHAR pszExePath[MAX_PATH];
GetModuleFileName(nullptr, pszExePath, sizeof(pszExePath));
// Start client minimized
QString strArgs = "-min";
// Set -testnet /-regtest options
strArgs += QString::fromStdString(strprintf(" -testnet=%d -regtest=%d", gArgs.GetBoolArg("-testnet", false), gArgs.GetBoolArg("-regtest", false)));
#ifdef UNICODE
boost::scoped_array<TCHAR> args(new TCHAR[strArgs.length() + 1]);
// Convert the QString to TCHAR*
strArgs.toWCharArray(args.get());
// Add missing '\0'-termination to string
args[strArgs.length()] = '\0';
#endif
// Set the path to the shortcut target
psl->SetPath(pszExePath);
PathRemoveFileSpec(pszExePath);
psl->SetWorkingDirectory(pszExePath);
psl->SetShowCmd(SW_SHOWMINNOACTIVE);
#ifndef UNICODE
psl->SetArguments(strArgs.toStdString().c_str());
#else
psl->SetArguments(args.get());
#endif
// Query IShellLink for the IPersistFile interface for
// saving the shortcut in persistent storage.
IPersistFile* ppf = nullptr;
hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf));
if (SUCCEEDED(hres))
{
WCHAR pwsz[MAX_PATH];
// Ensure that the string is ANSI.
MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(pwsz, TRUE);
ppf->Release();
psl->Release();
CoUninitialize();
return true;
}
psl->Release();
}
CoUninitialize();
return false;
}
return true;
}
#elif defined(Q_OS_LINUX)
// Follow the Desktop Application Autostart Spec:
// http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
fs::path static GetAutostartDir()
{
char* pszConfigHome = getenv("XDG_CONFIG_HOME");
if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
char* pszHome = getenv("HOME");
if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
return fs::path();
}
fs::path static GetAutostartFilePath()
{
std::string chain = ChainNameFromCommandLine();
if (chain == CBaseChainParams::MAIN)
return GetAutostartDir() / "utopiacoin.desktop";
return GetAutostartDir() / strprintf("utopiacoin-%s.lnk", chain);
}
bool GetStartOnSystemStartup()
{
fs::ifstream optionFile(GetAutostartFilePath());
if (!optionFile.good())
return false;
// Scan through file for "Hidden=true":
std::string line;
while (!optionFile.eof())
{
getline(optionFile, line);
if (line.find("Hidden") != std::string::npos &&
line.find("true") != std::string::npos)
return false;
}
optionFile.close();
return true;
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
if (!fAutoStart)
fs::remove(GetAutostartFilePath());
else
{
char pszExePath[MAX_PATH+1];
ssize_t r = readlink("/proc/self/exe", pszExePath, sizeof(pszExePath) - 1);
if (r == -1)
return false;
pszExePath[r] = '\0';
fs::create_directories(GetAutostartDir());
fs::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
if (!optionFile.good())
return false;
std::string chain = ChainNameFromCommandLine();
// Write a utopiacoin.desktop file to the autostart directory:
optionFile << "[Desktop Entry]\n";
optionFile << "Type=Application\n";
if (chain == CBaseChainParams::MAIN)
optionFile << "Name=Utopiacoin\n";
else
optionFile << strprintf("Name=Utopiacoin (%s)\n", chain);
optionFile << "Exec=" << pszExePath << strprintf(" -min -testnet=%d -regtest=%d\n", gArgs.GetBoolArg("-testnet", false), gArgs.GetBoolArg("-regtest", false));
optionFile << "Terminal=false\n";
optionFile << "Hidden=false\n";
optionFile.close();
}
return true;
}
#elif defined(Q_OS_MAC)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
// based on: https://github.com/Mozketo/LaunchAtLoginController/blob/master/LaunchAtLoginController.m
#include <CoreFoundation/CoreFoundation.h>
#include <CoreServices/CoreServices.h>
LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl);
LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl)
{
CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(list, nullptr);
if (listSnapshot == nullptr) {
return nullptr;
}
// loop through the list of startup items and try to find the utopiacoin app
for(int i = 0; i < CFArrayGetCount(listSnapshot); i++) {
LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i);
UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes;
CFURLRef currentItemURL = nullptr;
#if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED >= 10100
if(&LSSharedFileListItemCopyResolvedURL)
currentItemURL = LSSharedFileListItemCopyResolvedURL(item, resolutionFlags, nullptr);
#if defined(MAC_OS_X_VERSION_MIN_REQUIRED) && MAC_OS_X_VERSION_MIN_REQUIRED < 10100
else
LSSharedFileListItemResolve(item, resolutionFlags, ¤tItemURL, nullptr);
#endif
#else
LSSharedFileListItemResolve(item, resolutionFlags, ¤tItemURL, nullptr);
#endif
if(currentItemURL) {
if (CFEqual(currentItemURL, findUrl)) {
// found
CFRelease(listSnapshot);
CFRelease(currentItemURL);
return item;
}
CFRelease(currentItemURL);
}
}
CFRelease(listSnapshot);
return nullptr;
}
bool GetStartOnSystemStartup()
{
CFURLRef utopiacoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
if (utopiacoinAppUrl == nullptr) {
return false;
}
LSSharedFileListRef loginItems = LSSharedFileListCreate(nullptr, kLSSharedFileListSessionLoginItems, nullptr);
LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, utopiacoinAppUrl);
CFRelease(utopiacoinAppUrl);
return !!foundItem; // return boolified object
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
CFURLRef utopiacoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
if (utopiacoinAppUrl == nullptr) {
return false;
}
LSSharedFileListRef loginItems = LSSharedFileListCreate(nullptr, kLSSharedFileListSessionLoginItems, nullptr);
LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, utopiacoinAppUrl);
if(fAutoStart && !foundItem) {
// add utopiacoin app to startup item list
LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, nullptr, nullptr, utopiacoinAppUrl, nullptr, nullptr);
}
else if(!fAutoStart && foundItem) {
// remove item
LSSharedFileListItemRemove(loginItems, foundItem);
}
CFRelease(utopiacoinAppUrl);
return true;
}
#pragma GCC diagnostic pop
#else
bool GetStartOnSystemStartup() { return false; }
bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
#endif
void setClipboard(const QString& str)
{
QApplication::clipboard()->setText(str, QClipboard::Clipboard);
QApplication::clipboard()->setText(str, QClipboard::Selection);
}
fs::path qstringToBoostPath(const QString &path)
{
return fs::path(path.toStdString(), utf8);
}
QString boostPathToQString(const fs::path &path)
{
return QString::fromStdString(path.string(utf8));
}
QString formatDurationStr(int secs)
{
QStringList strList;
int days = secs / 86400;
int hours = (secs % 86400) / 3600;
int mins = (secs % 3600) / 60;
int seconds = secs % 60;
if (days)
strList.append(QString(QObject::tr("%1 d")).arg(days));
if (hours)
strList.append(QString(QObject::tr("%1 h")).arg(hours));
if (mins)
strList.append(QString(QObject::tr("%1 m")).arg(mins));
if (seconds || (!days && !hours && !mins))
strList.append(QString(QObject::tr("%1 s")).arg(seconds));
return strList.join(" ");
}
QString formatServicesStr(quint64 mask)
{
QStringList strList;
// Just scan the last 8 bits for now.
for (int i = 0; i < 8; i++) {
uint64_t check = 1 << i;
if (mask & check)
{
switch (check)
{
case NODE_NETWORK:
strList.append("NETWORK");
break;
case NODE_GETUTXO:
strList.append("GETUTXO");
break;
case NODE_BLOOM:
strList.append("BLOOM");
break;
case NODE_WITNESS:
strList.append("WITNESS");
break;
case NODE_XTHIN:
strList.append("XTHIN");
break;
default:
strList.append(QString("%1[%2]").arg("UNKNOWN").arg(check));
}
}
}
if (strList.size())
return strList.join(" & ");
else
return QObject::tr("None");
}
QString formatPingTime(double dPingTime)
{
return (dPingTime == std::numeric_limits<int64_t>::max()/1e6 || dPingTime == 0) ? QObject::tr("N/A") : QString(QObject::tr("%1 ms")).arg(QString::number((int)(dPingTime * 1000), 10));
}
QString formatTimeOffset(int64_t nTimeOffset)
{
return QString(QObject::tr("%1 s")).arg(QString::number((int)nTimeOffset, 10));
}
QString formatNiceTimeOffset(qint64 secs)
{
// Represent time from last generated block in human readable text
QString timeBehindText;
const int HOUR_IN_SECONDS = 60*60;
const int DAY_IN_SECONDS = 24*60*60;
const int WEEK_IN_SECONDS = 7*24*60*60;
const int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar
if(secs < 60)
{
timeBehindText = QObject::tr("%n second(s)","",secs);
}
else if(secs < 2*HOUR_IN_SECONDS)
{
timeBehindText = QObject::tr("%n minute(s)","",secs/60);
}
else if(secs < 2*DAY_IN_SECONDS)
{
timeBehindText = QObject::tr("%n hour(s)","",secs/HOUR_IN_SECONDS);
}
else if(secs < 2*WEEK_IN_SECONDS)
{
timeBehindText = QObject::tr("%n day(s)","",secs/DAY_IN_SECONDS);
}
else if(secs < YEAR_IN_SECONDS)
{
timeBehindText = QObject::tr("%n week(s)","",secs/WEEK_IN_SECONDS);
}
else
{
qint64 years = secs / YEAR_IN_SECONDS;
qint64 remainder = secs % YEAR_IN_SECONDS;
timeBehindText = QObject::tr("%1 and %2").arg(QObject::tr("%n year(s)", "", years)).arg(QObject::tr("%n week(s)","", remainder/WEEK_IN_SECONDS));
}
return timeBehindText;
}
QString formatBytes(uint64_t bytes)
{
if(bytes < 1024)
return QString(QObject::tr("%1 B")).arg(bytes);
if(bytes < 1024 * 1024)
return QString(QObject::tr("%1 KB")).arg(bytes / 1024);
if(bytes < 1024 * 1024 * 1024)
return QString(QObject::tr("%1 MB")).arg(bytes / 1024 / 1024);
return QString(QObject::tr("%1 GB")).arg(bytes / 1024 / 1024 / 1024);
}
qreal calculateIdealFontSize(int width, const QString& text, QFont font, qreal minPointSize, qreal font_size) {
while(font_size >= minPointSize) {
font.setPointSizeF(font_size);
QFontMetrics fm(font);
if (fm.width(text) < width) {
break;
}
font_size -= 0.5;
}
return font_size;
}
void ClickableLabel::mouseReleaseEvent(QMouseEvent *event)
{
Q_EMIT clicked(event->pos());
}
void ClickableProgressBar::mouseReleaseEvent(QMouseEvent *event)
{
Q_EMIT clicked(event->pos());
}
} // namespace GUIUtil
|
class Solution {
public:
int nthUglyNumber(int n) {
vector<int> nums(n);
int c2 = 0, c3 = 0, c5 = 0;
nums[0] = 1;
for (int i = 1; i < n; i++) {
nums[i] = min(nums[c2] * 2, min(nums[c3] * 3, nums[c5] * 5));
if (nums[i] == nums[c2] * 2) c2++;
if (nums[i] == nums[c3] * 3) c3++;
if (nums[i] == nums[c5] * 5) c5++;
}
return nums[n - 1];
}
};
|
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(FUSION_SEQUENCE_FILTER_VIEW_HPP)
#define FUSION_SEQUENCE_FILTER_VIEW_HPP
#include <boost/fusion/support/config.hpp>
#include <boost/fusion/support/detail/access.hpp>
#include <boost/fusion/support/sequence_base.hpp>
#include <boost/fusion/support/is_view.hpp>
#include <boost/fusion/view/filter_view/filter_view_iterator.hpp>
#include <boost/fusion/view/filter_view/detail/begin_impl.hpp>
#include <boost/fusion/view/filter_view/detail/end_impl.hpp>
#include <boost/fusion/view/filter_view/detail/size_impl.hpp>
#include <boost/fusion/sequence/intrinsic/begin.hpp>
#include <boost/fusion/sequence/intrinsic/end.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/inherit.hpp>
#include <boost/mpl/identity.hpp>
namespace boost { namespace fusion
{
struct filter_view_tag;
struct forward_traversal_tag;
struct fusion_sequence_tag;
template <typename Sequence, typename Pred>
struct filter_view : sequence_base<filter_view<Sequence, Pred> >
{
typedef filter_view_tag fusion_tag;
typedef fusion_sequence_tag tag; // this gets picked up by MPL
typedef typename
mpl::eval_if<
traits::is_associative<Sequence>
, mpl::inherit2<forward_traversal_tag,associative_tag>
, mpl::identity<forward_traversal_tag>
>::type
category;
typedef mpl::true_ is_view;
typedef typename result_of::begin<Sequence>::type first_type;
typedef typename result_of::end<Sequence>::type last_type;
typedef Pred pred_type;
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
filter_view(Sequence& in_seq)
: seq(in_seq)
{}
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
first_type first() const { return fusion::begin(seq); }
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
last_type last() const { return fusion::end(seq); }
typename mpl::if_<traits::is_view<Sequence>, Sequence, Sequence&>::type seq;
// silence MSVC warning C4512: assignment operator could not be generated
BOOST_DELETED_FUNCTION(filter_view& operator= (filter_view const&))
};
}}
#endif
|
#include "soundManager.h"
#include <iostream>
const std::string SoundManager::soundPaths[SoundManager::TOTAL_SOUNDS] = {"Assets/Sound/sound/default/arugh.wav",
"Assets/Sound/sound/prt/laser.wav",
"Assets/Sound/sound/prt/thud.wav",
"Assets/Sound/sound/prt/footstep.wav",
"Assets/Sound/sound/prt/glass_cracking.wav",
"Assets/Sound/sound/prt/glass_shatter.wav" };
std::vector<SoundClip*> SoundManager::soundClips;
const std::string SoundManager::musicPaths[SoundManager::TOTAL_MUSIC] = { "Assets/Sound/music/default/untitled.mid",
"Assets/Sound/music/prt/window.mid",
"Assets/Sound/music/prt/lab.mid",
"Assets/Sound/music/editor/editor.mid" };
std::vector<MusicClip*> SoundManager::musicClips;
SoundManager::MUSIC SoundManager::currentMusic = TOTAL_MUSIC;
void SoundManager::initalizeSoundManager()
{
MusicClip::initialize();
soundClips.resize(TOTAL_SOUNDS);
for (int i = 0; i < TOTAL_SOUNDS; i++) {
soundClips[i] = (new SoundClip(soundPaths[i]));
}
musicClips.resize(TOTAL_MUSIC);
for (int i = 0; i < TOTAL_MUSIC; i++) {
musicClips[i] = (new MusicClip(musicPaths[i]));
}
}
void SoundManager::closeSoundManager()
{
soundClips.clear();
musicClips.clear();
}
void SoundManager::playMusic(MUSIC music)
{
if (music == TOTAL_MUSIC) {
musicClips[currentMusic]->stop();
}
if (music == currentMusic) {
return;
}
else {
if (currentMusic < TOTAL_MUSIC)
musicClips[currentMusic]->stop();
musicClips[music]->play();
}
currentMusic = music;
}
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Copyright (C) 2017, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "opencv2/core/hal/intrin.hpp"
namespace cv {
namespace dnn {
CV_CPU_OPTIMIZATION_NAMESPACE_BEGIN
void fastConv( const float* weights, size_t wstep, const float* bias,
const float* rowbuf, float* output, const int* outShape,
int blockSize, int vecsize, int vecsize_aligned,
const float* relu, bool initOutput );
void fastDepthwiseConv( const float* weights,
int kernel_h, int kernel_w,
int stride_h, int stride_w,
int dilation_h, int dilation_w,
int pad_t, int pad_l,
const float* bias, const float* relu,
const float* inptr,
int height, int width,
float* outptr,
int out_d, int outH, int outW );
void fastGEMM1T( const float* vec, const float* weights,
size_t wstep, const float* bias,
float* dst, int nvecs, int vecsize );
void fastGEMM( const float* aptr, size_t astep, const float* bptr,
size_t bstep, float* cptr, size_t cstep,
int ma, int na, int nb );
#if !defined(CV_CPU_OPTIMIZATION_DECLARATIONS_ONLY) && CV_AVX
#if !CV_FMA3 // AVX workaround
#undef _mm256_fmadd_ps
#define _mm256_fmadd_ps(a, b, c) _mm256_add_ps(c, _mm256_mul_ps(a, b))
#endif
enum { FASCONV_BASE_VECSZ = 4 };
void fastConv( const float* weights, size_t wstep, const float* bias,
const float* rowbuf, float* output, const int* outShape,
int blockSize, int vecsize, int vecsize_aligned,
const float* relu, bool initOutput )
{
CV_Assert(isAligned<32>(weights));
int outCn = outShape[1];
size_t outPlaneSize = outShape[2]*outShape[3];
float r0 = 1.f, r1 = 1.f, r2 = 1.f;
__m128 vr0 = _mm_set1_ps(1.f), vr1 = vr0, vr2 = vr0, z = _mm_setzero_ps();
int CV_DECL_ALIGNED(16) maskbuf[FASCONV_BASE_VECSZ] = {0};
int rsz = blockSize % FASCONV_BASE_VECSZ;
for( int i = 0; i < rsz; i++ )
maskbuf[FASCONV_BASE_VECSZ - i - 1] = -1;
__m128 mask = _mm_loadu_ps((const float*)maskbuf);
// now compute dot product of the weights
// and im2row-transformed part of the tensor
for( int i = 0; i < outCn; i += 3 )
{
const float* wptr0 = weights + i*wstep;
const float* wptr1 = wptr0 + wstep;
const float* wptr2 = wptr1 + wstep;
float* outptr0 = output + i*outPlaneSize;
float* outptr1 = outptr0 + outPlaneSize;
float* outptr2 = outptr1 + outPlaneSize;
float bias0 = bias[i], bias1 = bias[i+1], bias2 = bias[i+2];
if( i+2 >= outCn )
{
wptr2 = wptr1;
outptr2 = outptr1;
bias2 = bias1;
if( i+1 >= outCn )
{
wptr2 = wptr1 = wptr0;
outptr2 = outptr1 = outptr0;
bias2 = bias1 = bias0;
}
}
if( relu )
{
r0 = relu[i]; r1 = relu[i+1]; r2 = relu[i+2];
if( i+2 >= outCn )
{
r2 = r1;
if( i+1 >= outCn )
r2 = r1 = r0;
}
vr0 = _mm_set1_ps(r0);
vr1 = _mm_set1_ps(r1);
vr2 = _mm_set1_ps(r2);
}
int j = 0;
for( ; j < blockSize; j += FASCONV_BASE_VECSZ )
{
bool tail = false;
if (j + FASCONV_BASE_VECSZ > blockSize)
{
if (j == 0)
break;
j = blockSize - FASCONV_BASE_VECSZ;
tail = true;
}
int k = 0;
const float* rptr = rowbuf + j*vecsize_aligned;
__m256 vs00 = _mm256_setzero_ps(), vs01 = _mm256_setzero_ps(),
vs02 = _mm256_setzero_ps(), vs03 = _mm256_setzero_ps(),
vs10 = _mm256_setzero_ps(), vs11 = _mm256_setzero_ps(),
vs12 = _mm256_setzero_ps(), vs13 = _mm256_setzero_ps(),
vs20 = _mm256_setzero_ps(), vs21 = _mm256_setzero_ps(),
vs22 = _mm256_setzero_ps(), vs23 = _mm256_setzero_ps();
#if CV_AVX512_SKX // AVX512VL is necessary to avoid register spilling
if (vecsize >= 32)
{
__m512 vs00_5 = _mm512_setzero_ps(), vs01_5 = _mm512_setzero_ps(),
vs02_5 = _mm512_setzero_ps(), vs03_5 = _mm512_setzero_ps(),
vs10_5 = _mm512_setzero_ps(), vs11_5 = _mm512_setzero_ps(),
vs12_5 = _mm512_setzero_ps(), vs13_5 = _mm512_setzero_ps(),
vs20_5 = _mm512_setzero_ps(), vs21_5 = _mm512_setzero_ps(),
vs22_5 = _mm512_setzero_ps(), vs23_5 = _mm512_setzero_ps();
for (; k <= vecsize - 16; k += 16, rptr += 16)
{
__m512 w0 = _mm512_loadu_ps(wptr0 + k);
__m512 w1 = _mm512_loadu_ps(wptr1 + k);
__m512 w2 = _mm512_loadu_ps(wptr2 + k);
__m512 r0 = _mm512_loadu_ps(rptr);
vs00_5 = _mm512_fmadd_ps(w0, r0, vs00_5);
vs10_5 = _mm512_fmadd_ps(w1, r0, vs10_5);
vs20_5 = _mm512_fmadd_ps(w2, r0, vs20_5);
r0 = _mm512_loadu_ps(rptr + vecsize_aligned);
vs01_5 = _mm512_fmadd_ps(w0, r0, vs01_5);
vs11_5 = _mm512_fmadd_ps(w1, r0, vs11_5);
vs21_5 = _mm512_fmadd_ps(w2, r0, vs21_5);
r0 = _mm512_loadu_ps(rptr + vecsize_aligned*2);
vs02_5 = _mm512_fmadd_ps(w0, r0, vs02_5);
vs12_5 = _mm512_fmadd_ps(w1, r0, vs12_5);
vs22_5 = _mm512_fmadd_ps(w2, r0, vs22_5);
r0 = _mm512_loadu_ps(rptr + vecsize_aligned*3);
vs03_5 = _mm512_fmadd_ps(w0, r0, vs03_5);
vs13_5 = _mm512_fmadd_ps(w1, r0, vs13_5);
vs23_5 = _mm512_fmadd_ps(w2, r0, vs23_5);
}
/*
* now fold the 512 bit accumulator vectors into 256 bit vectors so that the AVX2 code can finish
* the tail of the vector
*/
vs00 = _mm256_add_ps( _mm512_extractf32x8_ps(vs00_5, 0), _mm512_extractf32x8_ps(vs00_5, 1));
vs10 = _mm256_add_ps( _mm512_extractf32x8_ps(vs10_5, 0), _mm512_extractf32x8_ps(vs10_5, 1));
vs20 = _mm256_add_ps( _mm512_extractf32x8_ps(vs20_5, 0), _mm512_extractf32x8_ps(vs20_5, 1));
vs01 = _mm256_add_ps( _mm512_extractf32x8_ps(vs01_5, 0), _mm512_extractf32x8_ps(vs01_5, 1));
vs11 = _mm256_add_ps( _mm512_extractf32x8_ps(vs11_5, 0), _mm512_extractf32x8_ps(vs11_5, 1));
vs21 = _mm256_add_ps( _mm512_extractf32x8_ps(vs21_5, 0), _mm512_extractf32x8_ps(vs21_5, 1));
vs02 = _mm256_add_ps( _mm512_extractf32x8_ps(vs02_5, 0), _mm512_extractf32x8_ps(vs02_5, 1));
vs12 = _mm256_add_ps( _mm512_extractf32x8_ps(vs12_5, 0), _mm512_extractf32x8_ps(vs12_5, 1));
vs22 = _mm256_add_ps( _mm512_extractf32x8_ps(vs22_5, 0), _mm512_extractf32x8_ps(vs22_5, 1));
vs03 = _mm256_add_ps( _mm512_extractf32x8_ps(vs03_5, 0), _mm512_extractf32x8_ps(vs03_5, 1));
vs13 = _mm256_add_ps( _mm512_extractf32x8_ps(vs13_5, 0), _mm512_extractf32x8_ps(vs13_5, 1));
vs23 = _mm256_add_ps( _mm512_extractf32x8_ps(vs23_5, 0), _mm512_extractf32x8_ps(vs23_5, 1));
}
#endif
for (; k < vecsize; k += 8, rptr += 8 )
{
__m256 w0 = _mm256_load_ps(wptr0 + k);
__m256 w1 = _mm256_load_ps(wptr1 + k);
__m256 w2 = _mm256_load_ps(wptr2 + k);
__m256 r0 = _mm256_load_ps(rptr);
vs00 = _mm256_fmadd_ps(w0, r0, vs00);
vs10 = _mm256_fmadd_ps(w1, r0, vs10);
vs20 = _mm256_fmadd_ps(w2, r0, vs20);
r0 = _mm256_load_ps(rptr + vecsize_aligned);
vs01 = _mm256_fmadd_ps(w0, r0, vs01);
vs11 = _mm256_fmadd_ps(w1, r0, vs11);
vs21 = _mm256_fmadd_ps(w2, r0, vs21);
r0 = _mm256_load_ps(rptr + vecsize_aligned*2);
vs02 = _mm256_fmadd_ps(w0, r0, vs02);
vs12 = _mm256_fmadd_ps(w1, r0, vs12);
vs22 = _mm256_fmadd_ps(w2, r0, vs22);
r0 = _mm256_load_ps(rptr + vecsize_aligned*3);
vs03 = _mm256_fmadd_ps(w0, r0, vs03);
vs13 = _mm256_fmadd_ps(w1, r0, vs13);
vs23 = _mm256_fmadd_ps(w2, r0, vs23);
}
__m256 t0 = _mm256_hadd_ps(_mm256_hadd_ps(vs00, vs01), _mm256_hadd_ps(vs02, vs03));
__m256 t1 = _mm256_hadd_ps(_mm256_hadd_ps(vs10, vs11), _mm256_hadd_ps(vs12, vs13));
__m256 t2 = _mm256_hadd_ps(_mm256_hadd_ps(vs20, vs21), _mm256_hadd_ps(vs22, vs23));
t0 = _mm256_add_ps(t0, _mm256_permute2f128_ps(t0, t0, 1));
t1 = _mm256_add_ps(t1, _mm256_permute2f128_ps(t1, t1, 1));
t2 = _mm256_add_ps(t2, _mm256_permute2f128_ps(t2, t2, 1));
__m128 s0, s1, s2;
if( initOutput )
{
s0 = _mm_set1_ps(bias0);
s1 = _mm_set1_ps(bias1);
s2 = _mm_set1_ps(bias2);
}
else
{
s0 = _mm_loadu_ps(outptr0 + j);
s1 = _mm_loadu_ps(outptr1 + j);
s2 = _mm_loadu_ps(outptr2 + j);
}
s0 = _mm_add_ps(s0, _mm256_castps256_ps128(t0));
s1 = _mm_add_ps(s1, _mm256_castps256_ps128(t1));
s2 = _mm_add_ps(s2, _mm256_castps256_ps128(t2));
if( relu )
{
__m128 m0 = _mm_cmp_ps(s0, z, _CMP_GT_OS);
__m128 m1 = _mm_cmp_ps(s1, z, _CMP_GT_OS);
__m128 m2 = _mm_cmp_ps(s2, z, _CMP_GT_OS);
s0 = _mm_blendv_ps(_mm_mul_ps(s0, vr0), s0, m0);
s1 = _mm_blendv_ps(_mm_mul_ps(s1, vr1), s1, m1);
s2 = _mm_blendv_ps(_mm_mul_ps(s2, vr2), s2, m2);
}
if( tail )
{
s0 = _mm_blendv_ps(_mm_loadu_ps(outptr0 + j), s0, mask);
s1 = _mm_blendv_ps(_mm_loadu_ps(outptr1 + j), s1, mask);
s2 = _mm_blendv_ps(_mm_loadu_ps(outptr2 + j), s2, mask);
}
_mm_storeu_ps(outptr0 + j, s0);
_mm_storeu_ps(outptr1 + j, s1);
_mm_storeu_ps(outptr2 + j, s2);
}
for( ; j <= blockSize - 2; j += 2 )
{
const float* rptr0 = rowbuf + j*vecsize_aligned;
const float* rptr1 = rowbuf + (j+1)*vecsize_aligned;
float s00, s01, s10, s11, s20, s21;
if( initOutput )
{
s00 = s01 = bias0;
s10 = s11 = bias1;
s20 = s21 = bias2;
}
else
{
s00 = outptr0[j]; s01 = outptr0[j+1];
s10 = outptr1[j]; s11 = outptr1[j+1];
s20 = outptr2[j]; s21 = outptr2[j+1];
}
for( int k = 0; k < vecsize; k++ )
{
float w0 = wptr0[k], w1 = wptr1[k], w2 = wptr2[k];
float r = rptr0[k];
s00 += w0*r; s10 += w1*r; s20 += w2*r;
r = rptr1[k];
s01 += w0*r; s11 += w1*r; s21 += w2*r;
}
if( relu )
{
s00 = s00 > 0.f ? s00 : s00*r0;
s01 = s01 > 0.f ? s01 : s01*r0;
s10 = s10 > 0.f ? s10 : s10*r1;
s11 = s11 > 0.f ? s11 : s11*r1;
s20 = s20 > 0.f ? s20 : s20*r2;
s21 = s21 > 0.f ? s21 : s21*r2;
}
outptr0[j] = s00;
outptr0[j+1] = s01;
outptr1[j] = s10;
outptr1[j+1] = s11;
outptr2[j] = s20;
outptr2[j+1] = s21;
}
for( ; j < blockSize; j++ )
{
const float* rptr0 = rowbuf + j*vecsize_aligned;
float s00, s10, s20;
if( initOutput )
{
s00 = bias0;
s10 = bias1;
s20 = bias2;
}
else
{
s00 = outptr0[j];
s10 = outptr1[j];
s20 = outptr2[j];
}
for( int k = 0; k < vecsize; k++ )
{
float w0 = wptr0[k], w1 = wptr1[k], w2 = wptr2[k];
float r = rptr0[k];
s00 += w0*r; s10 += w1*r; s20 += w2*r;
}
if( relu )
{
s00 = s00 > 0.f ? s00 : s00*r0;
s10 = s10 > 0.f ? s10 : s10*r1;
s20 = s20 > 0.f ? s20 : s20*r2;
}
outptr0[j] = s00;
outptr1[j] = s10;
outptr2[j] = s20;
}
}
_mm256_zeroupper();
}
static inline void _mm256_load_deinterleave(const float* ptr, __m256& a, __m256& b)
{
__m256 t0 = _mm256_loadu_ps(ptr);
__m256 t1 = _mm256_loadu_ps(ptr + 8);
__m256 lo = _mm256_permute2f128_ps(t0, t1, 0+2*16);
__m256 hi = _mm256_permute2f128_ps(t0, t1, 1+3*16);
a = _mm256_shuffle_ps(lo, hi, 0x88);
b = _mm256_shuffle_ps(lo, hi, 0xdd);
}
void fastDepthwiseConv( const float* wptr,
int kernel_h, int kernel_w,
int stride_h, int stride_w,
int dilation_h, int dilation_w,
int pad_t, int pad_l,
const float* biasptr, const float* relu,
const float* inptr_,
int height, int width,
float* outptr_,
int out_d, int outH, int outW )
{
const float w00_ = wptr[0], w01_ = wptr[1], w02_ = wptr[2],
w10 = wptr[3], w11 = wptr[4], w12 = wptr[5],
w20_ = wptr[6], w21_ = wptr[7], w22_ = wptr[8];
int outW1 = min(outW, (width - dilation_w*(kernel_w - 1) + pad_l)/stride_w);
float relu_coeff = relu ? relu[out_d] : 1.f, bias = biasptr[out_d];
for (int out_i = 0; out_i < outH; out_i++)
{
int in_i = out_i * stride_h - pad_t, out_j = 0;
const float* imgptr0 = inptr_ + in_i*width;
const float* imgptr1 = imgptr0 + dilation_h*width;
const float* imgptr2 = imgptr0 + (dilation_h*2)*width;
float out, w00 = w00_, w01 = w01_, w02 = w02_;
float w20 = w20_, w21 = w21_, w22 = w22_;
if (in_i < 0)
{
w00 = w01 = w02 = 0.f;
imgptr0 = imgptr1;
}
else if (in_i + dilation_h*(kernel_h-1) >= height)
{
w20 = w21 = w22 = 0.f;
imgptr2 = imgptr1;
}
float* outptr = outptr_ + out_i*outW;
if (pad_l > 0)
{
out = imgptr0[0]*w01 + imgptr0[dilation_w]*w02 +
imgptr1[0]*w11 + imgptr1[dilation_w]*w12 +
imgptr2[0]*w21 + imgptr2[dilation_w]*w22 + bias;
if (relu)
out = out > 0.f ? out : out*relu_coeff;
outptr[0] = out;
out_j = 1;
}
if (stride_w == 1 || (stride_w == 2 && dilation_w == 1))
{
const int VECSZ = 8;
__m256 vw00 = _mm256_set1_ps(w00), vw01 = _mm256_set1_ps(w01), vw02 = _mm256_set1_ps(w02),
vw10 = _mm256_set1_ps(w10), vw11 = _mm256_set1_ps(w11), vw12 = _mm256_set1_ps(w12),
vw20 = _mm256_set1_ps(w20), vw21 = _mm256_set1_ps(w21), vw22 = _mm256_set1_ps(w22);
__m256 z = _mm256_setzero_ps(), vbias = _mm256_set1_ps(bias), vrc = _mm256_set1_ps(relu_coeff);
if( stride_w == 1 )
for( ; out_j < outW1; out_j += VECSZ )
{
if (out_j + VECSZ > outW1 && out_j > pad_l)
out_j = outW1 - VECSZ;
int in_j = out_j * stride_w - pad_l;
__m256 v00 = _mm256_loadu_ps(imgptr0 + in_j),
v01 = _mm256_loadu_ps(imgptr0 + in_j + dilation_w),
v02 = _mm256_loadu_ps(imgptr0 + in_j + dilation_w*2),
v10 = _mm256_loadu_ps(imgptr1 + in_j),
v11 = _mm256_loadu_ps(imgptr1 + in_j + dilation_w),
v12 = _mm256_loadu_ps(imgptr1 + in_j + dilation_w*2),
v20 = _mm256_loadu_ps(imgptr2 + in_j),
v21 = _mm256_loadu_ps(imgptr2 + in_j + dilation_w),
v22 = _mm256_loadu_ps(imgptr2 + in_j + dilation_w*2);
__m256 vout0 = _mm256_fmadd_ps(v00, vw00, vbias);
__m256 vout1 = _mm256_mul_ps(v01, vw01);
__m256 vout2 = _mm256_mul_ps(v02, vw02);
vout0 = _mm256_fmadd_ps(v10, vw10, vout0);
vout1 = _mm256_fmadd_ps(v11, vw11, vout1);
vout2 = _mm256_fmadd_ps(v12, vw12, vout2);
vout0 = _mm256_fmadd_ps(v20, vw20, vout0);
vout1 = _mm256_fmadd_ps(v21, vw21, vout1);
vout2 = _mm256_fmadd_ps(v22, vw22, vout2);
vout0 = _mm256_add_ps(_mm256_add_ps(vout0, vout1), vout2);
if (relu)
{
__m256 m = _mm256_cmp_ps(vout0, z, _CMP_GT_OQ);
vout0 = _mm256_blendv_ps(_mm256_mul_ps(vout0, vrc), vout0, m);
}
_mm256_storeu_ps(outptr + out_j, vout0);
}
else
for( ; out_j < outW1; out_j += VECSZ )
{
if (out_j + VECSZ > outW1 && out_j > pad_l)
out_j = outW1 - VECSZ;
int in_j = out_j * stride_w - pad_l;
__m256 v00, v01, v02, v10, v11, v12, v20, v21, v22, unused;
_mm256_load_deinterleave(imgptr0 + in_j, v00, v01);
_mm256_load_deinterleave(imgptr0 + in_j + 2, v02, unused);
_mm256_load_deinterleave(imgptr1 + in_j, v10, v11);
_mm256_load_deinterleave(imgptr1 + in_j + 2, v12, unused);
_mm256_load_deinterleave(imgptr2 + in_j, v20, v21);
_mm256_load_deinterleave(imgptr2 + in_j + 2, v22, unused);
__m256 vout0 = _mm256_fmadd_ps(v00, vw00, vbias);
__m256 vout1 = _mm256_mul_ps(v01, vw01);
__m256 vout2 = _mm256_mul_ps(v02, vw02);
vout0 = _mm256_fmadd_ps(v10, vw10, vout0);
vout1 = _mm256_fmadd_ps(v11, vw11, vout1);
vout2 = _mm256_fmadd_ps(v12, vw12, vout2);
vout0 = _mm256_fmadd_ps(v20, vw20, vout0);
vout1 = _mm256_fmadd_ps(v21, vw21, vout1);
vout2 = _mm256_fmadd_ps(v22, vw22, vout2);
vout0 = _mm256_add_ps(_mm256_add_ps(vout0, vout1), vout2);
if (relu)
{
__m256 m = _mm256_cmp_ps(vout0, z, _CMP_GT_OQ);
vout0 = _mm256_blendv_ps(_mm256_mul_ps(vout0, vrc), vout0, m);
}
_mm256_storeu_ps(outptr + out_j, vout0);
}
}
for (; out_j < outW1; out_j++)
{
int in_j = out_j * stride_w - pad_l;
out = imgptr0[in_j]*w00 + imgptr0[in_j + dilation_w]*w01 + imgptr0[in_j + dilation_w*2]*w02 +
imgptr1[in_j]*w10 + imgptr1[in_j + dilation_w]*w11 + imgptr1[in_j + dilation_w*2]*w12 +
imgptr2[in_j]*w20 + imgptr2[in_j + dilation_w]*w21 + imgptr2[in_j + dilation_w*2]*w22 + bias;
if (relu)
out = out > 0.f ? out : out*relu_coeff;
outptr[out_j] = out;
}
for (; out_j < outW; out_j++ )
{
int in_j0 = out_j * stride_w - pad_l, in_j1 = in_j0 + dilation_w, in_j2 = in_j0 + dilation_w*2;
float s0 = 1.f, s1 = 1.f, s2 = 1.f;
if (in_j0 >= width)
{
in_j0 = 0;
s0 = 0.f;
}
if (in_j1 >= width)
{
in_j1 = 0;
s1 = 0.f;
}
if (in_j2 >= width)
{
in_j2 = 0;
s2 = 0.f;
}
out = imgptr0[in_j0]*w00*s0 + imgptr0[in_j1]*w01*s1 + imgptr0[in_j2]*w02*s2 +
imgptr1[in_j0]*w10*s0 + imgptr1[in_j1]*w11*s1 + imgptr1[in_j2]*w12*s2 +
imgptr2[in_j0]*w20*s0 + imgptr2[in_j1]*w21*s1 + imgptr2[in_j2]*w22*s2 + bias;
if (relu)
out = out > 0.f ? out : out*relu_coeff;
outptr[out_j] = out;
}
}
_mm256_zeroupper();
}
// Used to generate the mask used when calculating tails
static const uint32_t tailMaskArray[15] = {
0, 0, 0, 0, 0, 0, 0, 0,
0xffffffffUL, 0xffffffffUL, 0xffffffffUL, 0xffffffffUL, 0xffffffffUL, 0xffffffffUL, 0xffffffffUL
};
// dst = vec * weights^t + bias
// Requires that vecsize is at least 8 or equal to 0 to avoid memory access problems. Does not require alignment.
void fastGEMM1T( const float* vec, const float* weights,
size_t wstep, const float* bias,
float* dst, int nvecs, int vecsize )
{
int i = 0;
CV_Assert(vecsize >= 8 || vecsize == 0);
__m256 tailMask = _mm256_loadu_ps(reinterpret_cast<const float*>(tailMaskArray) + (vecsize % 8));
for( ; i <= nvecs - 8; i += 8 )
{
const float* wptr = weights + i*wstep;
__m256 vs0 = _mm256_setzero_ps(), vs1 = _mm256_setzero_ps(),
vs2 = _mm256_setzero_ps(), vs3 = _mm256_setzero_ps(),
vs4 = _mm256_setzero_ps(), vs5 = _mm256_setzero_ps(),
vs6 = _mm256_setzero_ps(), vs7 = _mm256_setzero_ps();
int k = 0;
for( ; k <= vecsize-8; k += 8, wptr += 8 )
{
__m256 v = _mm256_loadu_ps(vec + k);
vs0 = _mm256_fmadd_ps(_mm256_loadu_ps(wptr), v, vs0);
vs1 = _mm256_fmadd_ps(_mm256_loadu_ps(wptr + wstep), v, vs1);
vs2 = _mm256_fmadd_ps(_mm256_loadu_ps(wptr + wstep*2), v, vs2);
vs3 = _mm256_fmadd_ps(_mm256_loadu_ps(wptr + wstep*3), v, vs3);
vs4 = _mm256_fmadd_ps(_mm256_loadu_ps(wptr + wstep*4), v, vs4);
vs5 = _mm256_fmadd_ps(_mm256_loadu_ps(wptr + wstep*5), v, vs5);
vs6 = _mm256_fmadd_ps(_mm256_loadu_ps(wptr + wstep*6), v, vs6);
vs7 = _mm256_fmadd_ps(_mm256_loadu_ps(wptr + wstep*7), v, vs7);
}
if (k != vecsize) {
// Tail
k = vecsize - 8;
wptr = weights + i * wstep + k;
__m256 v = _mm256_loadu_ps(vec + k);
v = _mm256_and_ps(v, tailMask);
vs0 = _mm256_fmadd_ps(_mm256_and_ps(_mm256_loadu_ps(wptr), tailMask), v, vs0);
vs1 = _mm256_fmadd_ps(_mm256_and_ps(_mm256_loadu_ps(wptr + wstep), tailMask), v, vs1);
vs2 = _mm256_fmadd_ps(_mm256_and_ps(_mm256_loadu_ps(wptr + wstep * 2), tailMask), v, vs2);
vs3 = _mm256_fmadd_ps(_mm256_and_ps(_mm256_loadu_ps(wptr + wstep * 3), tailMask), v, vs3);
vs4 = _mm256_fmadd_ps(_mm256_and_ps(_mm256_loadu_ps(wptr + wstep * 4), tailMask), v, vs4);
vs5 = _mm256_fmadd_ps(_mm256_and_ps(_mm256_loadu_ps(wptr + wstep * 5), tailMask), v, vs5);
vs6 = _mm256_fmadd_ps(_mm256_and_ps(_mm256_loadu_ps(wptr + wstep * 6), tailMask), v, vs6);
vs7 = _mm256_fmadd_ps(_mm256_and_ps(_mm256_loadu_ps(wptr + wstep * 7), tailMask), v, vs7);
}
__m256 s0 = _mm256_hadd_ps(_mm256_hadd_ps(vs0, vs1), _mm256_hadd_ps(vs2, vs3));
__m256 s1 = _mm256_hadd_ps(_mm256_hadd_ps(vs4, vs5), _mm256_hadd_ps(vs6, vs7));
s0 = _mm256_add_ps(s0, _mm256_permute2f128_ps(s0, s0, 1));
s1 = _mm256_add_ps(s1, _mm256_permute2f128_ps(s1, s1, 1));
s0 = _mm256_add_ps(s0, _mm256_castps128_ps256(_mm_loadu_ps(bias + i)));
s1 = _mm256_add_ps(s1, _mm256_castps128_ps256(_mm_loadu_ps(bias + i + 4)));
_mm_storeu_ps(dst + i, _mm256_castps256_ps128(s0));
_mm_storeu_ps(dst + i + 4, _mm256_castps256_ps128(s1));
}
float temp = 0.f;
for( ; i < nvecs; i++ )
{
const float* wptr = weights + i*wstep;
__m256 vs0 = _mm256_setzero_ps();
int k = 0;
for( ; k <= vecsize-8; k += 8, wptr += 8 )
{
__m256 v = _mm256_loadu_ps(vec + k);
vs0 = _mm256_fmadd_ps(_mm256_loadu_ps(wptr), v, vs0);
}
if (k != vecsize) {
// Tail
k = vecsize - 8;
wptr = weights + i * wstep + k;
__m256 v = _mm256_loadu_ps(vec + k);
v = _mm256_and_ps(v, tailMask);
vs0 = _mm256_fmadd_ps(_mm256_and_ps(_mm256_loadu_ps(wptr), tailMask), v, vs0);
}
__m256 s0 = _mm256_hadd_ps(_mm256_hadd_ps(vs0, vs0), vs0);
s0 = _mm256_add_ps(s0, _mm256_permute2f128_ps(s0, s0, 1));
_mm_store_ss(&temp, _mm256_castps256_ps128(s0));
dst[i] = temp + bias[i];
}
_mm256_zeroupper();
}
void fastGEMM( const float* aptr, size_t astep, const float* bptr,
size_t bstep, float* cptr, size_t cstep,
int ma, int na, int nb )
{
int n = 0;
#if CV_AVX512_SKX // AVX512VL is necessary to avoid register spilling
for( ; n <= nb - 32; n += 32 )
{
for( int m = 0; m < ma; m += 4 )
{
const float* aptr0 = aptr + astep*m;
const float* aptr1 = aptr + astep*std::min(m+1, ma-1);
const float* aptr2 = aptr + astep*std::min(m+2, ma-1);
const float* aptr3 = aptr + astep*std::min(m+3, ma-1);
float* cptr0 = cptr + cstep*m;
float* cptr1 = cptr + cstep*std::min(m+1, ma-1);
float* cptr2 = cptr + cstep*std::min(m+2, ma-1);
float* cptr3 = cptr + cstep*std::min(m+3, ma-1);
__m512 d00 = _mm512_setzero_ps(), d01 = _mm512_setzero_ps();
__m512 d10 = _mm512_setzero_ps(), d11 = _mm512_setzero_ps();
__m512 d20 = _mm512_setzero_ps(), d21 = _mm512_setzero_ps();
__m512 d30 = _mm512_setzero_ps(), d31 = _mm512_setzero_ps();
for( int k = 0; k < na; k++ )
{
__m512 a0 = _mm512_set1_ps(aptr0[k]);
__m512 a1 = _mm512_set1_ps(aptr1[k]);
__m512 a2 = _mm512_set1_ps(aptr2[k]);
__m512 a3 = _mm512_set1_ps(aptr3[k]);
__m512 b0 = _mm512_loadu_ps(bptr + k*bstep + n);
__m512 b1 = _mm512_loadu_ps(bptr + k*bstep + n + 16);
d00 = _mm512_fmadd_ps(a0, b0, d00);
d01 = _mm512_fmadd_ps(a0, b1, d01);
d10 = _mm512_fmadd_ps(a1, b0, d10);
d11 = _mm512_fmadd_ps(a1, b1, d11);
d20 = _mm512_fmadd_ps(a2, b0, d20);
d21 = _mm512_fmadd_ps(a2, b1, d21);
d30 = _mm512_fmadd_ps(a3, b0, d30);
d31 = _mm512_fmadd_ps(a3, b1, d31);
}
_mm512_storeu_ps(cptr0 + n, d00);
_mm512_storeu_ps(cptr0 + n + 16, d01);
_mm512_storeu_ps(cptr1 + n, d10);
_mm512_storeu_ps(cptr1 + n + 16, d11);
_mm512_storeu_ps(cptr2 + n, d20);
_mm512_storeu_ps(cptr2 + n + 16, d21);
_mm512_storeu_ps(cptr3 + n, d30);
_mm512_storeu_ps(cptr3 + n + 16, d31);
}
}
#endif
for( ; n <= nb - 16; n += 16 )
{
for( int m = 0; m < ma; m += 4 )
{
const float* aptr0 = aptr + astep*m;
const float* aptr1 = aptr + astep*std::min(m+1, ma-1);
const float* aptr2 = aptr + astep*std::min(m+2, ma-1);
const float* aptr3 = aptr + astep*std::min(m+3, ma-1);
float* cptr0 = cptr + cstep*m;
float* cptr1 = cptr + cstep*std::min(m+1, ma-1);
float* cptr2 = cptr + cstep*std::min(m+2, ma-1);
float* cptr3 = cptr + cstep*std::min(m+3, ma-1);
__m256 d00 = _mm256_setzero_ps(), d01 = _mm256_setzero_ps();
__m256 d10 = _mm256_setzero_ps(), d11 = _mm256_setzero_ps();
__m256 d20 = _mm256_setzero_ps(), d21 = _mm256_setzero_ps();
__m256 d30 = _mm256_setzero_ps(), d31 = _mm256_setzero_ps();
for( int k = 0; k < na; k++ )
{
__m256 a0 = _mm256_set1_ps(aptr0[k]);
__m256 a1 = _mm256_set1_ps(aptr1[k]);
__m256 a2 = _mm256_set1_ps(aptr2[k]);
__m256 a3 = _mm256_set1_ps(aptr3[k]);
__m256 b0 = _mm256_loadu_ps(bptr + k*bstep + n);
__m256 b1 = _mm256_loadu_ps(bptr + k*bstep + n + 8);
d00 = _mm256_fmadd_ps(a0, b0, d00);
d01 = _mm256_fmadd_ps(a0, b1, d01);
d10 = _mm256_fmadd_ps(a1, b0, d10);
d11 = _mm256_fmadd_ps(a1, b1, d11);
d20 = _mm256_fmadd_ps(a2, b0, d20);
d21 = _mm256_fmadd_ps(a2, b1, d21);
d30 = _mm256_fmadd_ps(a3, b0, d30);
d31 = _mm256_fmadd_ps(a3, b1, d31);
}
_mm256_storeu_ps(cptr0 + n, d00);
_mm256_storeu_ps(cptr0 + n + 8, d01);
_mm256_storeu_ps(cptr1 + n, d10);
_mm256_storeu_ps(cptr1 + n + 8, d11);
_mm256_storeu_ps(cptr2 + n, d20);
_mm256_storeu_ps(cptr2 + n + 8, d21);
_mm256_storeu_ps(cptr3 + n, d30);
_mm256_storeu_ps(cptr3 + n + 8, d31);
}
}
for( ; n < nb; n++ )
{
for( int m = 0; m < ma; m++ )
{
const float* aptr0 = aptr + astep*m;
float* cptr0 = cptr + cstep*m;
float d0 = 0.f;
for( int k = 0; k < na; k++ )
d0 += aptr0[k]*bptr[k*bstep + n];
cptr0[n] = d0;
}
}
_mm256_zeroupper();
}
#endif // CV_CPU_OPTIMIZATION_DECLARATIONS_ONLY
#if !defined(CV_CPU_OPTIMIZATION_DECLARATIONS_ONLY) && CV_RVV
void fastGEMM( const float* aptr, size_t astep, const float* bptr,
size_t bstep, float* cptr, size_t cstep,
int ma, int na, int nb )
{
int avl = nb, vl;
for(int n = 0; n < nb; n += vl, avl -= vl)
{
vl = vsetvl_e32m4(avl);
for( int m = 0; m < ma; m += 7 )
{
const float* aptr0 = aptr + astep*m;
const float* aptr1 = aptr + astep*std::min(m+1, ma-1);
const float* aptr2 = aptr + astep*std::min(m+2, ma-1);
const float* aptr3 = aptr + astep*std::min(m+3, ma-1);
const float* aptr4 = aptr + astep*std::min(m+4, ma-1);
const float* aptr5 = aptr + astep*std::min(m+5, ma-1);
const float* aptr6 = aptr + astep*std::min(m+6, ma-1);
float* cptr0 = cptr + cstep*m;
float* cptr1 = cptr + cstep*std::min(m+1, ma-1);
float* cptr2 = cptr + cstep*std::min(m+2, ma-1);
float* cptr3 = cptr + cstep*std::min(m+3, ma-1);
float* cptr4 = cptr + cstep*std::min(m+4, ma-1);
float* cptr5 = cptr + cstep*std::min(m+5, ma-1);
float* cptr6 = cptr + cstep*std::min(m+6, ma-1);
vfloat32m4_t d0 = vfmv_v_f_f32m4(0, vl);
vfloat32m4_t d1 = vfmv_v_f_f32m4(0, vl);
vfloat32m4_t d2 = vfmv_v_f_f32m4(0, vl);
vfloat32m4_t d3 = vfmv_v_f_f32m4(0, vl);
vfloat32m4_t d4 = vfmv_v_f_f32m4(0, vl);
vfloat32m4_t d5 = vfmv_v_f_f32m4(0, vl);
vfloat32m4_t d6 = vfmv_v_f_f32m4(0, vl);
for( int k = 0; k < na; k++ )
{
float a0 = aptr0[k];
float a1 = aptr1[k];
float a2 = aptr2[k];
float a3 = aptr3[k];
float a4 = aptr4[k];
float a5 = aptr5[k];
float a6 = aptr6[k];
vfloat32m4_t b = vle32_v_f32m4(bptr + k*bstep + n, vl);
d0 = vfmacc_vf_f32m4(d0, a0, b, vl);
d1 = vfmacc_vf_f32m4(d1, a1, b, vl);
d2 = vfmacc_vf_f32m4(d2, a2, b, vl);
d3 = vfmacc_vf_f32m4(d3, a3, b, vl);
d4 = vfmacc_vf_f32m4(d4, a4, b, vl);
d5 = vfmacc_vf_f32m4(d5, a5, b, vl);
d6 = vfmacc_vf_f32m4(d6, a6, b, vl);
}
vse32_v_f32m4(cptr0 + n, d0, vl);
vse32_v_f32m4(cptr1 + n, d1, vl);
vse32_v_f32m4(cptr2 + n, d2, vl);
vse32_v_f32m4(cptr3 + n, d3, vl);
vse32_v_f32m4(cptr4 + n, d4, vl);
vse32_v_f32m4(cptr5 + n, d5, vl);
vse32_v_f32m4(cptr6 + n, d6, vl);
}
}
}
void fastGEMM1T( const float* vec, const float* weights,
size_t wstep, const float* bias,
float* dst, int nvecs, int vecsize )
{
const int vlm2 = vsetvlmax_e32m2();
int i = 0;
for( ; i <= nvecs - 15; i += 15 )
{
const float* wptr = weights + i*wstep;
vfloat32m2_t
vs0 = vfmv_v_f_f32m2(0, vlm2), vs1 = vfmv_v_f_f32m2(0, vlm2), vs2 = vfmv_v_f_f32m2(0, vlm2),
vs3 = vfmv_v_f_f32m2(0, vlm2), vs4 = vfmv_v_f_f32m2(0, vlm2), vs5 = vfmv_v_f_f32m2(0, vlm2),
vs6 = vfmv_v_f_f32m2(0, vlm2), vs7 = vfmv_v_f_f32m2(0, vlm2), vs8 = vfmv_v_f_f32m2(0, vlm2),
vs9 = vfmv_v_f_f32m2(0, vlm2), vs10 = vfmv_v_f_f32m2(0, vlm2), vs11 = vfmv_v_f_f32m2(0, vlm2),
vs12 = vfmv_v_f_f32m2(0, vlm2), vs13 = vfmv_v_f_f32m2(0, vlm2), vs14 = vfmv_v_f_f32m2(0, vlm2);
int avl = vecsize, vl;
for(int k = 0 ; k < vecsize; k += vl, wptr += vl, avl -= vl)
{
vl = vsetvl_e32m2(avl);
vfloat32m2_t v = vle32_v_f32m2(vec + k, vl);
vs0 = vfmacc_vv_f32m2(vs0, vle32_v_f32m2(wptr, vl), v, vl);
vs1 = vfmacc_vv_f32m2(vs1, vle32_v_f32m2(wptr + wstep, vl), v, vl);
vs2 = vfmacc_vv_f32m2(vs2, vle32_v_f32m2(wptr + wstep*2, vl), v, vl);
vs3 = vfmacc_vv_f32m2(vs3, vle32_v_f32m2(wptr + wstep*3, vl), v, vl);
vs4 = vfmacc_vv_f32m2(vs4, vle32_v_f32m2(wptr + wstep*4, vl), v, vl);
vs5 = vfmacc_vv_f32m2(vs5, vle32_v_f32m2(wptr + wstep*5, vl), v, vl);
vs6 = vfmacc_vv_f32m2(vs6, vle32_v_f32m2(wptr + wstep*6, vl), v, vl);
vs7 = vfmacc_vv_f32m2(vs7, vle32_v_f32m2(wptr + wstep*7, vl), v, vl);
vs8 = vfmacc_vv_f32m2(vs8, vle32_v_f32m2(wptr + wstep*8, vl), v, vl);
vs9 = vfmacc_vv_f32m2(vs9, vle32_v_f32m2(wptr + wstep*9, vl), v, vl);
vs10 = vfmacc_vv_f32m2(vs10, vle32_v_f32m2(wptr + wstep*10, vl), v, vl);
vs11 = vfmacc_vv_f32m2(vs11, vle32_v_f32m2(wptr + wstep*11, vl), v, vl);
vs12 = vfmacc_vv_f32m2(vs12, vle32_v_f32m2(wptr + wstep*12, vl), v, vl);
vs13 = vfmacc_vv_f32m2(vs13, vle32_v_f32m2(wptr + wstep*13, vl), v, vl);
vs14 = vfmacc_vv_f32m2(vs14, vle32_v_f32m2(wptr + wstep*14, vl), v, vl);
}
// Calculate the sum of each vector
float sum[15];
vfloat32m1_t zero = vfmv_v_f_f32m1(0, vlm2);
sum[0] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs0, zero, vlm2));
sum[1] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs1, zero, vlm2));
sum[2] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs2, zero, vlm2));
sum[3] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs3, zero, vlm2));
sum[4] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs4, zero, vlm2));
sum[5] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs5, zero, vlm2));
sum[6] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs6, zero, vlm2));
sum[7] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs7, zero, vlm2));
sum[8] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs8, zero, vlm2));
sum[9] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs9, zero, vlm2));
sum[10] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs10, zero, vlm2));
sum[11] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs11, zero, vlm2));
sum[12] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs12, zero, vlm2));
sum[13] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs13, zero, vlm2));
sum[14] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs14, zero, vlm2));
vfloat32m4_t s0 = vfadd_vv_f32m4(vle32_v_f32m4(sum, 15), vle32_v_f32m4(bias + i, 15), 15);
vse32_v_f32m4(dst + i, s0, 15);
}
int unroll_tail = nvecs - i;
if (unroll_tail > 0)
{
const float* wptr = weights + i*wstep;
vfloat32m2_t
vs0 = vfmv_v_f_f32m2(0, vlm2), vs1 = vfmv_v_f_f32m2(0, vlm2), vs2 = vfmv_v_f_f32m2(0, vlm2),
vs3 = vfmv_v_f_f32m2(0, vlm2), vs4 = vfmv_v_f_f32m2(0, vlm2), vs5 = vfmv_v_f_f32m2(0, vlm2),
vs6 = vfmv_v_f_f32m2(0, vlm2), vs7 = vfmv_v_f_f32m2(0, vlm2), vs8 = vfmv_v_f_f32m2(0, vlm2),
vs9 = vfmv_v_f_f32m2(0, vlm2), vs10 = vfmv_v_f_f32m2(0, vlm2), vs11 = vfmv_v_f_f32m2(0, vlm2),
vs12 = vfmv_v_f_f32m2(0, vlm2), vs13 = vfmv_v_f_f32m2(0, vlm2);
int avl = vecsize, vl;
for(int k = 0; k < vecsize; k += vl, wptr += vl, avl -= vl)
{
vl = vsetvl_e32m2(avl);
vfloat32m2_t v = vle32_v_f32m2(vec + k, vl);
vs0 = vfmacc_vv_f32m2(vs0, vle32_v_f32m2(wptr, vl), v, vl);
vs1 = vfmacc_vv_f32m2(vs1, vle32_v_f32m2(wptr + wstep*std::min(1, unroll_tail-1), vl), v, vl);
vs2 = vfmacc_vv_f32m2(vs2, vle32_v_f32m2(wptr + wstep*std::min(2, unroll_tail-1), vl), v, vl);
vs3 = vfmacc_vv_f32m2(vs3, vle32_v_f32m2(wptr + wstep*std::min(3, unroll_tail-1), vl), v, vl);
vs4 = vfmacc_vv_f32m2(vs4, vle32_v_f32m2(wptr + wstep*std::min(4, unroll_tail-1), vl), v, vl);
vs5 = vfmacc_vv_f32m2(vs5, vle32_v_f32m2(wptr + wstep*std::min(5, unroll_tail-1), vl), v, vl);
vs6 = vfmacc_vv_f32m2(vs6, vle32_v_f32m2(wptr + wstep*std::min(6, unroll_tail-1), vl), v, vl);
vs7 = vfmacc_vv_f32m2(vs7, vle32_v_f32m2(wptr + wstep*std::min(7, unroll_tail-1), vl), v, vl);
vs8 = vfmacc_vv_f32m2(vs8, vle32_v_f32m2(wptr + wstep*std::min(8, unroll_tail-1), vl), v, vl);
vs9 = vfmacc_vv_f32m2(vs9, vle32_v_f32m2(wptr + wstep*std::min(9, unroll_tail-1), vl), v, vl);
vs10 = vfmacc_vv_f32m2(vs10, vle32_v_f32m2(wptr + wstep*std::min(10, unroll_tail-1), vl), v, vl);
vs11 = vfmacc_vv_f32m2(vs11, vle32_v_f32m2(wptr + wstep*std::min(11, unroll_tail-1), vl), v, vl);
vs12 = vfmacc_vv_f32m2(vs12, vle32_v_f32m2(wptr + wstep*std::min(12, unroll_tail-1), vl), v, vl);
vs13 = vfmacc_vv_f32m2(vs13, vle32_v_f32m2(wptr + wstep*std::min(13, unroll_tail-1), vl), v, vl);
}
// Calculate the sum of each vector
float sum[14];
vfloat32m1_t zero = vfmv_v_f_f32m1(0, vlm2);
sum[0] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs0, zero, vlm2));
sum[1] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs1, zero, vlm2));
sum[2] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs2, zero, vlm2));
sum[3] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs3, zero, vlm2));
sum[4] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs4, zero, vlm2));
sum[5] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs5, zero, vlm2));
sum[6] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs6, zero, vlm2));
sum[7] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs7, zero, vlm2));
sum[8] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs8, zero, vlm2));
sum[9] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs9, zero, vlm2));
sum[10] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs10, zero, vlm2));
sum[11] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs11, zero, vlm2));
sum[12] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs12, zero, vlm2));
sum[13] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m2_f32m1(zero, vs13, zero, vlm2));
vfloat32m4_t s0 = vfadd_vv_f32m4(vle32_v_f32m4(sum, unroll_tail), vle32_v_f32m4(bias + i, unroll_tail), unroll_tail);
vse32_v_f32m4(dst + i, s0, unroll_tail);
}
}
enum { FASCONV_BASE_VECSZ = 8 };
void fastConv( const float* weights, size_t wstep, const float* bias,
const float* rowbuf, float* output, const int* outShape,
int blockSize, int vecsize, int vecsize_aligned,
const float* relu, bool initOutput )
{
const int vlm1 = vsetvlmax_e32m1();
int outCn = outShape[1];
size_t outPlaneSize = outShape[2]*outShape[3];
// now compute dot product of the weights
// and im2row-transformed part of the tensor
for( int i = 0; i < outCn; i += 3 )
{
int unroll_tail = FASCONV_BASE_VECSZ;
const float* wptr0 = weights + i*wstep;
const float* wptr1 = wptr0 + wstep;
const float* wptr2 = wptr1 + wstep;
float* outptr0 = output + i*outPlaneSize;
float* outptr1 = outptr0 + outPlaneSize;
float* outptr2 = outptr1 + outPlaneSize;
float bias0 = bias[i], bias1 = bias[i+1], bias2 = bias[i+2];
if( i+2 >= outCn )
{
wptr2 = wptr1;
outptr2 = outptr1;
bias2 = bias1;
if( i+1 >= outCn )
{
wptr2 = wptr1 = wptr0;
outptr2 = outptr1 = outptr0;
bias2 = bias1 = bias0;
}
}
int j = 0;
for( ; j < blockSize; j += FASCONV_BASE_VECSZ )
{
const float* rptr = rowbuf + j*vecsize_aligned;
const float *rptr1 = rptr + vecsize_aligned*1,
*rptr2 = rptr + vecsize_aligned*2,
*rptr3 = rptr + vecsize_aligned*3,
*rptr4 = rptr + vecsize_aligned*4,
*rptr5 = rptr + vecsize_aligned*5,
*rptr6 = rptr + vecsize_aligned*6,
*rptr7 = rptr + vecsize_aligned*7;
if (j + FASCONV_BASE_VECSZ > blockSize)
{
unroll_tail = blockSize - j;
rptr1 = rptr + vecsize_aligned*std::min(1, unroll_tail-1),
rptr2 = rptr + vecsize_aligned*std::min(2, unroll_tail-1),
rptr3 = rptr + vecsize_aligned*std::min(3, unroll_tail-1),
rptr4 = rptr + vecsize_aligned*std::min(4, unroll_tail-1),
rptr5 = rptr + vecsize_aligned*std::min(5, unroll_tail-1),
rptr6 = rptr + vecsize_aligned*std::min(6, unroll_tail-1),
rptr7 = rptr + vecsize_aligned*std::min(7, unroll_tail-1);
}
int vl, avl = vecsize;
vfloat32m1_t
vs00 = vfmv_v_f_f32m1(0, vlm1), vs10 = vfmv_v_f_f32m1(0, vlm1), vs20 = vfmv_v_f_f32m1(0, vlm1),
vs01 = vfmv_v_f_f32m1(0, vlm1), vs11 = vfmv_v_f_f32m1(0, vlm1), vs21 = vfmv_v_f_f32m1(0, vlm1),
vs02 = vfmv_v_f_f32m1(0, vlm1), vs12 = vfmv_v_f_f32m1(0, vlm1), vs22 = vfmv_v_f_f32m1(0, vlm1),
vs03 = vfmv_v_f_f32m1(0, vlm1), vs13 = vfmv_v_f_f32m1(0, vlm1), vs23 = vfmv_v_f_f32m1(0, vlm1),
vs04 = vfmv_v_f_f32m1(0, vlm1), vs14 = vfmv_v_f_f32m1(0, vlm1), vs24 = vfmv_v_f_f32m1(0, vlm1),
vs05 = vfmv_v_f_f32m1(0, vlm1), vs15 = vfmv_v_f_f32m1(0, vlm1), vs25 = vfmv_v_f_f32m1(0, vlm1),
vs06 = vfmv_v_f_f32m1(0, vlm1), vs16 = vfmv_v_f_f32m1(0, vlm1), vs26 = vfmv_v_f_f32m1(0, vlm1),
vs07 = vfmv_v_f_f32m1(0, vlm1), vs17 = vfmv_v_f_f32m1(0, vlm1), vs27 = vfmv_v_f_f32m1(0, vlm1);
for (int k = 0; k < vecsize; k += vl, avl -= vl)
{
vl = vsetvl_e32m1(avl);
vfloat32m1_t w0 = vle32_v_f32m1(wptr0 + k, vl);
vfloat32m1_t w1 = vle32_v_f32m1(wptr1 + k, vl);
vfloat32m1_t w2 = vle32_v_f32m1(wptr2 + k, vl);
vfloat32m1_t r0 = vle32_v_f32m1(rptr, vl);
vs00 = vfmacc_vv_f32m1(vs00, w0, r0, vl);
vs10 = vfmacc_vv_f32m1(vs10, w1, r0, vl);
vs20 = vfmacc_vv_f32m1(vs20, w2, r0, vl);
r0 = vle32_v_f32m1(rptr1, vl);
vs01 = vfmacc_vv_f32m1(vs01, w0, r0, vl);
vs11 = vfmacc_vv_f32m1(vs11, w1, r0, vl);
vs21 = vfmacc_vv_f32m1(vs21, w2, r0, vl);
r0 = vle32_v_f32m1(rptr2, vl);
vs02 = vfmacc_vv_f32m1(vs02, w0, r0, vl);
vs12 = vfmacc_vv_f32m1(vs12, w1, r0, vl);
vs22 = vfmacc_vv_f32m1(vs22, w2, r0, vl);
r0 = vle32_v_f32m1(rptr3, vl);
vs03 = vfmacc_vv_f32m1(vs03, w0, r0, vl);
vs13 = vfmacc_vv_f32m1(vs13, w1, r0, vl);
vs23 = vfmacc_vv_f32m1(vs23, w2, r0, vl);
r0 = vle32_v_f32m1(rptr4, vl);
vs04 = vfmacc_vv_f32m1(vs04, w0, r0, vl);
vs14 = vfmacc_vv_f32m1(vs14, w1, r0, vl);
vs24 = vfmacc_vv_f32m1(vs24, w2, r0, vl);
r0 = vle32_v_f32m1(rptr5, vl);
vs05 = vfmacc_vv_f32m1(vs05, w0, r0, vl);
vs15 = vfmacc_vv_f32m1(vs15, w1, r0, vl);
vs25 = vfmacc_vv_f32m1(vs25, w2, r0, vl);
r0 = vle32_v_f32m1(rptr6, vl);
vs06 = vfmacc_vv_f32m1(vs06, w0, r0, vl);
vs16 = vfmacc_vv_f32m1(vs16, w1, r0, vl);
vs26 = vfmacc_vv_f32m1(vs26, w2, r0, vl);
r0 = vle32_v_f32m1(rptr7, vl);
vs07 = vfmacc_vv_f32m1(vs07, w0, r0, vl);
vs17 = vfmacc_vv_f32m1(vs17, w1, r0, vl);
vs27 = vfmacc_vv_f32m1(vs27, w2, r0, vl);
rptr += vl; rptr1 += vl; rptr2 += vl; rptr3 += vl;
rptr4 += vl; rptr5 += vl; rptr6 += vl; rptr7 += vl;
}
// compute sum of each vs
vfloat32m1_t zero = vfmv_v_f_f32m1(0, vlm1);
// unroll_tail(vl) is required here to be at least FASCONV_BASE_VECSZ, aka 8.
float sum0[FASCONV_BASE_VECSZ], sum1[FASCONV_BASE_VECSZ], sum2[FASCONV_BASE_VECSZ];
sum0[0] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs00, zero, vlm1));
sum0[1] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs01, zero, vlm1));
sum0[2] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs02, zero, vlm1));
sum0[3] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs03, zero, vlm1));
sum0[4] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs04, zero, vlm1));
sum0[5] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs05, zero, vlm1));
sum0[6] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs06, zero, vlm1));
sum0[7] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs07, zero, vlm1));
sum1[0] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs10, zero, vlm1));
sum1[1] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs11, zero, vlm1));
sum1[2] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs12, zero, vlm1));
sum1[3] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs13, zero, vlm1));
sum1[4] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs14, zero, vlm1));
sum1[5] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs15, zero, vlm1));
sum1[6] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs16, zero, vlm1));
sum1[7] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs17, zero, vlm1));
sum2[0] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs20, zero, vlm1));
sum2[1] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs21, zero, vlm1));
sum2[2] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs22, zero, vlm1));
sum2[3] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs23, zero, vlm1));
sum2[4] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs24, zero, vlm1));
sum2[5] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs25, zero, vlm1));
sum2[6] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs26, zero, vlm1));
sum2[7] = vfmv_f_s_f32m1_f32(vfredosum_vs_f32m1_f32m1(zero, vs27, zero, vlm1));
// if VLEN = 128, so LMUL = 2 for unroll_tail(vl) = 8.
// otherwise, VLEN >=256, we only use fist 8 element of the vReg.
vfloat32m2_t s0, s1, s2;
if( initOutput )
{
s0 = vfmv_v_f_f32m2(bias0, unroll_tail);
s1 = vfmv_v_f_f32m2(bias1, unroll_tail);
s2 = vfmv_v_f_f32m2(bias2, unroll_tail);
}
else
{
s0 = vle32_v_f32m2(outptr0 + j, unroll_tail);
s1 = vle32_v_f32m2(outptr1 + j, unroll_tail);
s2 = vle32_v_f32m2(outptr2 + j, unroll_tail);
}
s0 = vfadd_vv_f32m2(vle32_v_f32m2(sum0, unroll_tail), s0, unroll_tail);
s1 = vfadd_vv_f32m2(vle32_v_f32m2(sum1, unroll_tail), s1, unroll_tail);
s2 = vfadd_vv_f32m2(vle32_v_f32m2(sum2, unroll_tail), s2, unroll_tail);
if( relu )
{
float r0 = relu[i], r1 = relu[i+1], r2 = relu[i+2];
if( i+2 >= outCn )
{
r2 = r1;
if( i+1 >= outCn )
r2 = r1 = r0;
}
vbool16_t m0 = vmfgt_vf_f32m2_b16(s0, 0, unroll_tail);
vbool16_t m1 = vmfgt_vf_f32m2_b16(s1, 0, unroll_tail);
vbool16_t m2 = vmfgt_vf_f32m2_b16(s2, 0, unroll_tail);
s0 = vmerge_vvm_f32m2(m0, vfmul_vf_f32m2(s0, r0, unroll_tail), s0, unroll_tail);
s1 = vmerge_vvm_f32m2(m1, vfmul_vf_f32m2(s1, r1, unroll_tail), s1, unroll_tail);
s2 = vmerge_vvm_f32m2(m2, vfmul_vf_f32m2(s2, r2, unroll_tail), s2, unroll_tail);
}
vse32_v_f32m2(outptr0 + j, s0, unroll_tail);
vse32_v_f32m2(outptr1 + j, s1, unroll_tail);
vse32_v_f32m2(outptr2 + j, s2, unroll_tail);
}
}
}
/*
Example for load_deinterleave:
input: ptr[16] = {1,2,3, ... ,14,15,16}
output: a = {1, 3, 5, 7, 9, 11, 13, 15}
output: b = {2, 4, 6, 8,10, 12, 14, 16}
*/
static inline void vfloat32m2_load_deinterleave(const float* ptr, vfloat32m2_t& a, vfloat32m2_t& b, int vl)
{
vuint64m4_t mask = vmv_v_x_u64m4(1,vl*2);
vuint32m4_t mask_re = vreinterpret_v_u64m4_u32m4(mask);
vbool8_t mask0 = vmseq_vx_u32m4_b8 (mask_re, 1, vl*2);
vbool8_t mask1 = vmseq_vx_u32m4_b8 (mask_re, 0, vl*2);
vfloat32m4_t tempa = vundefined_f32m4(), tempb = vundefined_f32m4();
vfloat32m4_t vw = vle32_v_f32m4(ptr, vl*2);
tempa = vcompress_vm_f32m4(mask0, tempa, vw, vl*2);
tempb = vcompress_vm_f32m4(mask1, tempb, vw, vl*2);
/* The following instructions have not to be supported by the GNU toolchain.
So we temporarily use store and load instead.
// a = vlmul_trunc_v_f32m4_f32m2(tempa);
// b = vlmul_trunc_v_f32m4_f32m2(tempb);
*/
cv::AutoBuffer<float> cvBuffer(sizeof(float)*vl*2);
float* buffer = (float*)cvBuffer.data();
vse32_v_f32m4(buffer, tempa, vl);
a = vle32_v_f32m2(buffer, vl);
vse32_v_f32m4(buffer, tempb, vl);
b = vle32_v_f32m2(buffer, vl);
}
void fastDepthwiseConv( const float* wptr,
int kernel_h, int kernel_w,
int stride_h, int stride_w,
int dilation_h, int dilation_w,
int pad_t, int pad_l,
const float* biasptr, const float* relu,
const float* inptr_,
int height, int width,
float* outptr_,
int out_d, int outH, int outW )
{
int vl;
const float w00_ = wptr[0], w01_ = wptr[1], w02_ = wptr[2],
w10 = wptr[3], w11 = wptr[4], w12 = wptr[5],
w20_ = wptr[6], w21_ = wptr[7], w22_ = wptr[8];
int outW1 = std::min(outW, (width - dilation_w*(kernel_w - 1) + pad_l)/stride_w);
float relu_coeff = relu ? relu[out_d] : 1.f, bias = biasptr[out_d];
for (int out_i = 0; out_i < outH; out_i++)
{
int in_i = out_i * stride_h - pad_t, out_j = 0;
const float* imgptr0 = inptr_ + in_i*width;
const float* imgptr1 = imgptr0 + dilation_h*width;
const float* imgptr2 = imgptr0 + (dilation_h*2)*width;
float out, w00 = w00_, w01 = w01_, w02 = w02_;
float w20 = w20_, w21 = w21_, w22 = w22_;
if (in_i < 0)
{
w00 = w01 = w02 = 0.f;
imgptr0 = imgptr1;
}
else if (in_i + dilation_h*(kernel_h-1) >= height)
{
w20 = w21 = w22 = 0.f;
imgptr2 = imgptr1;
}
float* outptr = outptr_ + out_i*outW;
if (pad_l > 0)
{
out = imgptr0[0]*w01 + imgptr0[dilation_w]*w02 +
imgptr1[0]*w11 + imgptr1[dilation_w]*w12 +
imgptr2[0]*w21 + imgptr2[dilation_w]*w22 + bias;
if (relu)
out = out > 0.f ? out : out*relu_coeff;
outptr[0] = out;
out_j = 1;
}
if (stride_w == 1 || (stride_w == 2 && dilation_w == 1))
{
int avl = outW1 - out_j;
if( stride_w == 1 )
for( ; out_j < outW1; out_j += vl, avl -= vl)
{
vl = vsetvl_e32m2(avl);
int in_j = out_j * stride_w - pad_l;
vfloat32m2_t v00 = vle32_v_f32m2(imgptr0 + in_j, vl),
v01 = vle32_v_f32m2(imgptr0 + in_j + dilation_w, vl),
v02 = vle32_v_f32m2(imgptr0 + in_j + dilation_w*2, vl),
v10 = vle32_v_f32m2(imgptr1 + in_j, vl),
v11 = vle32_v_f32m2(imgptr1 + in_j + dilation_w, vl),
v12 = vle32_v_f32m2(imgptr1 + in_j + dilation_w*2, vl),
v20 = vle32_v_f32m2(imgptr2 + in_j, vl),
v21 = vle32_v_f32m2(imgptr2 + in_j + dilation_w, vl),
v22 = vle32_v_f32m2(imgptr2 + in_j + dilation_w*2, vl);
vfloat32m2_t vout0 = vfmul_vf_f32m2(v00, w00, vl);
vfloat32m2_t vout1 = vfmul_vf_f32m2(v01, w01, vl);
vfloat32m2_t vout2 = vfmul_vf_f32m2(v02, w02, vl);
vout0 = vfadd_vf_f32m2(vout0, bias, vl);
vout0 = vfmacc_vf_f32m2(vout0, w10, v10, vl);
vout1 = vfmacc_vf_f32m2(vout1, w11, v11, vl);
vout2 = vfmacc_vf_f32m2(vout2, w12, v12, vl);
vout0 = vfmacc_vf_f32m2(vout0, w20, v20, vl);
vout1 = vfmacc_vf_f32m2(vout1, w21, v21, vl);
vout2 = vfmacc_vf_f32m2(vout2, w22, v22, vl);
vout0 = vfadd_vv_f32m2(vfadd_vv_f32m2(vout0, vout1, vl), vout2, vl);
if (relu)
{
vbool16_t m = vmfgt_vf_f32m2_b16(vout0, 0, vl);
vout0 = vmerge_vvm_f32m2(m, vfmul_vf_f32m2(vout0, relu_coeff, vl), vout0, vl);
}
vse32_v_f32m2(outptr + out_j, vout0, vl);
}
else //stride_w == 2 && dilation_w == 1
for( ; out_j < outW1; out_j += vl, avl -= vl)
{
vl = vsetvl_e32m2(avl);
int in_j = out_j * stride_w - pad_l;
vfloat32m2_t v00, v01, v02, v10, v11, v12, v20, v21, v22, unused;
vfloat32m2_load_deinterleave(imgptr0 + in_j, v00, v01, vl);
vfloat32m2_load_deinterleave(imgptr0 + in_j + 2, v02, unused, vl);
vfloat32m2_load_deinterleave(imgptr1 + in_j, v10, v11, vl);
vfloat32m2_load_deinterleave(imgptr1 + in_j + 2, v12, unused, vl);
vfloat32m2_load_deinterleave(imgptr2 + in_j, v20, v21, vl);
vfloat32m2_load_deinterleave(imgptr2 + in_j + 2, v22, unused, vl);
vfloat32m2_t vout0 = vfmul_vf_f32m2(v00, w00, vl);
vfloat32m2_t vout1 = vfmul_vf_f32m2(v01, w01, vl);
vfloat32m2_t vout2 = vfmul_vf_f32m2(v02, w02, vl);
vout0 = vfadd_vf_f32m2(vout0, bias, vl);
vout0 = vfmacc_vf_f32m2(vout0, w10, v10, vl);
vout1 = vfmacc_vf_f32m2(vout1, w11, v11, vl);
vout2 = vfmacc_vf_f32m2(vout2, w12, v12, vl);
vout0 = vfmacc_vf_f32m2(vout0, w20, v20, vl);
vout1 = vfmacc_vf_f32m2(vout1, w21, v21, vl);
vout2 = vfmacc_vf_f32m2(vout2, w22, v22, vl);
vout0 = vfadd_vv_f32m2(vfadd_vv_f32m2(vout0, vout1, vl), vout2, vl);
if (relu)
{
vbool16_t m = vmfgt_vf_f32m2_b16(vout0, 0, vl);
vout0 = vmerge_vvm_f32m2(m, vfmul_vf_f32m2(vout0, relu_coeff, vl), vout0, vl);
}
vse32_v_f32m2(outptr + out_j, vout0, vl);
}
}
for (; out_j < outW1; out_j++)
{
int in_j = out_j * stride_w - pad_l;
out = imgptr0[in_j]*w00 + imgptr0[in_j + dilation_w]*w01 + imgptr0[in_j + dilation_w*2]*w02 +
imgptr1[in_j]*w10 + imgptr1[in_j + dilation_w]*w11 + imgptr1[in_j + dilation_w*2]*w12 +
imgptr2[in_j]*w20 + imgptr2[in_j + dilation_w]*w21 + imgptr2[in_j + dilation_w*2]*w22 + bias;
if (relu)
out = out > 0.f ? out : out*relu_coeff;
outptr[out_j] = out;
}
for (; out_j < outW; out_j++ )
{
int in_j0 = out_j * stride_w - pad_l, in_j1 = in_j0 + dilation_w, in_j2 = in_j0 + dilation_w*2;
float s0 = 1.f, s1 = 1.f, s2 = 1.f;
if (in_j0 >= width)
{
in_j0 = 0;
s0 = 0.f;
}
if (in_j1 >= width)
{
in_j1 = 0;
s1 = 0.f;
}
if (in_j2 >= width)
{
in_j2 = 0;
s2 = 0.f;
}
out = imgptr0[in_j0]*w00*s0 + imgptr0[in_j1]*w01*s1 + imgptr0[in_j2]*w02*s2 +
imgptr1[in_j0]*w10*s0 + imgptr1[in_j1]*w11*s1 + imgptr1[in_j2]*w12*s2 +
imgptr2[in_j0]*w20*s0 + imgptr2[in_j1]*w21*s1 + imgptr2[in_j2]*w22*s2 + bias;
if (relu)
out = out > 0.f ? out : out*relu_coeff;
outptr[out_j] = out;
}
}
}
#endif // CV_RVV
#if !defined(CV_CPU_OPTIMIZATION_DECLARATIONS_ONLY) && CV_LASX
enum { FASCONV_BASE_VECSZ = 4 };
void fastConv( const float* weights, size_t wstep, const float* bias,
const float* rowbuf, float* output, const int* outShape,
int blockSize, int vecsize, int vecsize_aligned,
const float* relu, bool initOutput )
{
int outCn = outShape[1];
size_t outPlaneSize = outShape[2]*outShape[3];
float r0 = 1.f, r1 = 1.f, r2 = 1.f;
__m256 t1 = _v256_setall_ps(1.f), t2 = _v256_setall_ps(0.f);
__m128 vr0 = *(__m128*)&t1, vr1 = vr0, vr2 = vr0, z = *(__m128*)&t2;
int CV_DECL_ALIGNED(16) maskbuf[FASCONV_BASE_VECSZ] = {0};
int rsz = blockSize % FASCONV_BASE_VECSZ;
for( int i = 0; i < rsz; i++ )
maskbuf[FASCONV_BASE_VECSZ - i - 1] = -1;
__m128i mask = __lsx_vld((const float*)maskbuf, 0);
// now compute dot product of the weights
// and im2row-transformed part of the tensor
for( int i = 0; i < outCn; i += 3 )
{
const float* wptr0 = weights + i*wstep;
const float* wptr1 = wptr0 + wstep;
const float* wptr2 = wptr1 + wstep;
float* outptr0 = output + i*outPlaneSize;
float* outptr1 = outptr0 + outPlaneSize;
float* outptr2 = outptr1 + outPlaneSize;
float bias0 = bias[i], bias1 = bias[i+1], bias2 = bias[i+2];
if( i+2 >= outCn )
{
wptr2 = wptr1;
outptr2 = outptr1;
bias2 = bias1;
if( i+1 >= outCn )
{
wptr2 = wptr1 = wptr0;
outptr2 = outptr1 = outptr0;
bias2 = bias1 = bias0;
}
}
if( relu )
{
r0 = relu[i]; r1 = relu[i+1]; r2 = relu[i+2];
if( i+2 >= outCn )
{
r2 = r1;
if( i+1 >= outCn )
r2 = r1 = r0;
}
vr0 = _v256_extract_low(_v256_setall_ps(r0));
vr1 = _v256_extract_low(_v256_setall_ps(r1));
vr2 = _v256_extract_low(_v256_setall_ps(r2));
}
int j = 0;
for( ; j < blockSize; j += FASCONV_BASE_VECSZ )
{
bool tail = false;
if (j + FASCONV_BASE_VECSZ > blockSize)
{
if (j == 0)
break;
j = blockSize - FASCONV_BASE_VECSZ;
tail = true;
}
int k = 0;
const float* rptr = rowbuf + j*vecsize_aligned;
__m256i tmp;
__m256 vs00 = (__m256)__lasx_xvxor_v(tmp, tmp), vs01 = (__m256)__lasx_xvxor_v(tmp, tmp),
vs02 = (__m256)__lasx_xvxor_v(tmp, tmp), vs03 = (__m256)__lasx_xvxor_v(tmp, tmp),
vs10 = (__m256)__lasx_xvxor_v(tmp, tmp), vs11 = (__m256)__lasx_xvxor_v(tmp, tmp),
vs12 = (__m256)__lasx_xvxor_v(tmp, tmp), vs13 = (__m256)__lasx_xvxor_v(tmp, tmp),
vs20 = (__m256)__lasx_xvxor_v(tmp, tmp), vs21 = (__m256)__lasx_xvxor_v(tmp, tmp),
vs22 = (__m256)__lasx_xvxor_v(tmp, tmp), vs23 = (__m256)__lasx_xvxor_v(tmp, tmp);
for (; k < vecsize; k += 8, rptr += 8 )
{
__m256 w0 = (__m256)__lasx_xvld(wptr0 + k, 0);
__m256 w1 = (__m256)__lasx_xvld(wptr1 + k, 0);
__m256 w2 = (__m256)__lasx_xvld(wptr2 + k, 0);
__m256 r0 = (__m256)__lasx_xvld(rptr, 0);
vs00 = __lasx_xvfmadd_s(w0, r0, vs00);
vs10 = __lasx_xvfmadd_s(w1, r0, vs10);
vs20 = __lasx_xvfmadd_s(w2, r0, vs20);
r0 = (__m256)__lasx_xvld(rptr + vecsize_aligned, 0);
vs01 = __lasx_xvfmadd_s(w0, r0, vs01);
vs11 = __lasx_xvfmadd_s(w1, r0, vs11);
vs21 = __lasx_xvfmadd_s(w2, r0, vs21);
r0 = (__m256)__lasx_xvld(rptr + vecsize_aligned*2, 0);
vs02 = __lasx_xvfmadd_s(w0, r0, vs02);
vs12 = __lasx_xvfmadd_s(w1, r0, vs12);
vs22 = __lasx_xvfmadd_s(w2, r0, vs22);
r0 = (__m256)__lasx_xvld(rptr + vecsize_aligned*3, 0);
vs03 = __lasx_xvfmadd_s(w0, r0, vs03);
vs13 = __lasx_xvfmadd_s(w1, r0, vs13);
vs23 = __lasx_xvfmadd_s(w2, r0, vs23);
}
/*t0*/
__m256 vs00_perm = (__m256)__lasx_xvpermi_d(vs00, (2<<6) + (3<<4) + (0<<2) + 1);
__m256 vs00_add_2w = __lasx_xvfadd_s(vs00, vs00_perm);
__m256 tmp00_srl = (__m256)__lasx_xvsrli_d(vs00_add_2w, 32);
__m256 vs00_add_4w = __lasx_xvfadd_s(vs00_add_2w, tmp00_srl);
__m256 vs01_perm = (__m256)__lasx_xvpermi_d(vs01, (2<<6) + (3<<4) + (0<<2) + 1);
__m256 vs01_add_2w = __lasx_xvfadd_s(vs01, vs01_perm);
__m256 tmp01_srl = (__m256)__lasx_xvsrli_d(vs01_add_2w, 32);
__m256 vs01_add_4w = __lasx_xvfadd_s(vs01_add_2w, tmp01_srl);
__m256 vs02_perm = (__m256)__lasx_xvpermi_d(vs02, (2<<6) + (3<<4) + (0<<2) + 1);
__m256 vs02_add_2w = __lasx_xvfadd_s(vs02, vs02_perm);
__m256 tmp02_srl = (__m256)__lasx_xvsrli_d(vs02_add_2w, 32);
__m256 vs02_add_4w = __lasx_xvfadd_s(vs02_add_2w, tmp02_srl);
__m256 vs03_perm = (__m256)__lasx_xvpermi_d(vs03, (2<<6) + (3<<4) + (0<<2) + 1);
__m256 vs03_add_2w = __lasx_xvfadd_s(vs03, vs03_perm);
__m256 tmp03_srl = (__m256)__lasx_xvsrli_d(vs03_add_2w, 32);
__m256 vs03_add_4w = __lasx_xvfadd_s(vs03_add_2w, tmp03_srl);
__m256i vs01_vs00 = __lasx_xvpackev_w((__m256i)vs01_add_4w, (__m256i)vs00_add_4w);
__m256i vs03_vs02 = __lasx_xvpackev_w((__m256i)vs03_add_4w, (__m256i)vs02_add_4w);
__m256 t0 = (__m256)__lasx_xvpackev_d(vs03_vs02, vs01_vs00);
/*t1*/
__m256 vs10_perm = (__m256)__lasx_xvpermi_d(vs10, (2<<6) + (3<<4) + (0<<2) + 1);
__m256 vs10_add_2w = __lasx_xvfadd_s(vs10, vs10_perm);
__m256 tmp10_srl = (__m256)__lasx_xvsrli_d(vs10_add_2w, 32);
__m256 vs10_add_4w = __lasx_xvfadd_s(vs10_add_2w, tmp10_srl);
__m256 vs11_perm = (__m256)__lasx_xvpermi_d(vs11, (2<<6) + (3<<4) + (0<<2) + 1);
__m256 vs11_add_2w = __lasx_xvfadd_s(vs11, vs11_perm);
__m256 tmp11_srl = (__m256)__lasx_xvsrli_d(vs11_add_2w, 32);
__m256 vs11_add_4w = __lasx_xvfadd_s(vs11_add_2w, tmp11_srl);
__m256 vs12_perm = (__m256)__lasx_xvpermi_d(vs12, (2<<6) + (3<<4) + (0<<2) + 1);
__m256 vs12_add_2w = __lasx_xvfadd_s(vs12, vs12_perm);
__m256 tmp12_srl = (__m256)__lasx_xvsrli_d(vs12_add_2w, 32);
__m256 vs12_add_4w = __lasx_xvfadd_s(vs12_add_2w, tmp12_srl);
__m256 vs13_perm = (__m256)__lasx_xvpermi_d(vs13, (2<<6) + (3<<4) + (0<<2) + 1);
__m256 vs13_add_2w = __lasx_xvfadd_s(vs13, vs13_perm);
__m256 tmp13_srl = (__m256)__lasx_xvsrli_d(vs13_add_2w, 32);
__m256 vs13_add_4w = __lasx_xvfadd_s(vs13_add_2w, tmp13_srl);
__m256i vs11_vs10 = __lasx_xvpackev_w((__m256i)vs11_add_4w, (__m256i)vs10_add_4w);
__m256i vs13_vs12 = __lasx_xvpackev_w((__m256i)vs13_add_4w, (__m256i)vs12_add_4w);
__m256 t1 = (__m256)__lasx_xvpackev_d(vs13_vs12, vs11_vs10);
/*t2*/
__m256 vs20_perm = (__m256)__lasx_xvpermi_d(vs20, (2<<6) + (3<<4) + (0<<2) + 1);
__m256 vs20_add_2w = __lasx_xvfadd_s(vs20, vs20_perm);
__m256 tmp20_srl = (__m256)__lasx_xvsrli_d(vs20_add_2w, 32);
__m256 vs20_add_4w = __lasx_xvfadd_s(vs20_add_2w, tmp20_srl);
__m256 vs21_perm = (__m256)__lasx_xvpermi_d(vs21, (2<<6) + (3<<4) + (0<<2) + 1);
__m256 vs21_add_2w = __lasx_xvfadd_s(vs21, vs21_perm);
__m256 tmp21_srl = (__m256)__lasx_xvsrli_d(vs21_add_2w, 32);
__m256 vs21_add_4w = __lasx_xvfadd_s(vs21_add_2w, tmp21_srl);
__m256 vs22_perm = (__m256)__lasx_xvpermi_d(vs22, (2<<6) + (3<<4) + (0<<2) + 1);
__m256 vs22_add_2w = __lasx_xvfadd_s(vs22, vs22_perm);
__m256 tmp22_srl = (__m256)__lasx_xvsrli_d(vs22_add_2w, 32);
__m256 vs22_add_4w = __lasx_xvfadd_s(vs22_add_2w, tmp22_srl);
__m256 vs23_perm = (__m256)__lasx_xvpermi_d(vs23, (2<<6) + (3<<4) + (0<<2) + 1);
__m256 vs23_add_2w = __lasx_xvfadd_s(vs23, vs23_perm);
__m256 tmp23_srl = (__m256)__lasx_xvsrli_d(vs23_add_2w, 32);
__m256 vs23_add_4w = __lasx_xvfadd_s(vs23_add_2w, tmp23_srl);
__m256i vs21_vs20 = __lasx_xvpackev_w((__m256i)vs21_add_4w, (__m256i)vs20_add_4w);
__m256i vs23_vs22 = __lasx_xvpackev_w((__m256i)vs23_add_4w, (__m256i)vs22_add_4w);
__m256 t2 = (__m256)__lasx_xvpackev_d(vs23_vs22, vs21_vs20);
t0 = __lasx_xvfadd_s(t0, (__m256)__lasx_xvpermi_q(t0, t0, 1));
t1 = __lasx_xvfadd_s(t1, (__m256)__lasx_xvpermi_q(t1, t1, 1));
t2 = __lasx_xvfadd_s(t2, (__m256)__lasx_xvpermi_q(t2, t2, 1));
__m128 s0, s1, s2;
if( initOutput )
{
s0 = _v256_extract_low(_v256_setall_ps(bias0));
s1 = _v256_extract_low(_v256_setall_ps(bias1));
s2 = _v256_extract_low(_v256_setall_ps(bias2));
}
else
{
s0 = (__m128)__lsx_vld(outptr0 + j, 0);
s1 = (__m128)__lsx_vld(outptr1 + j, 0);
s2 = (__m128)__lsx_vld(outptr2 + j, 0);
}
s0 = __lsx_vfadd_s(s0, *(__m128*)&t0);
s1 = __lsx_vfadd_s(s1, *(__m128*)&t1);
s2 = __lsx_vfadd_s(s2, *(__m128*)&t2);
if( relu )
{
__m128i m0 = __lsx_vfcmp_clt_s(z, s0);
__m128i m1 = __lsx_vfcmp_clt_s(z, s1);
__m128i m2 = __lsx_vfcmp_clt_s(z, s2);
s0 = (__m128)__lsx_vbitsel_v((__m128i)__lsx_vfmul_s(s0, vr0), (__m128i)s0, m0);
s1 = (__m128)__lsx_vbitsel_v((__m128i)__lsx_vfmul_s(s1, vr1), (__m128i)s1, m1);
s2 = (__m128)__lsx_vbitsel_v((__m128i)__lsx_vfmul_s(s2, vr2), (__m128i)s2, m2);
}
if( tail )
{
s0 = (__m128)__lsx_vbitsel_v(__lsx_vld(outptr0 + j, 0), (__m128i)s0, mask);
s1 = (__m128)__lsx_vbitsel_v(__lsx_vld(outptr1 + j, 0), (__m128i)s1, mask);
s2 = (__m128)__lsx_vbitsel_v(__lsx_vld(outptr2 + j, 0), (__m128i)s2, mask);
}
__lsx_vst(s0, outptr0 + j, 0);
__lsx_vst(s1, outptr1 + j, 0);
__lsx_vst(s2, outptr2 + j, 0);
}
for( ; j <= blockSize - 2; j += 2 )
{
const float* rptr0 = rowbuf + j*vecsize_aligned;
const float* rptr1 = rowbuf + (j+1)*vecsize_aligned;
float s00, s01, s10, s11, s20, s21;
if( initOutput )
{
s00 = s01 = bias0;
s10 = s11 = bias1;
s20 = s21 = bias2;
}
else
{
s00 = outptr0[j]; s01 = outptr0[j+1];
s10 = outptr1[j]; s11 = outptr1[j+1];
s20 = outptr2[j]; s21 = outptr2[j+1];
}
for( int k = 0; k < vecsize; k++ )
{
float w0 = wptr0[k], w1 = wptr1[k], w2 = wptr2[k];
float r = rptr0[k];
s00 += w0*r; s10 += w1*r; s20 += w2*r;
r = rptr1[k];
s01 += w0*r; s11 += w1*r; s21 += w2*r;
}
if( relu )
{
s00 = s00 > 0.f ? s00 : s00*r0;
s01 = s01 > 0.f ? s01 : s01*r0;
s10 = s10 > 0.f ? s10 : s10*r1;
s11 = s11 > 0.f ? s11 : s11*r1;
s20 = s20 > 0.f ? s20 : s20*r2;
s21 = s21 > 0.f ? s21 : s21*r2;
}
outptr0[j] = s00;
outptr0[j+1] = s01;
outptr1[j] = s10;
outptr1[j+1] = s11;
outptr2[j] = s20;
outptr2[j+1] = s21;
}
for( ; j < blockSize; j++ )
{
const float* rptr0 = rowbuf + j*vecsize_aligned;
float s00, s10, s20;
if( initOutput )
{
s00 = bias0;
s10 = bias1;
s20 = bias2;
}
else
{
s00 = outptr0[j];
s10 = outptr1[j];
s20 = outptr2[j];
}
for( int k = 0; k < vecsize; k++ )
{
float w0 = wptr0[k], w1 = wptr1[k], w2 = wptr2[k];
float r = rptr0[k];
s00 += w0*r; s10 += w1*r; s20 += w2*r;
}
if( relu )
{
s00 = s00 > 0.f ? s00 : s00*r0;
s10 = s10 > 0.f ? s10 : s10*r1;
s20 = s20 > 0.f ? s20 : s20*r2;
}
outptr0[j] = s00;
outptr1[j] = s10;
outptr2[j] = s20;
}
}
}
static inline void _v256_load_deinterleave(const float* ptr, __m256& a, __m256& b)
{
__m256 t0 = (__m256)__lasx_xvld(ptr, 0);
__m256 t1 = (__m256)__lasx_xvld(ptr, 8*4);
__m256 lo = (__m256)__lasx_xvpermi_q(t0, t1, 2+0*16);
__m256 hi = (__m256)__lasx_xvpermi_q(t0, t1, 3+1*16);
a = (__m256)__lasx_xvpermi_w(hi, lo, 0x88);
b = (__m256)__lasx_xvpermi_w(hi, lo, 0xdd);
}
void fastDepthwiseConv( const float* wptr,
int kernel_h, int kernel_w,
int stride_h, int stride_w,
int dilation_h, int dilation_w,
int pad_t, int pad_l,
const float* biasptr, const float* relu,
const float* inptr_,
int height, int width,
float* outptr_,
int out_d, int outH, int outW )
{
const float w00_ = wptr[0], w01_ = wptr[1], w02_ = wptr[2],
w10 = wptr[3], w11 = wptr[4], w12 = wptr[5],
w20_ = wptr[6], w21_ = wptr[7], w22_ = wptr[8];
int outW1 = min(outW, (width - dilation_w*(kernel_w - 1) + pad_l)/stride_w);
float relu_coeff = relu ? relu[out_d] : 1.f, bias = biasptr[out_d];
for (int out_i = 0; out_i < outH; out_i++)
{
int in_i = out_i * stride_h - pad_t, out_j = 0;
const float* imgptr0 = inptr_ + in_i*width;
const float* imgptr1 = imgptr0 + dilation_h*width;
const float* imgptr2 = imgptr0 + (dilation_h*2)*width;
float out, w00 = w00_, w01 = w01_, w02 = w02_;
float w20 = w20_, w21 = w21_, w22 = w22_;
if (in_i < 0)
{
w00 = w01 = w02 = 0.f;
imgptr0 = imgptr1;
}
else if (in_i + dilation_h*(kernel_h-1) >= height)
{
w20 = w21 = w22 = 0.f;
imgptr2 = imgptr1;
}
float* outptr = outptr_ + out_i*outW;
if (pad_l > 0)
{
out = imgptr0[0]*w01 + imgptr0[dilation_w]*w02 +
imgptr1[0]*w11 + imgptr1[dilation_w]*w12 +
imgptr2[0]*w21 + imgptr2[dilation_w]*w22 + bias;
if (relu)
out = out > 0.f ? out : out*relu_coeff;
outptr[0] = out;
out_j = 1;
}
if (stride_w == 1 || (stride_w == 2 && dilation_w == 1))
{
const int VECSZ = 8;
__m256 vw00 = _v256_setall_ps(w00), vw01 = _v256_setall_ps(w01), vw02 = _v256_setall_ps(w02),
vw10 = _v256_setall_ps(w10), vw11 = _v256_setall_ps(w11), vw12 = _v256_setall_ps(w12),
vw20 = _v256_setall_ps(w20), vw21 = _v256_setall_ps(w21), vw22 = _v256_setall_ps(w22);
__m256 z = (__m256)__lasx_xvxor_v((__m256i)vw00, (__m256i)vw00),
vbias = _v256_setall_ps(bias), vrc = _v256_setall_ps(relu_coeff);
if( stride_w == 1 )
for( ; out_j < outW1; out_j += VECSZ )
{
if (out_j + VECSZ > outW1 && out_j > pad_l)
out_j = outW1 - VECSZ;
int in_j = out_j * stride_w - pad_l;
__m256 v00 = (__m256)__lasx_xvld(imgptr0 + in_j, 0),
v01 = (__m256)__lasx_xvld(imgptr0 + in_j + dilation_w, 0),
v02 = (__m256)__lasx_xvld(imgptr0 + in_j + dilation_w*2, 0),
v10 = (__m256)__lasx_xvld(imgptr1 + in_j, 0),
v11 = (__m256)__lasx_xvld(imgptr1 + in_j + dilation_w, 0),
v12 = (__m256)__lasx_xvld(imgptr1 + in_j + dilation_w*2, 0),
v20 = (__m256)__lasx_xvld(imgptr2 + in_j, 0),
v21 = (__m256)__lasx_xvld(imgptr2 + in_j + dilation_w, 0),
v22 = (__m256)__lasx_xvld(imgptr2 + in_j + dilation_w*2, 0);
__m256 vout0 = __lasx_xvfmadd_s(v00, vw00, vbias);
__m256 vout1 = __lasx_xvfmul_s(v01, vw01);
__m256 vout2 = __lasx_xvfmul_s(v02, vw02);
vout0 = __lasx_xvfmadd_s(v10, vw10, vout0);
vout1 = __lasx_xvfmadd_s(v11, vw11, vout1);
vout2 = __lasx_xvfmadd_s(v12, vw12, vout2);
vout0 = __lasx_xvfmadd_s(v20, vw20, vout0);
vout1 = __lasx_xvfmadd_s(v21, vw21, vout1);
vout2 = __lasx_xvfmadd_s(v22, vw22, vout2);
vout0 = __lasx_xvfadd_s(__lasx_xvfadd_s(vout0, vout1), vout2);
if (relu)
{
__m256i m = __lasx_xvfcmp_clt_s(z, vout0);
vout0 = (__m256)__lasx_xvbitsel_v((__m256i)__lasx_xvfmul_s(vout0, vrc), (__m256i)vout0, m);
}
__lasx_xvst(vout0, outptr + out_j, 0);
}
else
for( ; out_j < outW1; out_j += VECSZ )
{
if (out_j + VECSZ > outW1 && out_j > pad_l)
out_j = outW1 - VECSZ;
int in_j = out_j * stride_w - pad_l;
__m256 v00, v01, v02, v10, v11, v12, v20, v21, v22, unused;
_v256_load_deinterleave(imgptr0 + in_j, v00, v01);
_v256_load_deinterleave(imgptr0 + in_j + 2, v02, unused);
_v256_load_deinterleave(imgptr1 + in_j, v10, v11);
_v256_load_deinterleave(imgptr1 + in_j + 2, v12, unused);
_v256_load_deinterleave(imgptr2 + in_j, v20, v21);
_v256_load_deinterleave(imgptr2 + in_j + 2, v22, unused);
__m256 vout0 = __lasx_xvfmadd_s(v00, vw00, vbias);
__m256 vout1 = __lasx_xvfmul_s(v01, vw01);
__m256 vout2 = __lasx_xvfmul_s(v02, vw02);
vout0 = __lasx_xvfmadd_s(v10, vw10, vout0);
vout1 = __lasx_xvfmadd_s(v11, vw11, vout1);
vout2 = __lasx_xvfmadd_s(v12, vw12, vout2);
vout0 = __lasx_xvfmadd_s(v20, vw20, vout0);
vout1 = __lasx_xvfmadd_s(v21, vw21, vout1);
vout2 = __lasx_xvfmadd_s(v22, vw22, vout2);
vout0 = __lasx_xvfadd_s(__lasx_xvfadd_s(vout0, vout1), vout2);
if (relu)
{
__m256i m = __lasx_xvfcmp_clt_s(z, vout0);
vout0 = (__m256)__lasx_xvbitsel_v((__m256i)__lasx_xvfmul_s(vout0, vrc), (__m256i)vout0, m);
}
__lasx_xvst(vout0, outptr + out_j, 0);
}
}
for (; out_j < outW1; out_j++)
{
int in_j = out_j * stride_w - pad_l;
out = imgptr0[in_j]*w00 + imgptr0[in_j + dilation_w]*w01 + imgptr0[in_j + dilation_w*2]*w02 +
imgptr1[in_j]*w10 + imgptr1[in_j + dilation_w]*w11 + imgptr1[in_j + dilation_w*2]*w12 +
imgptr2[in_j]*w20 + imgptr2[in_j + dilation_w]*w21 + imgptr2[in_j + dilation_w*2]*w22 + bias;
if (relu)
out = out > 0.f ? out : out*relu_coeff;
outptr[out_j] = out;
}
for (; out_j < outW; out_j++ )
{
int in_j0 = out_j * stride_w - pad_l, in_j1 = in_j0 + dilation_w, in_j2 = in_j0 + dilation_w*2;
float s0 = 1.f, s1 = 1.f, s2 = 1.f;
if (in_j0 >= width)
{
in_j0 = 0;
s0 = 0.f;
}
if (in_j1 >= width)
{
in_j1 = 0;
s1 = 0.f;
}
if (in_j2 >= width)
{
in_j2 = 0;
s2 = 0.f;
}
out = imgptr0[in_j0]*w00*s0 + imgptr0[in_j1]*w01*s1 + imgptr0[in_j2]*w02*s2 +
imgptr1[in_j0]*w10*s0 + imgptr1[in_j1]*w11*s1 + imgptr1[in_j2]*w12*s2 +
imgptr2[in_j0]*w20*s0 + imgptr2[in_j1]*w21*s1 + imgptr2[in_j2]*w22*s2 + bias;
if (relu)
out = out > 0.f ? out : out*relu_coeff;
outptr[out_j] = out;
}
}
}
// dst = vec * weights^t + bias
void fastGEMM1T( const float* vec, const float* weights,
size_t wstep, const float* bias,
float* dst, int nvecs, int vecsize )
{
int i = 0;
__m256i v256_tmp;
for( ; i <= nvecs - 8; i += 8 )
{
const float* wptr = weights + i*wstep;
__m256 vs0 = (__m256)__lasx_xvxor_v(v256_tmp, v256_tmp), vs1 = (__m256)__lasx_xvxor_v(v256_tmp, v256_tmp),
vs2 = (__m256)__lasx_xvxor_v(v256_tmp, v256_tmp), vs3 = (__m256)__lasx_xvxor_v(v256_tmp, v256_tmp),
vs4 = (__m256)__lasx_xvxor_v(v256_tmp, v256_tmp), vs5 = (__m256)__lasx_xvxor_v(v256_tmp, v256_tmp),
vs6 = (__m256)__lasx_xvxor_v(v256_tmp, v256_tmp), vs7 = (__m256)__lasx_xvxor_v(v256_tmp, v256_tmp);
for( int k = 0; k < vecsize; k += 8, wptr += 8 )
{
__m256 v = (__m256)__lasx_xvld(vec + k, 0);
vs0 = __lasx_xvfmadd_s((__m256)__lasx_xvld(wptr, 0), v, vs0);
vs1 = __lasx_xvfmadd_s((__m256)__lasx_xvld(wptr + wstep, 0), v, vs1);
vs2 = __lasx_xvfmadd_s((__m256)__lasx_xvld(wptr + wstep*2, 0), v, vs2);
vs3 = __lasx_xvfmadd_s((__m256)__lasx_xvld(wptr + wstep*3, 0), v, vs3);
vs4 = __lasx_xvfmadd_s((__m256)__lasx_xvld(wptr + wstep*4, 0), v, vs4);
vs5 = __lasx_xvfmadd_s((__m256)__lasx_xvld(wptr + wstep*5, 0), v, vs5);
vs6 = __lasx_xvfmadd_s((__m256)__lasx_xvld(wptr + wstep*6, 0), v, vs6);
vs7 = __lasx_xvfmadd_s((__m256)__lasx_xvld(wptr + wstep*7, 0), v, vs7);
}
/*s0*/
__m256 vs00_perm = (__m256)__lasx_xvpermi_d(vs0, (2<<6) + (3<<4) + (0<<2) + 1);
__m256 vs00_add_2w = __lasx_xvfadd_s(vs0, vs00_perm);
__m256 tmp00_srl = (__m256)__lasx_xvsrli_d(vs00_add_2w, 32);
__m256 vs00_add_4w = __lasx_xvfadd_s(vs00_add_2w, tmp00_srl);
__m256 vs01_perm = (__m256)__lasx_xvpermi_d(vs1, (2<<6) + (3<<4) + (0<<2) + 1);
__m256 vs01_add_2w = __lasx_xvfadd_s(vs1, vs01_perm);
__m256 tmp01_srl = (__m256)__lasx_xvsrli_d(vs01_add_2w, 32);
__m256 vs01_add_4w = __lasx_xvfadd_s(vs01_add_2w, tmp01_srl);
__m256 vs02_perm = (__m256)__lasx_xvpermi_d(vs2, (2<<6) + (3<<4) + (0<<2) + 1);
__m256 vs02_add_2w = __lasx_xvfadd_s(vs2, vs02_perm);
__m256 tmp02_srl = (__m256)__lasx_xvsrli_d(vs02_add_2w, 32);
__m256 vs02_add_4w = __lasx_xvfadd_s(vs02_add_2w, tmp02_srl);
__m256 vs03_perm = (__m256)__lasx_xvpermi_d(vs3, (2<<6) + (3<<4) + (0<<2) + 1);
__m256 vs03_add_2w = __lasx_xvfadd_s(vs3, vs03_perm);
__m256 tmp03_srl = (__m256)__lasx_xvsrli_d(vs03_add_2w, 32);
__m256 vs03_add_4w = __lasx_xvfadd_s(vs03_add_2w, tmp03_srl);
__m256i vs01_vs00 = __lasx_xvpackev_w((__m256i)vs01_add_4w, (__m256i)vs00_add_4w);
__m256i vs03_vs02 = __lasx_xvpackev_w((__m256i)vs03_add_4w, (__m256i)vs02_add_4w);
__m256 s0 = (__m256)__lasx_xvpackev_d(vs03_vs02, vs01_vs00);
/*s1*/
__m256 vs10_perm = (__m256)__lasx_xvpermi_d(vs4, (2<<6) + (3<<4) + (0<<2) + 1);
__m256 vs10_add_2w = __lasx_xvfadd_s(vs4, vs10_perm);
__m256 tmp10_srl = (__m256)__lasx_xvsrli_d(vs10_add_2w, 32);
__m256 vs10_add_4w = __lasx_xvfadd_s(vs10_add_2w, tmp10_srl);
__m256 vs11_perm = (__m256)__lasx_xvpermi_d(vs5, (2<<6) + (3<<4) + (0<<2) + 1);
__m256 vs11_add_2w = __lasx_xvfadd_s(vs5, vs11_perm);
__m256 tmp11_srl = (__m256)__lasx_xvsrli_d(vs11_add_2w, 32);
__m256 vs11_add_4w = __lasx_xvfadd_s(vs11_add_2w, tmp11_srl);
__m256 vs12_perm = (__m256)__lasx_xvpermi_d(vs6, (2<<6) + (3<<4) + (0<<2) + 1);
__m256 vs12_add_2w = __lasx_xvfadd_s(vs6, vs12_perm);
__m256 tmp12_srl = (__m256)__lasx_xvsrli_d(vs12_add_2w, 32);
__m256 vs12_add_4w = __lasx_xvfadd_s(vs12_add_2w, tmp12_srl);
__m256 vs13_perm = (__m256)__lasx_xvpermi_d(vs7, (2<<6) + (3<<4) + (0<<2) + 1);
__m256 vs13_add_2w = __lasx_xvfadd_s(vs7, vs13_perm);
__m256 tmp13_srl = (__m256)__lasx_xvsrli_d(vs13_add_2w, 32);
__m256 vs13_add_4w = __lasx_xvfadd_s(vs13_add_2w, tmp13_srl);
__m256i vs11_vs10 = __lasx_xvpackev_w((__m256i)vs11_add_4w, (__m256i)vs10_add_4w);
__m256i vs13_vs12 = __lasx_xvpackev_w((__m256i)vs13_add_4w, (__m256i)vs12_add_4w);
__m256 s1 = (__m256)__lasx_xvpackev_d(vs13_vs12, vs11_vs10);
s0 = __lasx_xvfadd_s(s0, (__m256)__lasx_xvpermi_q(s0, s0, 1));
s1 = __lasx_xvfadd_s(s1, (__m256)__lasx_xvpermi_q(s1, s1, 1));
s0 = __lasx_xvfadd_s(s0, (__m256)__lasx_xvld(bias + i, 0));
s1 = __lasx_xvfadd_s(s1, (__m256)__lasx_xvld(bias + i, 4*4));
__lsx_vst(*(__m128*)&s0, dst + i, 0);
__lsx_vst(*(__m128*)&s1, dst + i, 4*4);
}
float temp = 0.f;
for( ; i < nvecs; i++ )
{
const float* wptr = weights + i*wstep;
__m256 vs0 = (__m256)__lasx_xvxor_v(v256_tmp, v256_tmp);
for( int k = 0; k < vecsize; k += 8, wptr += 8 )
{
__m256 v = (__m256)__lasx_xvld(vec + k, 0);
vs0 = __lasx_xvfmadd_s((__m256)__lasx_xvld(wptr, 0), v, vs0);
}
__m256i vs0_perm = __lasx_xvpermi_d(vs0, (2<<6) + (3<<4) + (0<<2) + 1);
__m256 vs0_add_2w = __lasx_xvfadd_s(vs0, (__m256)vs0_perm);
__m256i tmp_srl = __lasx_xvsrli_d(vs0_add_2w, 32);
__m256 vs0_add_4w = __lasx_xvfadd_s(vs0_add_2w, (__m256)tmp_srl);
temp = ((v8f32)vs0_add_4w)[0] + ((v8f32)vs0_add_4w)[4];
dst[i] = temp + bias[i];
}
}
void fastGEMM( const float* aptr, size_t astep, const float* bptr,
size_t bstep, float* cptr, size_t cstep,
int ma, int na, int nb )
{
int n = 0;
for( ; n <= nb - 16; n += 16 )
{
for( int m = 0; m < ma; m += 4 )
{
const float* aptr0 = aptr + astep*m;
const float* aptr1 = aptr + astep*std::min(m+1, ma-1);
const float* aptr2 = aptr + astep*std::min(m+2, ma-1);
const float* aptr3 = aptr + astep*std::min(m+3, ma-1);
float* cptr0 = cptr + cstep*m;
float* cptr1 = cptr + cstep*std::min(m+1, ma-1);
float* cptr2 = cptr + cstep*std::min(m+2, ma-1);
float* cptr3 = cptr + cstep*std::min(m+3, ma-1);
__m256i v256_tmp;
__m256 d00 = (__m256)__lasx_xvxor_v(v256_tmp, v256_tmp), d01 = (__m256)__lasx_xvxor_v(v256_tmp, v256_tmp);
__m256 d10 = (__m256)__lasx_xvxor_v(v256_tmp, v256_tmp), d11 = (__m256)__lasx_xvxor_v(v256_tmp, v256_tmp);
__m256 d20 = (__m256)__lasx_xvxor_v(v256_tmp, v256_tmp), d21 = (__m256)__lasx_xvxor_v(v256_tmp, v256_tmp);
__m256 d30 = (__m256)__lasx_xvxor_v(v256_tmp, v256_tmp), d31 = (__m256)__lasx_xvxor_v(v256_tmp, v256_tmp);
for( int k = 0; k < na; k++ )
{
__m256 a0 = _v256_setall_ps(aptr0[k]);
__m256 a1 = _v256_setall_ps(aptr1[k]);
__m256 a2 = _v256_setall_ps(aptr2[k]);
__m256 a3 = _v256_setall_ps(aptr3[k]);
__m256 b0 = (__m256)__lasx_xvld(bptr + k*bstep + n, 0);
__m256 b1 = (__m256)__lasx_xvld(bptr + k*bstep + n + 8, 0);
d00 = __lasx_xvfmadd_s(a0, b0, d00);
d01 = __lasx_xvfmadd_s(a0, b1, d01);
d10 = __lasx_xvfmadd_s(a1, b0, d10);
d11 = __lasx_xvfmadd_s(a1, b1, d11);
d20 = __lasx_xvfmadd_s(a2, b0, d20);
d21 = __lasx_xvfmadd_s(a2, b1, d21);
d30 = __lasx_xvfmadd_s(a3, b0, d30);
d31 = __lasx_xvfmadd_s(a3, b1, d31);
}
__lasx_xvst(d00, cptr0 + n, 0);
__lasx_xvst(d01, cptr0 + n, 8*4);
__lasx_xvst(d10, cptr1 + n, 0);
__lasx_xvst(d11, cptr1 + n, 8*4);
__lasx_xvst(d20, cptr2 + n, 0);
__lasx_xvst(d21, cptr2 + n, 8*4);
__lasx_xvst(d30, cptr3 + n, 0);
__lasx_xvst(d31, cptr3 + n, 8*4);
}
}
for( ; n < nb; n++ )
{
for( int m = 0; m < ma; m++ )
{
const float* aptr0 = aptr + astep*m;
float* cptr0 = cptr + cstep*m;
float d0 = 0.f;
for( int k = 0; k < na; k++ )
d0 += aptr0[k]*bptr[k*bstep + n];
cptr0[n] = d0;
}
}
}
#endif // CV_LASX
CV_CPU_OPTIMIZATION_NAMESPACE_END
}} // namespace
|
////////////////////////////////////////////////////////////////////////
//
// VideoWriter.CPP
//
// Implementation of the video writer node.
//
////////////////////////////////////////////////////////////////////////
#include "imagel_.h"
#include <stdio.h>
// Globals
VideoWriter :: VideoWriter ( void )
{
////////////////////////////////////////////////////////////////////////
//
// PURPOSE
// - Constructor for the object
//
////////////////////////////////////////////////////////////////////////
iFps = 10;
iW = 320;
iH = 240;
} // VideoWriter
HRESULT VideoWriter :: onAttach ( bool bAttach )
{
////////////////////////////////////////////////////////////////////////
//
// PURPOSE
// - Called when this behaviour is assigned to a node
//
// PARAMETERS
// - bAttach is true for attachment, false for detachment.
//
// RETURN VALUE
// S_OK if successful
//
////////////////////////////////////////////////////////////////////////
HRESULT hr = S_OK;
// Attach
if (bAttach)
{
adtValue vL;
// Defaults (optional)
if (pnDesc->load ( adtString(L"FPS"), vL ) == S_OK)
iFps = vL;
if (pnDesc->load ( adtString(L"Width"), vL ) == S_OK)
iW = vL;
if (pnDesc->load ( adtString(L"Height"), vL ) == S_OK)
iH = vL;
} // if
// Detach
else
{
// Shutdown
} // else
return hr;
} // onAttach
HRESULT VideoWriter :: onReceive ( IReceptor *pr, const ADTVALUE &v )
{
////////////////////////////////////////////////////////////////////////
//
// PURPOSE
// - The node has received a value on the specified receptor.
//
// PARAMETERS
// - pr is the receptor
// - v is the value
//
// RETURN VALUE
// S_OK if successful
//
////////////////////////////////////////////////////////////////////////
HRESULT hr = S_OK;
/*
// Grab video frame
if (_RCP(Fire))
{
// State check
CCLTRYE ( bOpen == true, ERROR_INVALID_STATE );
// Result
// if (hr == S_OK)
// _EMT(Fire,adtIUnknown(pImgUse));
// else
// _EMT(Error,adtInt(hr));
} // if
// State
else
*/ hr = ERROR_NO_MATCH;
return hr;
} // receive
|
/*
Copyright (c) 2009-2012, Intel Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// written by Roman Dementiev
//
#include "cpucounters.h"
#include <iostream>
#include <algorithm>
#include <list>
#include <vector>
#include <sys/time.h>
using std::cout;
using std::endl;
inline double my_timestamp()
{
struct timeval tp;
gettimeofday(&tp, NULL);
return double(tp.tv_sec) + tp.tv_usec / 1000000.;
}
struct T
{
int key[1];
int data[15];
T() { }
T(int a) { key[0] = a; }
bool operator == (const T & k) const
{
return k.key[0] == key[0];
}
};
template <class DS>
void Memory_intensive_task(DS & ds)
{
std::find(ds.begin(), ds.end(), ds.size());
}
int main(int argc, char * argv[])
{
std::vector<T> vector;
int nelements = 13000000;
int i = 0;
int delay = atoi(argv[1]);
cout << "Elements data size: " << sizeof(T) * nelements / 1024 << " KB" << std::endl;
for ( ; i < nelements; ++i)
{
vector.push_back(i);
}
double before_ts, after_ts;
while (1)
{
before_ts = my_timestamp();
cout << "Reading memory for " << delay << " seconds" << std::endl;
do
{
Memory_intensive_task(vector);
after_ts = my_timestamp();
} while ((after_ts - before_ts) < delay);
cout << "Sleeping for " << delay << " seconds" << std::endl;
sleep(delay);
}
return 0;
}
|
/*
Operators
Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL.
Amanzi is released under the three-clause BSD License.
The terms of use and "as is" disclaimer for this license are
provided in the top-level COPYRIGHT file.
Authors: Daniil Svyatskiy (dasvyat@lanl.gov)
Konstantin Lipnikov (lipnikov@lanl.gov)
*/
#include <vector>
// Amanzi
#include "Mesh_Algorithms.hh"
#include "MFD3D_Diffusion.hh"
#include "nlfv.hh"
#include "ParallelCommunication.hh"
#include "Op_Face_CellBndFace.hh"
#include "OperatorDefs.hh"
#include "Operator_CellBndFace.hh"
#include "PDE_DiffusionNLFVwithBndFaces.hh"
namespace Amanzi {
namespace Operators {
/* ******************************************************************
* Initialization
****************************************************************** */
void PDE_DiffusionNLFVwithBndFaces::Init_(Teuchos::ParameterList& plist)
{
// Define stencil for the FV diffusion method.
local_op_schema_ = OPERATOR_SCHEMA_BASE_FACE | OPERATOR_SCHEMA_DOFS_CELL | OPERATOR_SCHEMA_DOFS_BNDFACE;
// create or check the existing Operator
if (global_op_ == Teuchos::null) {
// constructor was given a mesh
global_op_schema_ = OPERATOR_SCHEMA_DOFS_CELL| OPERATOR_SCHEMA_DOFS_BNDFACE;
// build the CVS from the global schema
Teuchos::RCP<CompositeVectorSpace> cvs = Teuchos::rcp(new CompositeVectorSpace());
cvs->SetMesh(mesh_)->SetGhosted(true);
cvs->AddComponent("cell", AmanziMesh::CELL, 1);
cvs->AddComponent("boundary_face", AmanziMesh::BOUNDARY_FACE, 1);
global_op_ = Teuchos::rcp(new Operator_CellBndFace(cvs, plist, global_op_schema_));
} else {
// constructor was given an Operator
global_op_schema_ = global_op_->schema();
mesh_ = global_op_->DomainMap().Mesh();
}
// create the local Op and register it with the global Operator
std::string name = "Diffusion: FACE_CELLBNDFACE";
local_op_ = Teuchos::rcp(new Op_Face_CellBndFace(name, mesh_));
global_op_->OpPushBack(local_op_);
// upwind options (not used yet)
std::string uwname = plist.get<std::string>("nonlinear coefficient", "upwind: face");
little_k_ = OPERATOR_LITTLE_K_UPWIND;
if (uwname == "none") {
little_k_ = OPERATOR_LITTLE_K_NONE;
}
// Newton correction terms
std::string jacobian = plist.get<std::string>("Newton correction", "none");
if (jacobian == "none") {
newton_correction_ = OPERATOR_DIFFUSION_JACOBIAN_NONE;
} else if (jacobian == "approximate Jacobian") {
newton_correction_ = OPERATOR_DIFFUSION_JACOBIAN_APPROXIMATE;
name = "Diffusion: FACE_CELLBNDFACE Jacobian terms";
jac_op_ = Teuchos::rcp(new Op_Face_CellBndFace(name, mesh_));
global_op_->OpPushBack(jac_op_);
} else if (jacobian == "true Jacobian") {
newton_correction_ = OPERATOR_DIFFUSION_JACOBIAN_TRUE;
Errors::Message msg;
msg << "PDE_DiffusionNLFVwithBndFaces: \"true Jacobian\" not supported -- maybe you mean \"approximate Jacobian\"?";
Exceptions::amanzi_throw(msg);
} else {
Errors::Message msg;
msg << "PDE_DiffusionNLFVwithBndFaces: invalid parameter \"" << jacobian
<< "\" for option \"Newton correction\" -- valid are: \"none\", \"approximate Jacobian\"";
Exceptions::amanzi_throw(msg);
}
// other data
dim_ = mesh_->space_dimension();
}
/* ******************************************************************
* Setup methods: krel and dkdp must be called after calling a
* setup with K absolute
****************************************************************** */
void PDE_DiffusionNLFVwithBndFaces::SetScalarCoefficient(
const Teuchos::RCP<const CompositeVector>& k,
const Teuchos::RCP<const CompositeVector>& dkdp)
{
stencil_initialized_ = false;
k_ = k;
dkdp_ = dkdp;
if (k_ != Teuchos::null) {
if (little_k_ == OPERATOR_LITTLE_K_UPWIND) {
AMANZI_ASSERT(k_->HasComponent("face"));
}
}
// if (dkdp_ != Teuchos::null) AMANZI_ASSERT(dkdp_->HasComponent("cell"));
}
/* ******************************************************************
* Compute harmonic averaging points (function of geometry and tensor)
* and the positive decomposition of face conormals. The face-based
* data from left and right cells are ordered by the global cells ids.
****************************************************************** */
void PDE_DiffusionNLFVwithBndFaces::InitStencils_()
{
// allocate persistent memory
CompositeVectorSpace cvs;
cvs.SetMesh(mesh_)->SetGhosted(true)
->AddComponent("hap", AmanziMesh::FACE, dim_)
->AddComponent("gamma", AmanziMesh::FACE, 1)
->AddComponent("weight", AmanziMesh::FACE, 2 * dim_)
->AddComponent("flux_data", AmanziMesh::FACE, 2 * dim_);
stencil_data_ = Teuchos::rcp(new CompositeVector(cvs));
Epetra_MultiVector& hap = *stencil_data_->ViewComponent("hap", true);
Epetra_MultiVector& gamma = *stencil_data_->ViewComponent("gamma", true);
Epetra_MultiVector& weight = *stencil_data_->ViewComponent("weight", true);
stencil_data_->PutScalarMasterAndGhosted(0.0);
stencil_faces_.resize(2 * dim_);
stencil_cells_.resize(2 * dim_);
for (int i = 0; i < 2 * dim_; ++i) {
stencil_faces_[i] = Teuchos::rcp(new Epetra_IntVector(mesh_->face_map(true)));
stencil_cells_[i] = Teuchos::rcp(new Epetra_IntVector(mesh_->face_map(true)));
stencil_faces_[i]->PutValue(0);
stencil_cells_[i]->PutValue(0);
}
// allocate temporary memory for distributed tensor
CompositeVectorSpace cvs_tmp;
cvs_tmp.SetMesh(mesh_)->SetGhosted(true)
->AddComponent("tensor", AmanziMesh::CELL, dim_ * dim_);
Teuchos::RCP<CompositeVector> cv_tmp = Teuchos::rcp(new CompositeVector(cvs_tmp));
Epetra_MultiVector& Ktmp = *cv_tmp->ViewComponent("tensor", true);
// instantiate variables to access supporting tools
WhetStone::NLFV nlfv(mesh_);
WhetStone::MFD3D_Diffusion mfd3d(mesh_);
// distribute diffusion tensor
WhetStone::DenseVector data(dim_ * dim_);
for (int c = 0; c < ncells_owned; ++c) {
if (K_ != Teuchos::null) {
WhetStone::TensorToVector((*K_)[c], data);
} else{
WhetStone::Tensor Kc(dim_, 1);
Kc(0, 0) = 1.0;
WhetStone::TensorToVector(Kc, data);
}
for (int i = 0; i < dim_ *dim_; ++i) {
Ktmp[i][c] = data(i);
}
}
cv_tmp->ScatterMasterToGhosted();
// calculate harmonic averaging points (HAPs)
int c1, c2;
double hap_weight;
WhetStone::Tensor T(dim_, 2);
AmanziMesh::Entity_ID_List cells;
AmanziGeometry::Point Kn1(dim_), Kn2(dim_), p(dim_);
for (int f = 0; f < nfaces_owned; f++) {
mesh_->face_get_cells(f, AmanziMesh::Parallel_type::ALL, &cells);
int ncells = cells.size();
if (ncells == 2) {
const AmanziGeometry::Point& normal = mesh_->face_normal(f);
OrderCellsByGlobalId_(cells, c1, c2);
// create to conormals
for (int i = 0; i < dim_ *dim_; ++i) data(i) = Ktmp[i][c1];
VectorToTensor(data, T);
Kn1 = T * normal;
for (int i = 0; i < dim_ *dim_; ++i) data(i) = Ktmp[i][c2];
VectorToTensor(data, T);
Kn2 = T * normal;
nlfv.HarmonicAveragingPoint(f, c1, c2, Kn1, Kn2, p, hap_weight);
} else {
p = mesh_->face_centroid(f);
hap_weight = 0.0;
}
// factor going to stencil should be (1 - weight)
for (int i = 0; i < dim_; ++i) hap[i][f] = p[i];
gamma[0][f] = 1.0 - hap_weight;
}
stencil_data_->ScatterMasterToGhosted("hap");
stencil_data_->ScatterMasterToGhosted("gamma");
// calculate coefficients in positive decompositions of conormals
AmanziGeometry::Point conormal(dim_), v(dim_);
std::vector<AmanziGeometry::Point> tau;
for (int c = 0; c < ncells_owned; c++) {
const AmanziGeometry::Point& xc = mesh_->cell_centroid(c);
// calculate list of candidate vectors
const auto& faces = mesh_->cell_get_faces(c);
const auto& dirs = mesh_->cell_get_face_dirs(c);
int nfaces = faces.size();
WhetStone::Tensor Kc(mesh_->space_dimension(), 1);
Kc(0, 0) = 1.0;
if (K_.get()) Kc = (*K_)[c];
tau.clear();
for (int n = 0; n < nfaces; n++) {
int f = faces[n];
for (int i = 0; i < dim_; ++i) v[i] = hap[i][f] - xc[i];
tau.push_back(v);
}
// decompose co-normals
int ierr, ids[dim_];
double ws[dim_];
for (int n = 0; n < nfaces; n++) {
int f = faces[n];
const AmanziGeometry::Point& normal = mesh_->face_normal(f);
conormal = (Kc * normal) * dirs[n];
ierr = nlfv.PositiveDecomposition(n, tau, conormal, ws, ids);
AMANZI_ASSERT(ierr == 0);
mesh_->face_get_cells(f, AmanziMesh::Parallel_type::ALL, &cells);
OrderCellsByGlobalId_(cells, c1, c2);
int k = (c == c1) ? 0 : dim_;
for (int i = 0; i < dim_; i++) {
weight[k + i][f] = ws[i];
(*stencil_faces_[k + i])[f] = faces[ids[i]];
(*stencil_cells_[k + i])[f] = cell_get_face_adj_cell(*mesh_, c, faces[ids[i]]);
}
}
}
for (int f = 0; f < nfaces_owned; f++) {
mesh_->face_get_cells(f, AmanziMesh::Parallel_type::ALL, &cells);
int ncells = cells.size();
if (ncells == 1) {
int c = cells[0];
const AmanziGeometry::Point& xc = mesh_->cell_centroid(c);
const auto& faces = mesh_->cell_get_faces(c);
const auto& dirs = mesh_->cell_get_face_dirs(c);
int nfaces = faces.size();
WhetStone::Tensor Kc(mesh_->space_dimension(), 1);
Kc(0, 0) = 1.0;
if (K_.get()) Kc = (*K_)[c];
int face_itself;
tau.clear();
for (int n = 0; n < nfaces; n++) {
int g = faces[n];
if (g == f) {
face_itself = n;
for (int i = 0; i < dim_; ++i) v[i] = xc[i] - hap[i][f];
}else{
for (int i = 0; i < dim_; ++i) v[i] = hap[i][g] - hap[i][f];
}
tau.push_back(v);
}
const AmanziGeometry::Point& normal = mesh_->face_normal(f);
conormal = -(Kc * normal) * dirs[face_itself];
int ierr, ids[dim_];
double ws[dim_];
ierr = nlfv.PositiveDecomposition(face_itself, tau, conormal, ws, ids);
AMANZI_ASSERT(ierr == 0);
weight[dim_][f] = ws[0];
(*stencil_faces_[dim_])[f] = -100;
(*stencil_cells_[dim_])[f] = c;
for (int i = 1; i < dim_; i++) {
weight[dim_ + i][f] = ws[i];
(*stencil_faces_[dim_ + i])[f] = faces[ids[i]];
(*stencil_cells_[dim_ + i])[f] = cell_get_face_adj_cell(*mesh_, c, faces[ids[i]]);
}
}
}
// distribute stencils
stencil_data_->GatherGhostedToMaster("weight");
stencil_data_->ScatterMasterToGhosted("weight");
ParallelCommunication pp(mesh_);
for (int i = 0; i < 2 * dim_; ++i) {
pp.CombineGhostFace2MasterFace(*stencil_faces_[i], (Epetra_CombineMode)Add);
pp.CombineGhostFace2MasterFace(*stencil_cells_[i], (Epetra_CombineMode)Add);
pp.CopyMasterFace2GhostFace(*stencil_faces_[i]);
pp.CopyMasterFace2GhostFace(*stencil_cells_[i]);
}
stencil_initialized_ = true;
}
/* ******************************************************************
* Populate face-based 2x2 matrices on interior faces and 1x1 matrices
* on boundary faces. We avoid round-off operations since the stencils
* already incorporate them.
****************************************************************** */
void PDE_DiffusionNLFVwithBndFaces::UpdateMatrices(
const Teuchos::Ptr<const CompositeVector>& flux,
const Teuchos::Ptr<const CompositeVector>& u)
{
if (!stencil_initialized_) InitStencils_();
u->ScatterMasterToGhosted("cell");
Epetra_MultiVector& hap_gamma = *stencil_data_->ViewComponent("gamma", true);
Epetra_MultiVector& weight = *stencil_data_->ViewComponent("weight", true);
Epetra_MultiVector& flux_data = *stencil_data_->ViewComponent("flux_data", true);
// allocate auxiliary matrix structure
CompositeVectorSpace cvs;
cvs.SetMesh(mesh_)->SetGhosted(true)->AddComponent("face", AmanziMesh::FACE, 2);
CompositeVector matrix_cv(cvs), sideflux_cv(cvs);
Epetra_MultiVector& matrix = *matrix_cv.ViewComponent("face", true);
Epetra_MultiVector& sideflux = *sideflux_cv.ViewComponent("face", true);
// calculate one-sides flux corrections. Since a flux stencil can
// occupy (dim_ + 1) cells, we need parallel communications.
OneSidedFluxCorrections_(1, *u, sideflux_cv);
OneSidedNeumannCorrections_( *u, sideflux_cv);
sideflux_cv.GatherGhostedToMaster();
sideflux_cv.ScatterMasterToGhosted();
// un-rolling little-k data
Teuchos::RCP<const Epetra_MultiVector> k_face = Teuchos::null;
if (k_ != Teuchos::null) k_face = k_->ViewComponent("face");
// split each stencil between different local matrices
int c1, c2, c3, c4, k1, k2;
AmanziMesh::Entity_ID_List cells, cells_tmp;
matrix_cv.PutScalarMasterAndGhosted(0.0);
flux_data.PutScalar(0.0);
for (int c = 0; c < ncells_owned; ++c) {
const auto& faces = mesh_->cell_get_faces(c);
int nfaces = faces.size();
for (int n = 0; n < nfaces; ++n) {
int f = faces[n];
mesh_->face_get_cells(f, AmanziMesh::Parallel_type::ALL, &cells);
int ncells = cells.size();
OrderCellsByGlobalId_(cells, c1, c2);
k1 = (c1 == c) ? 0 : 1;
k2 = k1 * dim_;
// calculate little_k on the current face
double kf(1.0);
if (k_face.get()) kf = (*k_face)[0][f];
// Calculate solution-dependent weigths using corrections to the
// two-point flux. Note mu does not depend on one-sided flux.
double gamma, g1, g2, gg(-1.0), w1, w2(0.0), tpfa, mu(1.0), ntpfa1, ntpfa2;
gamma = hap_gamma[0][f];
if (ncells == 2) {
w1 = weight[0][f] * gamma;
w2 = weight[dim_][f] * (1.0 - gamma);
g1 = sideflux[0][f];
g2 = sideflux[1][f];
gg = g1 * g2;
g1 = fabs(g1);
g2 = fabs(g2);
mu = (g1 + g2 == 0.0) ? 0.5 : g2 / (g1 + g2);
tpfa = mu * w1 + (1.0 - mu) * w2;
matrix[k1][f] += kf * tpfa;
flux_data[k2][f] = kf * tpfa;
} else {
g1 = sideflux[0][f];
g2 = sideflux[1][f];
mu = (g1 + g2 == 0.0) ? 0.5 : g2 / (g1 + g2);
w1 = weight[0][f];
w2 = weight[dim_][f];
double tc1, tc2;
NLTPFAContributions_(f, tc1, tc2);
ntpfa1 = mu * w1 + (1.0 - mu) * w2 + mu*tc1;
ntpfa2 = mu * w1 + (1.0 - mu) * w2 + (1.0 - mu)*tc2;
gg = 0.;
matrix[0][f] += kf*ntpfa1;
matrix[1][f] += kf*ntpfa2;
flux_data[0][f] = kf*ntpfa1;
flux_data[dim_][f] = kf*ntpfa2;
//}
}
// remaining terms of one-sided flux in cell c. Now we need
// to select mu depending on the one-sided flux.
if (gg < 0.0) {
if (c1 != c) mu = 1.0 - mu;
for (int i = 1; i < dim_; i++) {
int f1 = (*stencil_faces_[i + k2])[f];
mesh_->face_get_cells(f1, AmanziMesh::Parallel_type::ALL, &cells_tmp);
gamma = hap_gamma[0][f1];
OrderCellsByGlobalId_(cells_tmp, c3, c4);
k1 = 0;
if (c3 != c) {
gamma = 1.0 - gamma;
k1 = 1;
}
double tmp = ncells * weight[i + k2][f] * gamma * mu;
matrix[k1][f1] += kf * tmp;
if (cells_tmp.size()==1) {
int kb = 1- k1;
matrix[kb][f1] += kf * tmp;
}
flux_data[k2+i][f] = kf * tmp;
}
}
}
}
stencil_data_->GatherGhostedToMaster("flux_data");
matrix_cv.GatherGhostedToMaster();
// populate local matrices
for (int f = 0; f < nfaces_owned; ++f) {
mesh_->face_get_cells(f, AmanziMesh::Parallel_type::ALL, &cells);
int ncells = cells.size();
WhetStone::DenseMatrix Aface(2, 2);
if (ncells == 2) {
k1 = OrderCellsByGlobalId_(cells, c3, c4);
k2 = 1 - k1;
Aface(0, 0) = matrix[k1][f];
Aface(0, 1) = -matrix[k1][f];
Aface(1, 0) = -matrix[k2][f];
Aface(1, 1) = matrix[k2][f];
} else {
Aface(0, 0) = matrix[0][f];
Aface(0, 1) = -matrix[1][f];
Aface(1, 1) = flux_data[dim_][f];
Aface(1, 0) = -flux_data[0][f];
}
local_op_->matrices[f] = Aface;
}
}
/* ******************************************************************
* Modify operator by adding an upwind approximation of the Newton
* correction term.
****************************************************************** */
void PDE_DiffusionNLFVwithBndFaces::UpdateMatricesNewtonCorrection(
const Teuchos::Ptr<const CompositeVector>& flux,
const Teuchos::Ptr<const CompositeVector>& u, double scalar_factor)
{
// ignore correction if no flux provided.
if (flux == Teuchos::null) return;
// Correction is zero for linear problems
if (k_ == Teuchos::null || dkdp_ == Teuchos::null) return;
if (k_->HasComponent("face")) k_->ScatterMasterToGhosted("face");
if (dkdp_->HasComponent("face")) dkdp_->ScatterMasterToGhosted("face");
// Correction is not required
if (newton_correction_ == OPERATOR_DIFFUSION_JACOBIAN_NONE) return;
// only works on upwinded methods
if (little_k_ == OPERATOR_UPWIND_NONE) return;
const Epetra_MultiVector& kf = *k_->ViewComponent("face");
const Epetra_MultiVector& dkdp_f = *dkdp_->ViewComponent("face");
const Epetra_MultiVector& flux_f = *flux->ViewComponent("face");
// populate the local matrices
double v, vmod;
AmanziMesh::Entity_ID_List cells;
for (int f = 0; f < nfaces_owned; f++) {
mesh_->face_get_cells(f, AmanziMesh::Parallel_type::ALL, &cells);
int ncells = cells.size();
WhetStone::DenseMatrix Aface(2,2);
Aface.PutScalar(0.0);
// We use the upwind discretization of the generalized flux.
v = std::abs(kf[0][f]) > 0.0 ? flux_f[0][f] * dkdp_f[0][f] / kf[0][f] : 0.0;
vmod = std::abs(v);
// prototype for future limiters
vmod *= scalar_factor;
// We use the upwind discretization of the generalized flux.
int i, dir, c1;
c1 = cells[0];
mesh_->face_normal(f, false, c1, &dir);
i = (v * dir >= 0.0) ? 0 : 1;
if (ncells == 2) {
Aface(i, i) = vmod;
Aface(1 - i, i) = -vmod;
} else if (i == 0) {
Aface(0, 0) = vmod;
}
jac_op_->matrices[f] = Aface;
}
}
/* ******************************************************************
* Modify operator by adding an upwind approximation of the Newton
* correction term.
****************************************************************** */
void PDE_DiffusionNLFVwithBndFaces::UpdateMatricesNewtonCorrection(
const Teuchos::Ptr<const CompositeVector>& flux,
const Teuchos::Ptr<const CompositeVector>& u,
const Teuchos::Ptr<const CompositeVector>& factor)
{
// ignore correction if no flux provided.
if (flux == Teuchos::null) return;
// Correction is zero for linear problems
if (k_ == Teuchos::null || dkdp_ == Teuchos::null) return;
// Correction is not required
if (newton_correction_ == OPERATOR_DIFFUSION_JACOBIAN_NONE) return;
// only works on upwinded methods
if (little_k_ == OPERATOR_UPWIND_NONE) return;
const Epetra_MultiVector& kf = *k_->ViewComponent("face");
const Epetra_MultiVector& dkdp_f = *dkdp_->ViewComponent("face");
const Epetra_MultiVector& flux_f = *flux->ViewComponent("face");
const Epetra_MultiVector& factor_cell = *factor->ViewComponent("cell");
// populate the local matrices
double v, vmod;
AmanziMesh::Entity_ID_List cells;
for (int f = 0; f < nfaces_owned; f++) {
mesh_->face_get_cells(f, AmanziMesh::Parallel_type::ALL, &cells);
int ncells = cells.size();
WhetStone::DenseMatrix Aface(2,2);
Aface.PutScalar(0.0);
// We use the upwind discretization of the generalized flux.
v = std::abs(kf[0][f]) > 0.0 ? flux_f[0][f] * dkdp_f[0][f] / kf[0][f] : 0.0;
vmod = std::abs(v);
double scalar_factor = 0.;
for (int j = 0; j < ncells; j++) scalar_factor += factor_cell[0][cells[j]];
scalar_factor *= 1.0 / ncells;
// prototype for future limiters
vmod *= scalar_factor;
// We use the upwind discretization of the generalized flux.
int i, dir, c1;
c1 = cells[0];
mesh_->face_normal(f, false, c1, &dir);
i = (v * dir >= 0.0) ? 0 : 1;
if (ncells == 2) {
Aface(i, i) = vmod;
Aface(1 - i, i) = -vmod;
} else if (i == 0) {
Aface(0, 0) = vmod;
}
jac_op_->matrices[f] = Aface;
}
}
/* ******************************************************************
* Calculate one-sided fluxes (i0=0) or flux corrections (i0=1).
****************************************************************** */
void PDE_DiffusionNLFVwithBndFaces::OneSidedFluxCorrections_(
int i0, const CompositeVector& u, CompositeVector& flux_cv)
{
// un-rolling composite vectors
const Epetra_MultiVector& uc = *u.ViewComponent("cell", true);
const Epetra_MultiVector& ubnd = *u.ViewComponent("boundary_face", true);
Epetra_MultiVector& flux = *flux_cv.ViewComponent("face", true);
Epetra_MultiVector& hap_gamma = *stencil_data_->ViewComponent("gamma", true);
Epetra_MultiVector& weight = *stencil_data_->ViewComponent("weight", true);
const std::vector<int>& bc_model = bcs_trial_[0]->bc_model();
// un-rolling little-k data
Teuchos::RCP<const Epetra_MultiVector> k_face = Teuchos::null;
if (k_ != Teuchos::null) k_face = k_->ViewComponent("face");
int c1, c2, c3, k1, k2;
double gamma, tmp;
AmanziMesh::Entity_ID_List cells, cells_tmp;
flux_cv.PutScalarMasterAndGhosted(0.0);
for (int c = 0; c < ncells_owned; ++c) {
const auto& faces = mesh_->cell_get_faces(c);
int nfaces = faces.size();
for (int n = 0; n < nfaces; ++n) {
int f = faces[n];
mesh_->face_get_cells(f, AmanziMesh::Parallel_type::ALL, &cells);
OrderCellsByGlobalId_(cells, c1, c2);
k1 = (c1 == c) ? 0 : 1;
k2 = k1 * dim_;
// scalar (nonlinear) coefficient
double kf(1.0);
if (k_face.get()) kf = (*k_face)[0][f];
double sideflux(0.0);
for (int i = i0; i < dim_; ++i) {
int f1 = (*stencil_faces_[i + k2])[f];
c3 = (*stencil_cells_[i + k2])[f];
if (c3 >= 0) {
mesh_->face_get_cells(f1, AmanziMesh::Parallel_type::ALL, &cells_tmp);
OrderCellsByGlobalId_(cells_tmp, c1, c2);
gamma = hap_gamma[0][f1];
if (c1 != c) gamma = 1.0 - gamma;
tmp = weight[i + k2][f] * gamma;
sideflux += tmp * (uc[0][c] - uc[0][c3]);
} else if (bc_model[f1] == OPERATOR_BC_DIRICHLET) {
tmp = weight[i + k2][f];
int bf = mesh_->exterior_face_map(false).LID(mesh_->face_map(false).GID(f1));
sideflux += tmp * (uc[0][c] - ubnd[0][bf] );// * dir;
} else if (bc_model[f1] == OPERATOR_BC_NEUMANN) {
tmp = weight[i + k2][f];
int bf = mesh_->exterior_face_map(false).LID(mesh_->face_map(false).GID(f1));
sideflux += tmp * (uc[0][c] - ubnd[0][bf]) ;//* dir;
}
}
flux[k1][f] = kf * sideflux;
}
}
}
void PDE_DiffusionNLFVwithBndFaces::OneSidedNeumannCorrections_(const CompositeVector& u,
CompositeVector& flux_cv) {
// un-rolling composite vectors
const Epetra_MultiVector& uc = *u.ViewComponent("cell", true);
const Epetra_MultiVector& ubnd = *u.ViewComponent("boundary_face", true);
Epetra_MultiVector& flux = *flux_cv.ViewComponent("face", true);
Epetra_MultiVector& hap_gamma = *stencil_data_->ViewComponent("gamma", true);
Epetra_MultiVector& weight = *stencil_data_->ViewComponent("weight", true);
const std::vector<int>& bc_model = bcs_trial_[0]->bc_model();
// un-rolling little-k data
Teuchos::RCP<const Epetra_MultiVector> k_face = Teuchos::null;
if (k_ != Teuchos::null) k_face = k_->ViewComponent("face");
int c1, c2, c3, k1, k2;
double gamma, tmp;
std::vector<int> dirs;
AmanziMesh::Entity_ID_List cells, cells_tmp, faces;
for (int f = 0; f < nfaces_owned; f++) {
if ((bc_model[f] == OPERATOR_BC_NEUMANN)||(bc_model[f] == OPERATOR_BC_DIRICHLET)) {
mesh_->face_get_cells(f, AmanziMesh::Parallel_type::ALL, &cells);
AMANZI_ASSERT(cells.size()==1);
k1 = 1;
k2 = dim_;
// scalar (nonlinear) coefficient
double kf(1.0);
if (k_face.get()) kf = (*k_face)[0][f];
for (k1=0; k1<2; k1++) {
k2 = k1*dim_;
double sideflux(0.0);
for (int i = 1; i < dim_; ++i) {
int f1 = (*stencil_faces_[i + k2])[f];
c3 = (*stencil_cells_[i + k2])[f];
if (f1 >=0) {
if (c3 >= 0) {
mesh_->face_get_cells(f1, AmanziMesh::Parallel_type::ALL, &cells_tmp);
OrderCellsByGlobalId_(cells_tmp, c1, c2);
gamma = hap_gamma[0][f1];
double uf = (1 - gamma)*uc[0][c1] + gamma*uc[0][c2];
sideflux += weight[i + k2][f] * uf;
} else if (bc_model[f1] == OPERATOR_BC_DIRICHLET) {
tmp = weight[i + k2][f];
int bf = mesh_->exterior_face_map(false).LID(mesh_->face_map(false).GID(f1));
sideflux += tmp * ubnd[0][bf];
} else if (bc_model[f1] == OPERATOR_BC_NEUMANN) {
tmp = weight[i + k2][f];
int bf = mesh_->exterior_face_map(false).LID(mesh_->face_map(false).GID(f1));
sideflux += tmp * ubnd[0][bf];
}
}
}
flux[k1][f] = kf * sideflux;
}
}
}
// flux_cv.GatherGhostedToMaster();
// flux_cv.ScatterMasterToGhosted();
}
/* ******************************************************************
* Calculate one-sided fluxes (i0=0) or flux corrections (i0=1).
****************************************************************** */
void PDE_DiffusionNLFVwithBndFaces::OneSidedWeightFluxes_(
int i0, const CompositeVector& u, CompositeVector& flux_cv)
{
// un-rolling composite vectors
const Epetra_MultiVector& uc = *u.ViewComponent("cell", true);
const Epetra_MultiVector& ubnd = *u.ViewComponent("boundary_face", true);
Epetra_MultiVector& flux = *flux_cv.ViewComponent("face", true);
const std::vector<int>& bc_model = bcs_trial_[0]->bc_model();
Epetra_MultiVector& flux_data = *stencil_data_->ViewComponent("flux_data", true);
int c1, c2, c3, k1, k2;
AmanziMesh::Entity_ID_List cells;
flux_cv.PutScalarMasterAndGhosted(0.0);
for (int c = 0; c < ncells_owned; ++c) {
const auto& faces = mesh_->cell_get_faces(c);
int nfaces = faces.size();
for (int n = 0; n < nfaces; ++n) {
int f = faces[n];
mesh_->face_get_cells(f, AmanziMesh::Parallel_type::ALL, &cells);
if (cells.size() > 1) {
OrderCellsByGlobalId_(cells, c1, c2);
k1 = (c1 == c) ? 0 : 1;
k2 = k1 * dim_;
double sideflux(0.0);
for (int i = i0; i < dim_; ++i) {
c3 = (*stencil_cells_[i + k2])[f];
int f1 = (*stencil_faces_[i + k2])[f];
if (c3 >= 0) {
sideflux += flux_data[i + k2][f] * (uc[0][c] - uc[0][c3]);
} else if (bc_model[f1] == OPERATOR_BC_DIRICHLET) {
int bf = mesh_->exterior_face_map(false).LID(mesh_->face_map(false).GID(f1));
sideflux += flux_data[i + k2][f] * (uc[0][c] - ubnd[0][bf]);
} else if (bc_model[f1] == OPERATOR_BC_NEUMANN) {
int bf = mesh_->exterior_face_map(false).LID(mesh_->face_map(false).GID(f1));
sideflux += flux_data[i + k2][f] * (uc[0][c] - ubnd[0][bf]);
}
}
flux[k1][f] = sideflux;
}else if (cells.size() == 1) {
int bf = mesh_->exterior_face_map(false).LID(mesh_->face_map(false).GID(f));
flux[0][f] = flux_data[0][f] * uc[0][c] - flux_data[dim_][f]*ubnd[0][bf];
}
}
}
flux_cv.GatherGhostedToMaster();
flux_cv.ScatterMasterToGhosted();
}
/* ******************************************************************
* Matrix-based implementation of boundary conditions.
****************************************************************** */
void PDE_DiffusionNLFVwithBndFaces::ApplyBCs(bool primary, bool eliminate, bool essential_eqn)
{
const std::vector<int>& bc_model = bcs_trial_[0]->bc_model();
const std::vector<double>& bc_value = bcs_trial_[0]->bc_value();
Epetra_MultiVector& rhs_bnd = *global_op_->rhs()->ViewComponent("boundary_face", true);
Epetra_MultiVector& hap = *stencil_data_->ViewComponent("hap", true);
// un-rolling little-k data
Teuchos::RCP<const Epetra_MultiVector> k_face = Teuchos::null;
if (k_ != Teuchos::null) k_face = k_->ViewComponent("face");
AmanziMesh::Entity_ID_List cells;
for (int f = 0; f < nfaces_owned; f++) {
if (bc_model[f] != OPERATOR_BC_NONE) {
mesh_->face_get_cells(f, AmanziMesh::Parallel_type::ALL, &cells);
int c = cells[0];
int bf = mesh_->exterior_face_map(false).LID(mesh_->face_map(false).GID(f));
if (bc_model[f] == OPERATOR_BC_DIRICHLET) {
WhetStone::DenseMatrix& Aface = local_op_->matrices[f];
local_op_->matrices_shadow[f] = Aface;
Aface(1,0) = 0.;
// Aface(1,1) = 1e-10;
rhs_bnd[0][bf] = Aface(1,1)*bc_value[f];
} else if (bc_model[f] == OPERATOR_BC_NEUMANN) {
WhetStone::DenseMatrix& Aface = local_op_->matrices[f];
local_op_->matrices_shadow[f] = Aface;
WhetStone::Tensor Kc(dim_, 1);
Kc(0, 0) = 1.0;
if (K_.get()) Kc = (*K_)[c];
const AmanziGeometry::Point& xc = mesh_->cell_centroid(c);
AmanziGeometry::Point v(dim_);
for (int i = 0; i < dim_; ++i) v[i] = hap[i][f] - xc[i];
double ub = bc_value[f] * mesh_->face_area(f);
rhs_bnd[0][bf] -= ub;
}
}
}
return;
}
/* ******************************************************************
* Calculate flux using cell-centered data.
* **************************************************************** */
void PDE_DiffusionNLFVwithBndFaces::UpdateFlux(const Teuchos::Ptr<const CompositeVector>& u,
const Teuchos::Ptr<CompositeVector>& flux)
{
const std::vector<int>& bc_model = bcs_trial_[0]->bc_model();
CompositeVectorSpace cvs;
cvs.SetMesh(mesh_)->SetGhosted(true)->AddComponent("face", AmanziMesh::FACE, 2);
CompositeVector wgt_sideflux_cv(cvs);
Epetra_MultiVector& wgt_sideflux = *wgt_sideflux_cv.ViewComponent("face", true);
Epetra_MultiVector& flux_data = *flux->ViewComponent("face", true);
u->ScatterMasterToGhosted("cell");
OneSidedWeightFluxes_(0, *u, wgt_sideflux_cv);
int c1, c2, dir;
AmanziMesh::Entity_ID_List cells;
for (int f = 0; f < nfaces_owned; ++f) {
if ((bc_model[f] == OPERATOR_BC_DIRICHLET)) {
mesh_->face_get_cells(f, AmanziMesh::Parallel_type::ALL, &cells);
mesh_->face_normal(f, false, cells[0], &dir);
flux_data[0][f] = wgt_sideflux[0][f] * dir;
} else if (bc_model[f] == OPERATOR_BC_NEUMANN) {
//flux_data[0][f] = bc_value[f] * mesh_->face_area(f);
mesh_->face_get_cells(f, AmanziMesh::Parallel_type::ALL, &cells);
mesh_->face_normal(f, false, cells[0], &dir);
flux_data[0][f] = wgt_sideflux[0][f] * dir;
} else if (bc_model[f] == OPERATOR_BC_NONE) {
mesh_->face_get_cells(f, AmanziMesh::Parallel_type::ALL, &cells);
OrderCellsByGlobalId_(cells, c1, c2);
mesh_->face_normal(f, false, c1, &dir);
double wg1 = wgt_sideflux[0][f];
double wg2 = wgt_sideflux[1][f];
if (cells.size() == 2) flux_data[0][f] = 0.5*(wg1 - wg2)*dir;
else flux_data[0][f] = dir*wg1;
}
}
}
/* ******************************************************************
* Order cells by their global ids. Returns 1 if cells were swapped.
****************************************************************** */
int PDE_DiffusionNLFVwithBndFaces::OrderCellsByGlobalId_(
const AmanziMesh::Entity_ID_List& cells, int& c1, int& c2)
{
c1 = cells[0];
c2 = -1;
int ncells = cells.size();
if (ncells == 1) return 0;
c2 = cells[1];
if (mesh_->cell_map(true).GID(c1) > mesh_->cell_map(true).GID(c2)) {
int c(c1);
c1 = c2;
c2 = c;
return 1;
}
return 0;
}
/* ******************************************************************
* TBW
****************************************************************** */
int PDE_DiffusionNLFVwithBndFaces::NLTPFAContributions_(int f, double& tc1, double& tc2)
{
int c, c1, c2, c3, f1;
AmanziMesh::Entity_ID_List cells, cells_tmp, faces;
const std::vector<int>& bc_model = bcs_trial_[0]->bc_model();
//AMANZI_ASSERT(bc_model[f] == OPERATOR_BC_NEUMANN);
mesh_->face_get_cells(f, AmanziMesh::Parallel_type::ALL, &cells);
c = cells[0];
tc1 = 0.;
tc2 = 0.;
Epetra_MultiVector& hap_gamma = *stencil_data_->ViewComponent("gamma", true);
Epetra_MultiVector& weight = *stencil_data_->ViewComponent("weight", true);
for (int i = 1; i < dim_; i++) {
c3 = (*stencil_cells_[i])[f];
f1 = (*stencil_faces_[i])[f];
if (c3 >= 0) {
mesh_->face_get_cells(f1, AmanziMesh::Parallel_type::ALL, &cells_tmp);
OrderCellsByGlobalId_(cells_tmp, c1, c2);
double gamma = hap_gamma[0][f1];
if (c1 != c) gamma = 1.0 - gamma;
tc1 += weight[i][f];
} else if (bc_model[f1] == OPERATOR_BC_DIRICHLET) {
tc1 += weight[i][f];
} else if (bc_model[f1] == OPERATOR_BC_NEUMANN) {
tc1 += weight[i][f];
}
}
for (int i = 1; i < dim_; i++) {
c3 = (*stencil_cells_[dim_ + i])[f];
f1 = (*stencil_faces_[dim_ + i])[f];
if (c3 >= 0) {
mesh_->face_get_cells(f1, AmanziMesh::Parallel_type::ALL, &cells_tmp);
OrderCellsByGlobalId_(cells_tmp, c1, c2);
double gamma = hap_gamma[0][f1];
if (c1 != c) gamma = 1.0 - gamma;
tc2 += weight[i + dim_][f];
} else if (bc_model[f1] == OPERATOR_BC_DIRICHLET) {
tc2 += weight[i + dim_][f];
} else if (bc_model[f1] == OPERATOR_BC_NEUMANN) {
tc2 += weight[i + dim_][f];
}
}
return 0;
}
} // namespace Operators
} // namespace Amanzi
|
//
// window.cpp
// MDStudio
//
// Created by Daniel Cliche on 2017-05-29.
// Copyright (c) 2017-2020 Daniel Cliche. All rights reserved.
//
#include "window.h"
#include <platform.h>
using namespace MDStudio;
// ---------------------------------------------------------------------------------------------------------------------
Window::Window() {
_isOpened = false;
_didResignKeyWindowFn = nullptr;
_contentView = new View("contentView", this);
_contentView->createResponderChain();
_contentView->createTooltipManager();
}
// ---------------------------------------------------------------------------------------------------------------------
void Window::open(Rect rect, bool isKeyWindow) {
Platform::sharedInstance()->createWindow(this, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height,
_contentView, isKeyWindow);
_contentView->setFrame(makeRect(0.0f, 0.0f, rect.size.width, rect.size.height));
_contentView->updateResponderChain();
_contentView->updateTooltips();
_contentView->setDirtyAll();
_isOpened = true;
}
// ---------------------------------------------------------------------------------------------------------------------
void Window::makeKeyWindow() { Platform::sharedInstance()->makeKeyWindow(this); }
// ---------------------------------------------------------------------------------------------------------------------
void Window::close() {
Platform::sharedInstance()->destroyWindow(this);
_isOpened = false;
}
// ---------------------------------------------------------------------------------------------------------------------
Window::~Window() {
if (_isOpened) close();
_contentView->removeAllSubviews();
delete _contentView;
}
// ---------------------------------------------------------------------------------------------------------------------
void Window::sendDidResignKeyWindow() {
if (_didResignKeyWindowFn) _didResignKeyWindowFn(this);
}
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/resource-groups/model/ResourceFilter.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace ResourceGroups
{
namespace Model
{
ResourceFilter::ResourceFilter() :
m_name(ResourceFilterName::NOT_SET),
m_nameHasBeenSet(false),
m_valuesHasBeenSet(false)
{
}
ResourceFilter::ResourceFilter(JsonView jsonValue) :
m_name(ResourceFilterName::NOT_SET),
m_nameHasBeenSet(false),
m_valuesHasBeenSet(false)
{
*this = jsonValue;
}
ResourceFilter& ResourceFilter::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("Name"))
{
m_name = ResourceFilterNameMapper::GetResourceFilterNameForName(jsonValue.GetString("Name"));
m_nameHasBeenSet = true;
}
if(jsonValue.ValueExists("Values"))
{
Array<JsonView> valuesJsonList = jsonValue.GetArray("Values");
for(unsigned valuesIndex = 0; valuesIndex < valuesJsonList.GetLength(); ++valuesIndex)
{
m_values.push_back(valuesJsonList[valuesIndex].AsString());
}
m_valuesHasBeenSet = true;
}
return *this;
}
JsonValue ResourceFilter::Jsonize() const
{
JsonValue payload;
if(m_nameHasBeenSet)
{
payload.WithString("Name", ResourceFilterNameMapper::GetNameForResourceFilterName(m_name));
}
if(m_valuesHasBeenSet)
{
Array<JsonValue> valuesJsonList(m_values.size());
for(unsigned valuesIndex = 0; valuesIndex < valuesJsonList.GetLength(); ++valuesIndex)
{
valuesJsonList[valuesIndex].AsString(m_values[valuesIndex]);
}
payload.WithArray("Values", std::move(valuesJsonList));
}
return payload;
}
} // namespace Model
} // namespace ResourceGroups
} // namespace Aws
|
#include "chinamapwidgetobjectpoint.h"
ChinaMapWidgetObjectPoint::ChinaMapWidgetObjectPoint(QObject* parent)
: QObject(parent)
{
}
void ChinaMapWidgetObjectPoint::setGeoX(double geoX)
{
m_geoX = geoX;
}
void ChinaMapWidgetObjectPoint::setGeoY(double geoY)
{
m_geoY = geoY;
}
double ChinaMapWidgetObjectPoint::geoX()
{
return m_geoX;
}
double ChinaMapWidgetObjectPoint::geoY()
{
return m_geoY;
}
void ChinaMapWidgetObjectPoint::setScreenX(double screenX)
{
m_screenX = screenX;
}
void ChinaMapWidgetObjectPoint::setScreenY(double screenY)
{
m_screenY = screenY;
}
double ChinaMapWidgetObjectPoint::screenX()
{
return m_screenX;
}
double ChinaMapWidgetObjectPoint::screenY()
{
return m_screenY;
}
|
#include "HCISocket.h"
namespace WPEFramework {
namespace Bluetooth {
template <const uint16_t OPCODE, typename OUTBOUND>
class ManagementType : public Core::IOutbound {
private:
ManagementType() = delete;
ManagementType(const ManagementType<OPCODE, OUTBOUND>&) = delete;
ManagementType<OPCODE, OUTBOUND>& operator=(const ManagementType<OPCODE, OUTBOUND>&) = delete;
public:
ManagementType(const uint16_t adapterIndex)
: _offset(sizeof(_buffer))
{
_buffer[0] = (OPCODE & 0xFF);
_buffer[1] = (OPCODE >> 8) & 0xFF;
_buffer[2] = (adapterIndex & 0xFF);
_buffer[3] = ((adapterIndex >> 8) & 0xFF);
_buffer[4] = static_cast<uint8_t>(sizeof(OUTBOUND) & 0xFF);
_buffer[5] = static_cast<uint8_t>((sizeof(OUTBOUND) >> 8) & 0xFF);
}
virtual ~ManagementType()
{
}
public:
void Clear()
{
::memset(&(_buffer[6]), 0, sizeof(_buffer) - 6);
}
OUTBOUND* operator->()
{
return (reinterpret_cast<OUTBOUND*>(&(_buffer[6])));
}
Core::IOutbound& OpCode(const uint16_t opCode, const OUTBOUND& value)
{
_buffer[0] = (opCode & 0xFF);
_buffer[1] = ((opCode >> 8) & 0xFF);
::memcpy(reinterpret_cast<OUTBOUND*>(&(_buffer[6])), &value, sizeof(OUTBOUND));
return (*this);
}
private:
virtual void Reload() const override
{
_offset = 0;
}
virtual uint16_t Serialize(uint8_t stream[], const uint16_t length) const override
{
uint16_t result = std::min(static_cast<uint16_t>(sizeof(_buffer) - _offset), length);
if (result > 0) {
::memcpy(stream, &(_buffer[_offset]), result);
// for (uint8_t index = 0; index < result; index++) { printf("%02X:", stream[index]); } printf("\n");
_offset += result;
}
return (result);
}
private:
mutable uint16_t _offset;
uint8_t _buffer[6 + sizeof(OUTBOUND)];
};
// ------------------------------------------------------------------------
// Create definitions for the Management commands
// ------------------------------------------------------------------------
static constexpr mgmt_mode DISABLE_MODE = { 0x00 };
static constexpr mgmt_mode ENABLE_MODE = { 0x01 };
struct Management {
typedef ManagementType<~0, mgmt_mode> OperationalMode;
typedef ManagementType<MGMT_OP_PAIR_DEVICE, mgmt_cp_pair_device> Pair;
typedef ManagementType<MGMT_OP_UNPAIR_DEVICE, mgmt_cp_unpair_device> Unpair;
};
uint32_t HCISocket::Config(const bool powered, const bool bondable, const bool advertising, const bool simplePairing, const bool lowEnergy, const bool secure)
{
uint32_t result = Core::ERROR_GENERAL;
Management::OperationalMode command(SocketPort::LocalNode().PortNumber());
ASSERT (IsOpen() == true);
if (Exchange(500, command.OpCode(MGMT_OP_SET_POWERED, powered ? ENABLE_MODE : DISABLE_MODE)) != Core::ERROR_NONE) {
TRACE_L1("Failed to power on bluetooth adaptor");
}
// Enable/Disable Bondable on adaptor.
else if (Exchange(500, command.OpCode(MGMT_OP_SET_BONDABLE, bondable ? ENABLE_MODE : DISABLE_MODE)) != Core::ERROR_NONE) {
TRACE_L1("Failed to enable Bondable");
}
// Enable/Disable Simple Secure Simple Pairing.
else if (Exchange(500, command.OpCode(MGMT_OP_SET_SSP, simplePairing ? ENABLE_MODE : DISABLE_MODE)) != Core::ERROR_NONE) {
TRACE_L1("Failed to enable Simple Secure Simple Pairing");
}
// Enable/Disable Low Energy
else if (Exchange(500, command.OpCode(MGMT_OP_SET_LE, lowEnergy ? ENABLE_MODE : DISABLE_MODE)) != Core::ERROR_NONE) {
TRACE_L1("Failed to enable Low Energy");
}
// Enable/Disable Secure Connections
else if (Exchange(500, command.OpCode(MGMT_OP_SET_SECURE_CONN, secure ? ENABLE_MODE : DISABLE_MODE)) != Core::ERROR_NONE) {
TRACE_L1("Failed to enable Secure Connections");
}
// Enable/Disable Advertising
else if (Exchange(500, command.OpCode(MGMT_OP_SET_ADVERTISING, advertising ? ENABLE_MODE : DISABLE_MODE)) != Core::ERROR_NONE) {
TRACE_L1("Failed to enable Advertising");
}
else {
result = Core::ERROR_NONE;
}
return (result);
}
uint32_t HCISocket::Advertising(const bool enable, const uint8_t mode)
{
uint32_t result = Core::ERROR_ILLEGAL_STATE;
if (enable == true) {
if (IsAdvertising() == false) {
result = Core::ERROR_BAD_REQUEST;
Command::AdvertisingParametersLE parameters;
parameters.Clear();
parameters->min_interval = htobs(0x0800);
parameters->max_interval = htobs(0x0800);
parameters->advtype = mode;
parameters->chan_map = 7;
if ((Exchange(MAX_ACTION_TIMEOUT, parameters, parameters) == Core::ERROR_NONE) && (parameters.Response() == 0)) {
Command::AdvertisingEnableLE advertising;
advertising.Clear();
advertising->enable = 1;
if ((Exchange(MAX_ACTION_TIMEOUT, advertising, advertising) == Core::ERROR_NONE) && (advertising.Response() == 0)) {
_state.SetState(static_cast<state>(_state.GetState() | ADVERTISING));
result = Core::ERROR_NONE;
}
}
}
} else if (IsAdvertising() == true) {
result = Core::ERROR_BAD_REQUEST;
Command::AdvertisingEnableLE advertising;
advertising.Clear();
advertising->enable = 0;
if ((Exchange(MAX_ACTION_TIMEOUT, advertising, advertising) == Core::ERROR_NONE) && (advertising.Response() == 0)) {
_state.SetState(static_cast<state>(_state.GetState() & (~ADVERTISING)));
result = Core::ERROR_NONE;
}
}
return (result);
}
void HCISocket::Scan(const uint16_t scanTime, const uint32_t type, const uint8_t flags)
{
ASSERT(scanTime <= 326);
_state.Lock();
if ((_state & ACTION_MASK) == 0) {
int descriptor = Handle();
_state.SetState(static_cast<state>(_state.GetState() | SCANNING));
_state.Unlock();
ASSERT(descriptor >= 0);
void* buf = ALLOCA(sizeof(struct hci_inquiry_req) + (sizeof(inquiry_info) * 128));
struct hci_inquiry_req* ir = reinterpret_cast<struct hci_inquiry_req*>(buf);
std::list<Address> reported;
ir->dev_id = hci_get_route(nullptr);
ir->num_rsp = 128;
ir->length = (((scanTime * 100) + 50) / 128);
ir->flags = flags | IREQ_CACHE_FLUSH;
ir->lap[0] = (type >> 16) & 0xFF; // 0x33;
ir->lap[1] = (type >> 8) & 0xFF; // 0x8b;
ir->lap[2] = type & 0xFF; // 0x9e;
// Core::Time endTime = Core::Time::Now().Add(scanTime * 1000);
// while ((ir->length != 0) && (ioctl(descriptor, HCIINQUIRY, reinterpret_cast<unsigned long>(buf)) >= 0)) {
if (ioctl(descriptor, HCIINQUIRY, reinterpret_cast<unsigned long>(buf)) >= 0) {
for (uint8_t index = 0; index < (ir->num_rsp); index++) {
inquiry_info* info = reinterpret_cast<inquiry_info*>(&(reinterpret_cast<uint8_t*>(buf)[sizeof(hci_inquiry_req)]));
bdaddr_t* address = &(info[index].bdaddr);
Address newSource(*address);
std::list<Address>::const_iterator finder(std::find(reported.begin(), reported.end(), newSource));
if (finder == reported.end()) {
reported.push_back(newSource);
Discovered(false, newSource, _T("[Unknown]"));
}
}
// Reset go for the next round !!
// ir->length = (endTime <= Core::Time::Now() ? 0 : 1);
// ir->num_rsp = 128;
// ir->flags &= ~IREQ_CACHE_FLUSH;
}
_state.Lock();
_state.SetState(static_cast<state>(_state.GetState() & (~(ABORT | SCANNING))));
}
_state.Unlock();
}
void HCISocket::Scan(const uint16_t scanTime, const bool limited, const bool passive)
{
_state.Lock();
if ((_state & ACTION_MASK) == 0) {
Command::ScanParametersLE parameters;
parameters.Clear();
parameters->type = (passive ? 0x00 : 0x01);
parameters->interval = htobs((limited ? 0x12 : 0x10));
parameters->window = htobs((limited ? 0x12 : 0x10));
parameters->own_bdaddr_type = LE_PUBLIC_ADDRESS;
parameters->filter = SCAN_FILTER_POLICY;
if ((Exchange(MAX_ACTION_TIMEOUT, parameters, parameters) == Core::ERROR_NONE) && (parameters.Response() == 0)) {
Command::ScanEnableLE scanner;
scanner.Clear();
scanner->enable = 1;
scanner->filter_dup = SCAN_FILTER_DUPLICATES;
if ((Exchange(MAX_ACTION_TIMEOUT, scanner, scanner) == Core::ERROR_NONE) && (scanner.Response() == 0)) {
_state.SetState(static_cast<state>(_state.GetState() | SCANNING));
// Now lets wait for the scanning period..
_state.Unlock();
_state.WaitState(ABORT, scanTime * 1000);
_state.Lock();
scanner->enable = 0;
Exchange(MAX_ACTION_TIMEOUT, scanner, scanner);
_state.SetState(static_cast<state>(_state.GetState() & (~(ABORT | SCANNING))));
}
}
}
_state.Unlock();
}
uint32_t HCISocket::Pair(const Address& remote, const uint8_t type, const capabilities cap)
{
uint32_t result = Core::ERROR_INPROGRESS;
_state.Lock();
if ((_state & ACTION_MASK) == 0) {
_state.SetState(static_cast<state>(_state.GetState() | PAIRING));
_state.Unlock();
Management::Pair command(0);
command.Clear();
command->addr.bdaddr = *remote.Data();
command->addr.type = type;
command->io_cap = cap;
result = Core::ERROR_NONE;
result = Exchange(MAX_ACTION_TIMEOUT, command);
_state.Lock();
_state.SetState(static_cast<state>(_state.GetState() & (~(ABORT | PAIRING))));
}
_state.Unlock();
return (result);
}
uint32_t HCISocket::Unpair(const Address& remote, const uint8_t type)
{
uint32_t result = Core::ERROR_INPROGRESS;
_state.Lock();
if ((_state & ACTION_MASK) == 0) {
_state.SetState(static_cast<state>(_state.GetState() | PAIRING));
_state.Unlock();
Management::Unpair command(0);
command.Clear();
command->addr.bdaddr = *remote.Data();
command->addr.type = type;
command->disconnect = 1;
result = Exchange(MAX_ACTION_TIMEOUT, command);
_state.SetState(static_cast<state>(_state.GetState() & (~(ABORT | PAIRING))));
}
_state.Unlock();
return (result);
}
void HCISocket::Abort()
{
_state.Lock();
if ((_state & ACTION_MASK) != 0) {
// TODO: Find if we can actually abort a IOCTL:HCIINQUIRY !!
_state.SetState(static_cast<state>(_state.GetState() | ABORT));
}
_state.Unlock();
}
/* virtual */ void HCISocket::StateChange()
{
Core::SynchronousChannelType<Core::SocketPort>::StateChange();
if (IsOpen() == true) {
hci_filter_clear(&_filter);
hci_filter_set_ptype(HCI_EVENT_PKT, &_filter);
hci_filter_set_event(EVT_CMD_STATUS, &_filter);
hci_filter_set_event(EVT_CMD_COMPLETE, &_filter);
hci_filter_set_event(EVT_LE_META_EVENT, &_filter);
// Interesting why this needs to be set.... I hope not!!
// hci_filter_set_opcode(0, &_filter);
setsockopt(Handle(), SOL_HCI, HCI_FILTER, &_filter, sizeof(_filter));
}
}
/* virtual */ uint16_t HCISocket::Deserialize(const uint8_t* dataFrame, const uint16_t availableData)
{
const hci_event_hdr* hdr = reinterpret_cast<const hci_event_hdr*>(&(dataFrame[1]));
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(&(dataFrame[1 + HCI_EVENT_HDR_SIZE]));
if ( (hdr->evt != EVT_LE_META_EVENT) || (reinterpret_cast<const evt_le_meta_event*>(ptr)->subevent != EVT_LE_ADVERTISING_REPORT) ) {
Update(*hdr);
}
else {
const le_advertising_info* advertisingInfo = reinterpret_cast<const le_advertising_info*>(&(reinterpret_cast<const evt_le_meta_event*>(ptr)->data[1]));
uint16_t offset = 0;
const uint8_t* buffer = advertisingInfo->data;
const char* name = nullptr;
uint8_t pos = 0;
while (((offset + buffer[offset]) <= advertisingInfo->length) && (buffer[offset] != 0)) {
if (((buffer[offset + 1] == EIR_NAME_SHORT) && (name == nullptr)) || (buffer[offset + 1] == EIR_NAME_COMPLETE)) {
name = reinterpret_cast<const char*>(&(buffer[offset + 2]));
pos = buffer[offset] - 1;
}
offset += (buffer[offset] + 1);
}
if ((name == nullptr) || (pos == 0)) {
TRACE_L1("Entry[%s] has no name.", Address(advertisingInfo->bdaddr).ToString());
Discovered(false, Address(advertisingInfo->bdaddr), _T("[Unknown]"));
} else {
Discovered(true, Address(advertisingInfo->bdaddr), string(name, pos));
}
}
return (availableData);
}
/* virtual */ void HCISocket::Update(const hci_event_hdr& eventData)
{
}
/* virtual */ void HCISocket::Discovered(const bool lowEnergy, const Bluetooth::Address& address, const string& name)
{
}
void HCISocket::SetOpcode(const uint16_t opcode)
{
hci_filter_set_opcode(opcode, &_filter);
setsockopt(Handle(), SOL_HCI, HCI_FILTER, &_filter, sizeof(_filter));
}
} // namespace Bluetooth
} // namespace WPEFramework
|
#include "common.hpp"
{% from "mod/batch.cpp" import batch -%}
{% from "mod/binary.cpp" import inner, outer -%}
{% call(name, shape) batch() -%}
{% call(x, y) outer("Pow", name, shape) -%}
{% set r = numpy.random.rayleigh(size=x).astype(numpy.float32) -%}
{% set a = numpy.random.randn(*y).astype(numpy.float32) -%}
{{ inner(r**a, r, a) }}
{% set b = numpy.random.randint(0, 16, y, numpy.int8) -%}
{{ inner((-r)**b, -r, b) }}
{% endcall -%}
{% endcall -%}
{# vim: set ft=liquid: #}
|
#include "PositionInvertedIndexTestFixture.h"
#include <boost/test/unit_test.hpp>
#include <util/ClockTimer.h>
NS_IZENELIB_IR_BEGIN
using namespace Zambezi;
BOOST_AUTO_TEST_SUITE(t_index_search)
BOOST_AUTO_TEST_CASE(do_search_BWAND_AND_revserse)
{
std::cout <<"test case 1: [do_search_BWAND_AND_revserse] ..." << std::endl;
uint32_t DocNum = 300000;
PositionInvertedIndexTestFixture indexTestFixture;
bool reverse = true;
indexTestFixture.initIndexer(DocNum, reverse);
std::vector<std::string> term_list;
std::vector<uint32_t> docid_list;
term_list.push_back("abc");
term_list.push_back("abd");
term_list.push_back("abe");
indexTestFixture.search(term_list, docid_list, BWAND_AND);
BOOST_CHECK_EQUAL(docid_list.size(), 260000);
BOOST_CHECK_EQUAL(docid_list[0], 300000);
BOOST_CHECK_EQUAL(docid_list[1], 299999);
BOOST_CHECK_EQUAL(docid_list[2], 299998);
BOOST_CHECK_EQUAL(docid_list[3], 299997);
BOOST_CHECK_EQUAL(docid_list[4], 299996);
BOOST_CHECK_EQUAL(docid_list[5], 299995);
BOOST_CHECK_EQUAL(docid_list[6], 299994);
BOOST_CHECK_EQUAL(docid_list[7], 299993);
BOOST_CHECK_EQUAL(docid_list[8], 299992);
BOOST_CHECK_EQUAL(docid_list[9], 299991);
BOOST_CHECK_EQUAL(docid_list[10], 299990);
BOOST_CHECK_EQUAL(docid_list[11], 299989);
BOOST_CHECK_EQUAL(docid_list[12], 299988);
BOOST_CHECK_EQUAL(docid_list[13], 299985);
BOOST_CHECK_EQUAL(docid_list[14], 299984);
BOOST_CHECK_EQUAL(docid_list[15], 299983);
term_list.clear();
docid_list.clear();
term_list.push_back("abd");
term_list.push_back("abq");
indexTestFixture.search(term_list, docid_list, BWAND_AND);
BOOST_CHECK_EQUAL(docid_list.size(), 20000);
BOOST_CHECK_EQUAL(docid_list[0], 300000);
BOOST_CHECK_EQUAL(docid_list[1], 299985);
BOOST_CHECK_EQUAL(docid_list[2], 299970);
BOOST_CHECK_EQUAL(docid_list[3], 299955);
}
BOOST_AUTO_TEST_CASE(do_search_BWAND_AND_forward)
{
std::cout << std::endl <<"test case 2: [do_search_BWAND_AND_forward] ..." << std::endl;
uint32_t DocNum = 300000;
PositionInvertedIndexTestFixture indexTestFixture;
bool reverse = false;
indexTestFixture.initIndexer(DocNum, reverse);
std::vector<std::string> term_list;
std::vector<uint32_t> docid_list;
term_list.push_back("abc");
term_list.push_back("abd");
term_list.push_back("abe");
indexTestFixture.search(term_list, docid_list, BWAND_AND);
BOOST_CHECK_EQUAL(docid_list.size(), 260000);
BOOST_CHECK_EQUAL(docid_list[0], 3);
BOOST_CHECK_EQUAL(docid_list[1], 4);
BOOST_CHECK_EQUAL(docid_list[2], 5);
BOOST_CHECK_EQUAL(docid_list[3], 6);
BOOST_CHECK_EQUAL(docid_list[4], 7);
BOOST_CHECK_EQUAL(docid_list[5], 8);
BOOST_CHECK_EQUAL(docid_list[6], 9);
BOOST_CHECK_EQUAL(docid_list[7], 10);
BOOST_CHECK_EQUAL(docid_list[8], 11);
BOOST_CHECK_EQUAL(docid_list[9], 12);
BOOST_CHECK_EQUAL(docid_list[10], 13);
BOOST_CHECK_EQUAL(docid_list[11], 14);
BOOST_CHECK_EQUAL(docid_list[12], 15);
BOOST_CHECK_EQUAL(docid_list[13], 18); // ok
BOOST_CHECK_EQUAL(docid_list[14], 19); // ok
BOOST_CHECK_EQUAL(docid_list[15], 20); // ok
term_list.clear();
docid_list.clear();
term_list.push_back("abd");
term_list.push_back("abq");
indexTestFixture.search(term_list, docid_list, BWAND_AND);
BOOST_CHECK_EQUAL(docid_list.size(), 20000);
BOOST_CHECK_EQUAL(docid_list[0], 15);
BOOST_CHECK_EQUAL(docid_list[1], 30);
BOOST_CHECK_EQUAL(docid_list[2], 45);
BOOST_CHECK_EQUAL(docid_list[3], 60);
}
// BOOST_AUTO_TEST_CASE(do_search_BWAND_OR_revserse)
// {
// std::cout <<"test case 3: [do_search_BWAND_OR_revserse] ..." << std::endl;
// uint32_t DocNum = 300000;
// PositionInvertedIndexTestFixture indexTestFixture;
// bool reverse = true;
// indexTestFixture.initIndexer(DocNum, reverse);
// std::vector<std::string> term_list;
// std::vector<uint32_t> docid_list;
// term_list.push_back("abc");
// term_list.push_back("abd");
// term_list.push_back("abe");
// indexTestFixture.search(term_list, docid_list, BWAND_OR);
// BOOST_CHECK_EQUAL(docid_list.size(), 300000);
// BOOST_CHECK_EQUAL(docid_list[0], 1);
// BOOST_CHECK_EQUAL(docid_list[299999], 300000);
// term_list.clear();
// docid_list.clear();
// term_list.push_back("abd");
// term_list.push_back("abq");
// indexTestFixture.search(term_list, docid_list, BWAND_OR);
// BOOST_CHECK_EQUAL(docid_list.size(), 20000);
// term_list.clear();
// docid_list.clear();
// term_list.push_back("abd");
// term_list.push_back("abq");
// indexTestFixture.search(term_list, docid_list, BWAND_OR);
// BOOST_CHECK_EQUAL(docid_list.size(), 280000);
// term_list.clear();
// docid_list.clear();
// term_list.push_back("abe");
// term_list.push_back("abq");
// indexTestFixture.search(term_list, docid_list, BWAND_OR);
// BOOST_CHECK_EQUAL(docid_list.size(), 260000);
// }
// BOOST_AUTO_TEST_CASE(do_search_BWAND_OR_forward)
// {
// std::cout << std::endl <<"test case 4: [do_search_BWAND_OR_forward] ..." << std::endl;
// uint32_t DocNum = 300000;
// PositionInvertedIndexTestFixture indexTestFixture;
// bool reverse = false;
// indexTestFixture.initIndexer(DocNum, reverse);
// std::vector<std::string> term_list;
// std::vector<uint32_t> docid_list;
// term_list.push_back("abc");
// term_list.push_back("abd");
// term_list.push_back("abe");
// indexTestFixture.search(term_list, docid_list, BWAND_OR);
// BOOST_CHECK_EQUAL(docid_list.size(), 300000);
// BOOST_CHECK_EQUAL(docid_list[0], 1);
// BOOST_CHECK_EQUAL(docid_list[299999], 300000);
// term_list.clear();
// docid_list.clear();
// term_list.push_back("abd");
// term_list.push_back("abq");
// indexTestFixture.search(term_list, docid_list, BWAND_OR);
// BOOST_CHECK_EQUAL(docid_list.size(), 20000);
// term_list.clear();
// docid_list.clear();
// term_list.push_back("abd");
// term_list.push_back("abq");
// indexTestFixture.search(term_list, docid_list, BWAND_OR);
// BOOST_CHECK_EQUAL(docid_list.size(), 280000);
// term_list.clear();
// docid_list.clear();
// term_list.push_back("abe");
// term_list.push_back("abq");
// indexTestFixture.search(term_list, docid_list, BWAND_OR);
// BOOST_CHECK_EQUAL(docid_list.size(), 260000);
// }
BOOST_AUTO_TEST_CASE(do_search_SVS_forward)
{
std::cout << std::endl <<"test case 5: [do_search_SVS_forward] ..." << std::endl;
uint32_t DocNum = 10000000;
PositionInvertedIndexTestFixture indexTestFixture;
bool reverse = false;
indexTestFixture.initBIGIndexer(DocNum, reverse);
std::vector<std::string> wordlist = indexTestFixture.getWordList();
for (int i = 0; i < 100; ++i)
{
std::vector<std::string> term_list;
std::vector<uint32_t> docid_list;
term_list.push_back(wordlist[i]);
term_list.push_back(wordlist[i+1]);
term_list.push_back(wordlist[i+2]);
indexTestFixture.search(term_list, docid_list, SVS);
std::cout << "search: " << wordlist[i] << " / " << wordlist[i+1] << " / " << wordlist[i+2]
<< " :" <<docid_list.size() << std::endl;
}
}
BOOST_AUTO_TEST_CASE(do_search_SVS_reverse)
{
std::cout << std::endl <<"test case 6: [do_search_SVS_reverse] ..." << std::endl;
uint32_t DocNum = 10000000;
PositionInvertedIndexTestFixture indexTestFixture;
bool reverse = true;
indexTestFixture.initBIGIndexer(DocNum, reverse);
std::vector<std::string> wordlist = indexTestFixture.getWordList();
izenelib::util::ClockTimer timer;
for (int i = 0; i < 100; ++i)
{
std::vector<std::string> term_list;
std::vector<uint32_t> docid_list;
term_list.push_back(wordlist[i]);
term_list.push_back(wordlist[i+1]);
term_list.push_back(wordlist[i+2]);
indexTestFixture.search(term_list, docid_list, SVS);
std::cout << "search: " << wordlist[i] << " / " << wordlist[i+1] << " / " << wordlist[i+2]
<< " :" <<docid_list.size() << std::endl;
}
std::cout <<"search 100 queries cost:" << timer.elapsed() << std::endl;
}
BOOST_AUTO_TEST_CASE(do_index_save_load_reverse_SVS)
{
std::cout << std::endl <<"test case 7: [do_index_save_load_reverse_SVS] ..." << std::endl;
uint32_t DocNum = 2000000;
std::vector<std::string> wordlist;
uint32_t wordNumber = 100;
std::vector<uint32_t> resultNumber;
bool reverse = true;
///save
{
PositionInvertedIndexTestFixture indexTestFixture;
indexTestFixture.initBIGIndexer(DocNum, reverse);
wordlist = indexTestFixture.getWordList();
for (unsigned int i = 0; i < wordNumber; ++i)
{
std::vector<std::string> term_list;
std::vector<uint32_t> docid_list;
term_list.push_back(wordlist[i]);
term_list.push_back(wordlist[i+1]);
//term_list.push_back(wordlist[i+2]);
indexTestFixture.search(term_list, docid_list, SVS);
resultNumber.push_back(docid_list.size());
}
std::cout << "\nBegin save index ..." << std::endl;
indexTestFixture.saveIndex("Position_zambezi.reverse");
std::cout << "Save index finished..." << std::endl;
}
/// load
{
PositionInvertedIndexTestFixture indexTestFixture1;
indexTestFixture1.initBIGIndexer(0, reverse);
std::cout << "\nBegin load index ..." << std::endl;
indexTestFixture1.loadIndex("Position_zambezi.reverse");
std::cout << "Load index finished..." << std::endl;
for (unsigned int i = 0; i < wordNumber; ++i)
{
std::vector<std::string> term_list;
std::vector<uint32_t> docid_list;
term_list.push_back(wordlist[i]);
term_list.push_back(wordlist[i+1]);
//term_list.push_back(wordlist[i+2]);
indexTestFixture1.search(term_list, docid_list, SVS);
BOOST_CHECK_EQUAL(docid_list.size(), resultNumber[i]);
}
}
}
BOOST_AUTO_TEST_CASE(do_index_save_load_forward_SVS)
{
std::cout << std::endl <<"test case 8: [do_index_save_load_forward_SVS] ..." << std::endl;
uint32_t DocNum = 2000000;
std::vector<std::string> wordlist;
uint32_t wordNumber = 100;
std::vector<uint32_t> resultNumber;
bool reverse = false;
///save
{
PositionInvertedIndexTestFixture indexTestFixture;
indexTestFixture.initBIGIndexer(DocNum, reverse);
wordlist = indexTestFixture.getWordList();
for (unsigned int i = 0; i < wordNumber; ++i)
{
std::vector<std::string> term_list;
std::vector<uint32_t> docid_list;
term_list.push_back(wordlist[i]);
term_list.push_back(wordlist[i+1]);
indexTestFixture.search(term_list, docid_list, SVS);
resultNumber.push_back(docid_list.size());
//std::cout << "docid_list.size()" << docid_list.size() << std::endl;
}
std::cout << "\nBegin save index ..." << std::endl;
indexTestFixture.saveIndex("Position_zambezi.forward");
std::cout << "Save index finished..." << std::endl;
}
/// load
{
PositionInvertedIndexTestFixture indexTestFixture1;
indexTestFixture1.initBIGIndexer(0, reverse);
std::cout << "\nBegin load index ..." << std::endl;
indexTestFixture1.loadIndex("Position_zambezi.forward");
std::cout << "Load index finished..." << std::endl;
for (unsigned int i = 0; i < wordNumber; ++i)
{
std::vector<std::string> term_list;
std::vector<uint32_t> docid_list;
term_list.push_back(wordlist[i]);
term_list.push_back(wordlist[i+1]);
indexTestFixture1.search(term_list, docid_list, SVS);
BOOST_CHECK_EQUAL(docid_list.size(), resultNumber[i]);
}
}
}
BOOST_AUTO_TEST_SUITE_END()
NS_IZENELIB_IR_END
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txdb.h"
#include "walletdb.h"
#include "bitcoinrpc.h"
#include "net.h"
#include "init.h"
#include "util.h"
#include "ui_interface.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <openssl/crypto.h>
#ifndef WIN32
#include <signal.h>
#endif
using namespace std;
using namespace boost;
CWallet* pwalletMain;
CClientUIInterface uiInterface;
#ifdef WIN32
// Win32 LevelDB doesn't use filedescriptors, and the ones used for
// accessing block files, don't count towards to fd_set size limit
// anyway.
#define MIN_CORE_FILEDESCRIPTORS 0
#else
#define MIN_CORE_FILEDESCRIPTORS 150
#endif
// Used to pass flags to the Bind() function
enum BindFlags {
BF_NONE = 0,
BF_EXPLICIT = (1U << 0),
BF_REPORT_ERROR = (1U << 1)
};
//////////////////////////////////////////////////////////////////////////////
//
// Shutdown
//
//
// Thread management and startup/shutdown:
//
// The network-processing threads are all part of a thread group
// created by AppInit() or the Qt main() function.
//
// A clean exit happens when StartShutdown() or the SIGTERM
// signal handler sets fRequestShutdown, which triggers
// the DetectShutdownThread(), which interrupts the main thread group.
// DetectShutdownThread() then exits, which causes AppInit() to
// continue (it .joins the shutdown thread).
// Shutdown() is then
// called to clean up database connections, and stop other
// threads that should only be stopped after the main network-processing
// threads have exited.
//
// Note that if running -daemon the parent process returns from AppInit2
// before adding any threads to the threadGroup, so .join_all() returns
// immediately and the parent exits from main().
//
// Shutdown for Qt is very similar, only it uses a QTimer to detect
// fRequestShutdown getting set, and then does the normal Qt
// shutdown thing.
//
volatile bool fRequestShutdown = false;
void StartShutdown()
{
fRequestShutdown = true;
}
bool ShutdownRequested()
{
return fRequestShutdown;
}
static CCoinsViewDB *pcoinsdbview;
void Shutdown()
{
printf("Shutdown : In progress...\n");
static CCriticalSection cs_Shutdown;
TRY_LOCK(cs_Shutdown, lockShutdown);
if (!lockShutdown) return;
RenameThread("bitcoin-shutoff");
nTransactionsUpdated++;
StopRPCThreads();
ShutdownRPCMining();
if (pwalletMain)
bitdb.Flush(false);
GenerateBitcoins(false, NULL);
StopNode();
{
LOCK(cs_main);
if (pwalletMain)
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
if (pblocktree)
pblocktree->Flush();
if (pcoinsTip)
pcoinsTip->Flush();
delete pcoinsTip; pcoinsTip = NULL;
delete pcoinsdbview; pcoinsdbview = NULL;
delete pblocktree; pblocktree = NULL;
}
if (pwalletMain)
bitdb.Flush(true);
boost::filesystem::remove(GetPidFile());
UnregisterWallet(pwalletMain);
if (pwalletMain)
delete pwalletMain;
printf("Shutdown : done\n");
}
//
// Signal handlers are very limited in what they are allowed to do, so:
//
void DetectShutdownThread(boost::thread_group* threadGroup)
{
// Tell the main threads to shutdown.
while (!fRequestShutdown)
{
MilliSleep(200);
if (fRequestShutdown)
threadGroup->interrupt_all();
}
}
void HandleSIGTERM(int)
{
fRequestShutdown = true;
}
void HandleSIGHUP(int)
{
fReopenDebugLog = true;
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
#if !defined(QT_GUI)
bool AppInit(int argc, char* argv[])
{
boost::thread_group threadGroup;
boost::thread* detectShutdownThread = NULL;
bool fRet = false;
try
{
//
// Parameters
//
// If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
ParseParameters(argc, argv);
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified directory does not exist\n");
Shutdown();
}
ReadConfigFile(mapArgs, mapMultiArgs);
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
// First part of help message is specific to bitcoind / RPC client
std::string strUsage = _("GreenCoin version") + " " + FormatFullVersion() + "\n\n" +
_("Usage:") + "\n" +
" greencoind [options] " + "\n" +
" greencoind [options] <command> [params] " + _("Send command to -server or GreenCoind") + "\n" +
" greencoind [options] help " + _("List commands") + "\n" +
" greencoind [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessage();
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
// Command-line RPC
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "GreenCoin:"))
fCommandLine = true;
if (fCommandLine)
{
int ret = CommandLineRPC(argc, argv);
exit(ret);
}
#if !defined(WIN32)
fDaemon = GetBoolArg("-daemon");
if (fDaemon)
{
// Daemonize
pid_t pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return false;
}
if (pid > 0) // Parent process, pid is child process id
{
CreatePidFile(GetPidFile(), pid);
return true;
}
// Child process falls through to rest of initialization
pid_t sid = setsid();
if (sid < 0)
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
#endif
detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));
fRet = AppInit2(threadGroup);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "AppInit()");
} catch (...) {
PrintExceptionContinue(NULL, "AppInit()");
}
if (!fRet) {
if (detectShutdownThread)
detectShutdownThread->interrupt();
threadGroup.interrupt_all();
}
if (detectShutdownThread)
{
detectShutdownThread->join();
delete detectShutdownThread;
detectShutdownThread = NULL;
}
Shutdown();
return fRet;
}
extern void noui_connect();
int main(int argc, char* argv[])
{
bool fRet = false;
// Connect bitcoind signal handlers
noui_connect();
fRet = AppInit(argc, argv);
if (fRet && fDaemon)
return 0;
return (fRet ? 0 : 1);
}
#endif
bool static InitError(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
return false;
}
bool static InitWarning(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
return true;
}
bool static Bind(const CService &addr, unsigned int flags) {
if (!(flags & BF_EXPLICIT) && IsLimited(addr))
return false;
std::string strError;
if (!BindListenPort(addr, strError)) {
if (flags & BF_REPORT_ERROR)
return InitError(strError);
return false;
}
return true;
}
// Core-specific options shared between UI and daemon
std::string HelpMessage()
{
string strUsage = _("Options:") + "\n" +
" -? " + _("This help message") + "\n" +
" -conf=<file> " + _("Specify configuration file (default: greencoin.conf)") + "\n" +
" -pid=<file> " + _("Specify pid file (default: greencoind.pid)") + "\n" +
" -gen " + _("Generate coins (default: 0)") + "\n" +
" -datadir=<dir> " + _("Specify data directory") + "\n" +
" -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" +
" -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" +
" -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" +
" -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
" -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
" -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
" -port=<port> " + _("Listen for connections on <port> (default: 11036 or testnet: 33449)") + "\n" +
" -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
" -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
" -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
" -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
" -externalip=<ip> " + _("Specify your own public address") + "\n" +
" -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n" +
" -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
" -checkpoints " + _("Only accept block chain matching built-in checkpoints (default: 1)") + "\n" +
" -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
" -bind=<addr> " + _("Bind to given address and always listen on it. Use [host]:port notation for IPv6") + "\n" +
" -dnsseed " + _("Find peers using DNS lookup (default: 1 unless -connect)") + "\n" +
" -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
" -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
" -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
" -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
" -bloomfilters " + _("Allow peers to set bloom filters (default: 1)") + "\n" +
#ifdef USE_UPNP
#if USE_UPNP
" -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" +
#else
" -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" +
#endif
#endif
" -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
" -mininput=<amt> " + _("When creating transactions, ignore inputs with value less than this (default: 0.0001)") + "\n" +
#ifdef QT_GUI
" -server " + _("Accept command line and JSON-RPC commands") + "\n" +
#endif
#if !defined(WIN32) && !defined(QT_GUI)
" -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
#endif
" -testnet " + _("Use the test network") + "\n" +
" -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
" -debugnet " + _("Output extra network debugging information") + "\n" +
" -logtimestamps " + _("Prepend debug output with timestamp (default: 1)") + "\n" +
" -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
" -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
#ifdef WIN32
" -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
#endif
" -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
" -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
" -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 21036 or testnet: 33450)") + "\n" +
" -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
#ifndef QT_GUI
" -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
#endif
" -rpcthreads=<n> " + _("Set the number of threads to service RPC calls (default: 4)") + "\n" +
" -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
" -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" +
" -alertnotify=<cmd> " + _("Execute command when a relevant alert is received (%s in cmd is replaced by message)") + "\n" +
" -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
" -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
" -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
" -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
" -checkblocks=<n> " + _("How many blocks to check at startup (default: 288, 0 = all)") + "\n" +
" -checklevel=<n> " + _("How thorough the block verification is (0-4, default: 3)") + "\n" +
" -txindex " + _("Maintain a full transaction index (default: 0)") + "\n" +
" -loadblock=<file> " + _("Imports blocks from external blk000??.dat file") + "\n" +
" -reindex " + _("Rebuild block chain index from current blk000??.dat files") + "\n" +
" -par=<n> " + _("Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)") + "\n" +
"\n" + _("Block creation options:") + "\n" +
" -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
" -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
" -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
"\n" + _("SSL options: (see the Greencoin Wiki for SSL setup instructions)") + "\n" +
" -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
" -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" +
" -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" +
" -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
return strUsage;
}
struct CImportingNow
{
CImportingNow() {
assert(fImporting == false);
fImporting = true;
}
~CImportingNow() {
assert(fImporting == true);
fImporting = false;
}
};
void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
{
RenameThread("bitcoin-loadblk");
// -reindex
if (fReindex) {
CImportingNow imp;
int nFile = 0;
while (true) {
CDiskBlockPos pos(nFile, 0);
FILE *file = OpenBlockFile(pos, true);
if (!file)
break;
printf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
LoadExternalBlockFile(file, &pos);
nFile++;
}
pblocktree->WriteReindexing(false);
fReindex = false;
printf("Reindexing finished\n");
// To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
InitBlockIndex();
}
// hardcoded $DATADIR/bootstrap.dat
filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
if (filesystem::exists(pathBootstrap)) {
FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
if (file) {
CImportingNow imp;
filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
printf("Importing bootstrap.dat...\n");
LoadExternalBlockFile(file);
RenameOver(pathBootstrap, pathBootstrapOld);
}
}
// -loadblock=
BOOST_FOREACH(boost::filesystem::path &path, vImportFiles) {
FILE *file = fopen(path.string().c_str(), "rb");
if (file) {
CImportingNow imp;
printf("Importing %s...\n", path.string().c_str());
LoadExternalBlockFile(file);
}
}
}
/** Initialize bitcoin.
* @pre Parameters should be parsed and config file should be read.
*/
bool AppInit2(boost::thread_group& threadGroup)
{
// ********************************************************* Step 1: setup
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
#if _MSC_VER >= 1400
// Disable confusing "helpful" text message on abort, Ctrl-C
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
#ifdef WIN32
// Enable Data Execution Prevention (DEP)
// Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
// A failure is non-critical and needs no further attention!
#ifndef PROCESS_DEP_ENABLE
// We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
// which is not correct. Can be removed, when GCCs winbase.h is fixed!
#define PROCESS_DEP_ENABLE 0x00000001
#endif
typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
// Initialize Windows Sockets
WSADATA wsadata;
int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
{
return InitError(strprintf("Error: Winsock library failed to start (WSAStartup returned error %d)", ret));
}
#endif
#ifndef WIN32
umask(077);
// Clean shutdown on SIGTERM
struct sigaction sa;
sa.sa_handler = HandleSIGTERM;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
// Reopen debug.log on SIGHUP
struct sigaction sa_hup;
sa_hup.sa_handler = HandleSIGHUP;
sigemptyset(&sa_hup.sa_mask);
sa_hup.sa_flags = 0;
sigaction(SIGHUP, &sa_hup, NULL);
#endif
// ********************************************************* Step 2: parameter interactions
fTestNet = GetBoolArg("-testnet");
fBloomFilters = GetBoolArg("-bloomfilters", true);
if (fBloomFilters)
nLocalServices |= NODE_BLOOM;
if (mapArgs.count("-bind")) {
// when specifying an explicit binding address, you want to listen on it
// even when -connect or -proxy is specified
SoftSetBoolArg("-listen", true);
}
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
// when only connecting to trusted nodes, do not seed via DNS, or listen by default
SoftSetBoolArg("-dnsseed", false);
SoftSetBoolArg("-listen", false);
}
if (mapArgs.count("-proxy")) {
// to protect privacy, do not listen by default if a proxy server is specified
SoftSetBoolArg("-listen", false);
}
if (!GetBoolArg("-listen", true)) {
// do not map ports or try to retrieve public IP when not listening (pointless)
SoftSetBoolArg("-upnp", false);
SoftSetBoolArg("-discover", false);
}
if (mapArgs.count("-externalip")) {
// if an explicit public IP is specified, do not try to find others
SoftSetBoolArg("-discover", false);
}
if (GetBoolArg("-salvagewallet")) {
// Rewrite just private keys: rescan to find transactions
SoftSetBoolArg("-rescan", true);
}
// Make sure enough file descriptors are available
int nBind = std::max((int)mapArgs.count("-bind"), 1);
nMaxConnections = GetArg("-maxconnections", 125);
nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
if (nFD < MIN_CORE_FILEDESCRIPTORS)
return InitError(_("Not enough file descriptors available."));
if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections)
nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS;
// ********************************************************* Step 3: parameter-to-internal-flags
fDebug = GetBoolArg("-debug");
fBenchmark = GetBoolArg("-benchmark");
// -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
nScriptCheckThreads = GetArg("-par", 0);
if (nScriptCheckThreads <= 0)
nScriptCheckThreads += boost::thread::hardware_concurrency();
if (nScriptCheckThreads <= 1)
nScriptCheckThreads = 0;
else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
// -debug implies fDebug*
if (fDebug)
fDebugNet = true;
else
fDebugNet = GetBoolArg("-debugnet");
if (fDaemon)
fServer = true;
else
fServer = GetBoolArg("-server");
/* force fServer when running without GUI */
#if !defined(QT_GUI)
fServer = true;
#endif
fPrintToConsole = GetBoolArg("-printtoconsole");
fPrintToDebugger = GetBoolArg("-printtodebugger");
fLogTimestamps = GetBoolArg("-logtimestamps", true);
bool fDisableWallet = GetBoolArg("-disablewallet", false);
if (mapArgs.count("-timeout"))
{
int nNewTimeout = GetArg("-timeout", 5000);
if (nNewTimeout > 0 && nNewTimeout < 600000)
nConnectTimeout = nNewTimeout;
}
// Continue to put "/P2SH/" in the coinbase to monitor
// BIP16 support.
// This can be removed eventually...
const char* pszP2SH = "/P2SH/";
COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
// Fee-per-kilobyte amount considered the same as "free"
// If you are mining, be careful setting this:
// if you set it to zero then
// a transaction spammer can cheaply fill blocks using
// 1-satoshi-fee transactions. It should be set above the real
// cost to you of processing a transaction.
if (mapArgs.count("-mintxfee"))
{
int64 n = 0;
if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
CTransaction::nMinTxFee = n;
else
return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"].c_str()));
}
if (mapArgs.count("-minrelaytxfee"))
{
int64 n = 0;
if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
CTransaction::nMinRelayTxFee = n;
else
return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"].c_str()));
}
if (mapArgs.count("-paytxfee"))
{
if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
if (nTransactionFee > 0.25 * COIN)
InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
}
if (mapArgs.count("-mininput"))
{
if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue))
return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str()));
}
// ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
std::string strDataDir = GetDataDir().string();
// Make sure only a single Bitcoin process is using the data directory.
boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
if (file) fclose(file);
static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
if (!lock.try_lock())
return InitError(strprintf(_("Cannot obtain a lock on data directory %s. GreenCoin is probably already running."), strDataDir.c_str()));
if (GetBoolArg("-shrinkdebugfile", !fDebug))
ShrinkDebugFile();
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
printf("GreenCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
if (!fLogTimestamps)
printf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
printf("Using data directory %s\n", strDataDir.c_str());
printf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
std::ostringstream strErrors;
if (fDaemon)
fprintf(stdout, "GreenCoin server starting\n");
if (nScriptCheckThreads) {
printf("Using %u threads for script verification\n", nScriptCheckThreads);
for (int i=0; i<nScriptCheckThreads-1; i++)
threadGroup.create_thread(&ThreadScriptCheck);
}
int64 nStart;
#if defined(USE_SSE2)
scrypt_detect_sse2();
#endif
// ********************************************************* Step 5: verify wallet database integrity
if (!fDisableWallet) {
uiInterface.InitMessage(_("Verifying wallet..."));
if (!bitdb.Open(GetDataDir()))
{
// try moving the database env out of the way
boost::filesystem::path pathDatabase = GetDataDir() / "database";
boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%"PRI64d".bak", GetTime());
try {
boost::filesystem::rename(pathDatabase, pathDatabaseBak);
printf("Moved old %s to %s. Retrying.\n", pathDatabase.string().c_str(), pathDatabaseBak.string().c_str());
} catch(boost::filesystem::filesystem_error &error) {
// failure is ok (well, not really, but it's not worse than what we started with)
}
// try again
if (!bitdb.Open(GetDataDir())) {
// if it still fails, it probably means we can't even create the database env
string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir.c_str());
return InitError(msg);
}
}
if (GetBoolArg("-salvagewallet"))
{
// Recover readable keypairs:
if (!CWalletDB::Recover(bitdb, "wallet.dat", true))
return false;
}
if (filesystem::exists(GetDataDir() / "wallet.dat"))
{
CDBEnv::VerifyResult r = bitdb.Verify("wallet.dat", CWalletDB::Recover);
if (r == CDBEnv::RECOVER_OK)
{
string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
" Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
" your balance or transactions are incorrect you should"
" restore from a backup."), strDataDir.c_str());
InitWarning(msg);
}
if (r == CDBEnv::RECOVER_FAIL)
return InitError(_("wallet.dat corrupt, salvage failed"));
}
} // (!fDisableWallet)
// ********************************************************* Step 6: network initialization
int nSocksVersion = GetArg("-socks", 5);
if (nSocksVersion != 4 && nSocksVersion != 5)
return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
if (mapArgs.count("-onlynet")) {
std::set<enum Network> nets;
BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
enum Network net = ParseNetwork(snet);
if (net == NET_UNROUTABLE)
return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
nets.insert(net);
}
for (int n = 0; n < NET_MAX; n++) {
enum Network net = (enum Network)n;
if (!nets.count(net))
SetLimited(net);
}
}
#if defined(USE_IPV6)
#if ! USE_IPV6
else
SetLimited(NET_IPV6);
#endif
#endif
CService addrProxy;
bool fProxy = false;
if (mapArgs.count("-proxy")) {
addrProxy = CService(mapArgs["-proxy"], 9050);
if (!addrProxy.IsValid())
return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
if (!IsLimited(NET_IPV4))
SetProxy(NET_IPV4, addrProxy, nSocksVersion);
if (nSocksVersion > 4) {
#ifdef USE_IPV6
if (!IsLimited(NET_IPV6))
SetProxy(NET_IPV6, addrProxy, nSocksVersion);
#endif
SetNameProxy(addrProxy, nSocksVersion);
}
fProxy = true;
}
// -tor can override normal proxy, -notor disables tor entirely
if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
CService addrOnion;
if (!mapArgs.count("-tor"))
addrOnion = addrProxy;
else
addrOnion = CService(mapArgs["-tor"], 9050);
if (!addrOnion.IsValid())
return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
SetProxy(NET_TOR, addrOnion, 5);
SetReachable(NET_TOR);
}
// see Step 2: parameter interactions for more information about these
fNoListen = !GetBoolArg("-listen", true);
fDiscover = GetBoolArg("-discover", true);
fNameLookup = GetBoolArg("-dns", true);
bool fBound = false;
if (!fNoListen) {
if (mapArgs.count("-bind")) {
BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
}
}
else {
struct in_addr inaddr_any;
inaddr_any.s_addr = INADDR_ANY;
#ifdef USE_IPV6
fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
#endif
fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
}
if (!fBound)
return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
}
if (mapArgs.count("-externalip")) {
BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
CService addrLocal(strAddr, GetListenPort(), fNameLookup);
if (!addrLocal.IsValid())
return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
}
}
BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
AddOneShot(strDest);
// ********************************************************* Step 7: load block chain
fReindex = GetBoolArg("-reindex");
// Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
filesystem::path blocksDir = GetDataDir() / "blocks";
if (!filesystem::exists(blocksDir))
{
filesystem::create_directories(blocksDir);
bool linked = false;
for (unsigned int i = 1; i < 10000; i++) {
filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
if (!filesystem::exists(source)) break;
filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
try {
filesystem::create_hard_link(source, dest);
printf("Hardlinked %s -> %s\n", source.string().c_str(), dest.string().c_str());
linked = true;
} catch (filesystem::filesystem_error & e) {
// Note: hardlink creation failing is not a disaster, it just means
// blocks will get re-downloaded from peers.
printf("Error hardlinking blk%04u.dat : %s\n", i, e.what());
break;
}
}
if (linked)
{
fReindex = true;
}
}
// cache size calculations
size_t nTotalCache = GetArg("-dbcache", 25) << 20;
if (nTotalCache < (1 << 22))
nTotalCache = (1 << 22); // total cache cannot be less than 4 MiB
size_t nBlockTreeDBCache = nTotalCache / 8;
if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false))
nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
nTotalCache -= nBlockTreeDBCache;
size_t nCoinDBCache = nTotalCache / 2; // use half of the remaining cache for coindb cache
nTotalCache -= nCoinDBCache;
nCoinCacheSize = nTotalCache / 300; // coins in memory require around 300 bytes
bool fLoaded = false;
while (!fLoaded) {
bool fReset = fReindex;
std::string strLoadError;
uiInterface.InitMessage(_("Loading block index..."));
nStart = GetTimeMillis();
do {
try {
UnloadBlockIndex();
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
if (fReindex)
pblocktree->WriteReindexing(true);
if (!LoadBlockIndex()) {
strLoadError = _("Error loading block database");
break;
}
// If the loaded chain has a wrong genesis, bail out immediately
// (we're likely using a testnet datadir, or the other way around).
if (!mapBlockIndex.empty() && pindexGenesisBlock == NULL)
return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
// Initialize the block index (no-op if non-empty database was already loaded)
if (!InitBlockIndex()) {
strLoadError = _("Error initializing block database");
break;
}
// Check for changed -txindex state
if (fTxIndex != GetBoolArg("-txindex", false)) {
strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
break;
}
uiInterface.InitMessage(_("Verifying blocks..."));
if (!VerifyDB(GetArg("-checklevel", 3),
GetArg( "-checkblocks", 288))) {
strLoadError = _("Corrupted block database detected");
break;
}
} catch(std::exception &e) {
strLoadError = _("Error opening block database");
break;
}
fLoaded = true;
} while(false);
if (!fLoaded) {
// first suggest a reindex
if (!fReset) {
bool fRet = uiInterface.ThreadSafeMessageBox(
strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
"", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
if (fRet) {
fReindex = true;
fRequestShutdown = false;
} else {
return false;
}
} else {
return InitError(strLoadError);
}
}
}
// as LoadBlockIndex can take several minutes, it's possible the user
// requested to kill bitcoin-qt during the last operation. If so, exit.
// As the program has not fully started yet, Shutdown() is possibly overkill.
if (fRequestShutdown)
{
printf("Shutdown requested. Exiting.\n");
return false;
}
printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
{
PrintBlockTree();
return false;
}
if (mapArgs.count("-printblock"))
{
string strMatch = mapArgs["-printblock"];
int nFound = 0;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
uint256 hash = (*mi).first;
if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
{
CBlockIndex* pindex = (*mi).second;
CBlock block;
block.ReadFromDisk(pindex);
block.BuildMerkleTree();
block.print();
printf("\n");
nFound++;
}
}
if (nFound == 0)
printf("No blocks matching %s were found\n", strMatch.c_str());
return false;
}
// ********************************************************* Step 8: load wallet
if (fDisableWallet) {
printf("Wallet disabled!\n");
pwalletMain = NULL;
} else {
uiInterface.InitMessage(_("Loading wallet..."));
nStart = GetTimeMillis();
bool fFirstRun = true;
pwalletMain = new CWallet("wallet.dat");
DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
if (nLoadWalletRet != DB_LOAD_OK)
{
if (nLoadWalletRet == DB_CORRUPT)
strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
{
string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect."));
InitWarning(msg);
}
else if (nLoadWalletRet == DB_TOO_NEW)
strErrors << _("Error loading wallet.dat: Wallet requires newer version of GreenCoin") << "\n";
else if (nLoadWalletRet == DB_NEED_REWRITE)
{
strErrors << _("Wallet needed to be rewritten: restart GreenCoin to complete") << "\n";
printf("%s", strErrors.str().c_str());
return InitError(strErrors.str());
}
else
strErrors << _("Error loading wallet.dat") << "\n";
}
if (GetBoolArg("-upgradewallet", fFirstRun))
{
int nMaxVersion = GetArg("-upgradewallet", 0);
if (nMaxVersion == 0) // the -upgradewallet without argument case
{
printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
nMaxVersion = CLIENT_VERSION;
pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
}
else
printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
if (nMaxVersion < pwalletMain->GetVersion())
strErrors << _("Cannot downgrade wallet") << "\n";
pwalletMain->SetMaxVersion(nMaxVersion);
}
if (fFirstRun)
{
// Create new keyUser and set as default key
RandAddSeedPerfmon();
CPubKey newDefaultKey;
if (pwalletMain->GetKeyFromPool(newDefaultKey, false)) {
pwalletMain->SetDefaultKey(newDefaultKey);
if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
strErrors << _("Cannot write default address") << "\n";
}
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
}
printf("%s", strErrors.str().c_str());
printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
RegisterWallet(pwalletMain);
CBlockIndex *pindexRescan = pindexBest;
if (GetBoolArg("-rescan"))
pindexRescan = pindexGenesisBlock;
else
{
CWalletDB walletdb("wallet.dat");
CBlockLocator locator;
if (walletdb.ReadBestBlock(locator))
pindexRescan = locator.GetBlockIndex();
else
pindexRescan = pindexGenesisBlock;
}
if (pindexBest && pindexBest != pindexRescan)
{
uiInterface.InitMessage(_("Rescanning..."));
printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
nStart = GetTimeMillis();
pwalletMain->ScanForWalletTransactions(pindexRescan, true);
printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
nWalletDBUpdated++;
}
} // (!fDisableWallet)
// ********************************************************* Step 9: import blocks
// scan for better chains in the block chain database, that are not yet connected in the active best chain
CValidationState state;
if (!ConnectBestBlock(state))
strErrors << "Failed to connect best block";
std::vector<boost::filesystem::path> vImportFiles;
if (mapArgs.count("-loadblock"))
{
BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
vImportFiles.push_back(strFile);
}
threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
// ********************************************************* Step 10: load peers
uiInterface.InitMessage(_("Loading addresses..."));
nStart = GetTimeMillis();
{
CAddrDB adb;
if (!adb.Read(addrman))
printf("Invalid or missing peers.dat; recreating\n");
}
printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n",
addrman.size(), GetTimeMillis() - nStart);
// ********************************************************* Step 11: start node
if (!CheckDiskSpace())
return false;
if (!strErrors.str().empty())
return InitError(strErrors.str());
RandAddSeedPerfmon();
//// debug print
printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
printf("nBestHeight = %d\n", nBestHeight);
printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0);
printf("mapWallet.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->mapWallet.size() : 0);
printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0);
StartNode(threadGroup);
// InitRPCMining is needed here so getwork/getblocktemplate in the GUI debug console works properly.
InitRPCMining();
if (fServer)
StartRPCThreads();
// Generate coins in the background
if (pwalletMain)
GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain);
// ********************************************************* Step 12: finished
uiInterface.InitMessage(_("Done loading"));
if (pwalletMain) {
// Add wallet transactions that aren't already in a block to mapTransactions
pwalletMain->ReacceptWalletTransactions();
// Run a thread to flush wallet periodically
threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
}
return !fRequestShutdown;
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__delete_wchar_t_malloc_53b.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete.label.xml
Template File: sources-sinks-53b.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: malloc Allocate data using malloc()
* GoodSource: Allocate data using new
* Sinks:
* GoodSink: Deallocate data using free()
* BadSink : Deallocate data using delete
* Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files
*
* */
#include "std_testcase.h"
namespace CWE762_Mismatched_Memory_Management_Routines__delete_wchar_t_malloc_53
{
#ifndef OMITBAD
/* bad function declaration */
void badSink_c(wchar_t * data);
void badSink_b(wchar_t * data)
{
badSink_c(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink_c(wchar_t * data);
void goodG2BSink_b(wchar_t * data)
{
goodG2BSink_c(data);
}
/* goodB2G uses the BadSource with the GoodSink */
void goodB2GSink_c(wchar_t * data);
void goodB2GSink_b(wchar_t * data)
{
goodB2GSink_c(data);
}
#endif /* OMITGOOD */
} /* close namespace */
|
#include "common/router/rds_impl.h"
#include "common/common/assert.h"
#include "common/json/config_schemas.h"
#include "common/router/config_impl.h"
namespace Router {
RouteConfigProviderPtr RouteConfigProviderUtil::create(
const Json::Object& config, Runtime::Loader& runtime, Upstream::ClusterManager& cm,
Event::Dispatcher& dispatcher, Runtime::RandomGenerator& random,
const LocalInfo::LocalInfo& local_info, Stats::Scope& scope, const std::string& stat_prefix,
ThreadLocal::Instance& tls, Init::Manager& init_manager) {
bool has_rds = config.hasObject("rds");
bool has_route_config = config.hasObject("route_config");
if (!(has_rds ^ has_route_config)) {
throw EnvoyException(
"http connection manager must have either rds or route_config but not both");
}
if (has_route_config) {
return RouteConfigProviderPtr{
new StaticRouteConfigProviderImpl(*config.getObject("route_config"), runtime, cm)};
} else {
Json::ObjectPtr rds_config = config.getObject("rds");
rds_config->validateSchema(Json::Schema::RDS_CONFIGURATION_SCHEMA);
std::unique_ptr<RdsRouteConfigProviderImpl> provider{new RdsRouteConfigProviderImpl(
*rds_config, runtime, cm, dispatcher, random, local_info, scope, stat_prefix, tls)};
provider->registerInitTarget(init_manager);
return std::move(provider);
}
}
StaticRouteConfigProviderImpl::StaticRouteConfigProviderImpl(const Json::Object& config,
Runtime::Loader& runtime,
Upstream::ClusterManager& cm)
: config_(new ConfigImpl(config, runtime, cm, true)) {}
RdsRouteConfigProviderImpl::RdsRouteConfigProviderImpl(
const Json::Object& config, Runtime::Loader& runtime, Upstream::ClusterManager& cm,
Event::Dispatcher& dispatcher, Runtime::RandomGenerator& random,
const LocalInfo::LocalInfo& local_info, Stats::Scope& scope, const std::string& stat_prefix,
ThreadLocal::Instance& tls)
: RestApiFetcher(cm, config.getString("cluster"), dispatcher, random,
std::chrono::milliseconds(config.getInteger("refresh_delay_ms", 30000))),
runtime_(runtime), local_info_(local_info), tls_(tls), tls_slot_(tls.allocateSlot()),
route_config_name_(config.getString("route_config_name")),
stats_({ALL_RDS_STATS(POOL_COUNTER_PREFIX(scope, stat_prefix + "rds."))}) {
if (local_info.clusterName().empty() || local_info.nodeName().empty()) {
throw EnvoyException("rds: setting --service-cluster and --service-node are required");
}
if (!cm.get(remote_cluster_name_)) {
throw EnvoyException(fmt::format("rds: unknown remote cluster '{}'", remote_cluster_name_));
}
ConfigConstSharedPtr initial_config(new NullConfigImpl());
tls_.set(tls_slot_,
[initial_config](Event::Dispatcher&) -> ThreadLocal::ThreadLocalObjectSharedPtr {
return std::make_shared<ThreadLocalConfig>(initial_config);
});
}
Router::ConfigConstSharedPtr RdsRouteConfigProviderImpl::config() {
return tls_.getTyped<ThreadLocalConfig>(tls_slot_).config_;
}
void RdsRouteConfigProviderImpl::createRequest(Http::Message& request) {
log_debug("rds: starting request");
stats_.update_attempt_.inc();
request.headers().insertMethod().value(Http::Headers::get().MethodValues.Get);
request.headers().insertPath().value(fmt::format("/v1/routes/{}/{}/{}", route_config_name_,
local_info_.clusterName(),
local_info_.nodeName()));
}
void RdsRouteConfigProviderImpl::parseResponse(const Http::Message& response) {
log_debug("rds: parsing response");
Json::ObjectPtr response_json = Json::Factory::LoadFromString(response.bodyAsString());
uint64_t new_hash = response_json->hash();
if (new_hash != last_config_hash_ || !initialized_) {
response_json->validateSchema(Json::Schema::ROUTE_CONFIGURATION_SCHEMA);
ConfigConstSharedPtr new_config(new ConfigImpl(*response_json, runtime_, cm_, false));
initialized_ = true;
last_config_hash_ = new_hash;
stats_.config_reload_.inc();
log_debug("rds: loading new configuration: config_name={} hash={}", route_config_name_,
new_hash);
tls_.runOnAllThreads([this, new_config]() -> void {
tls_.getTyped<ThreadLocalConfig>(tls_slot_).config_ = new_config;
});
}
stats_.update_success_.inc();
}
void RdsRouteConfigProviderImpl::onFetchComplete() {
if (initialize_callback_) {
initialize_callback_();
initialize_callback_ = nullptr;
}
}
void RdsRouteConfigProviderImpl::onFetchFailure(EnvoyException* e) {
stats_.update_failure_.inc();
if (e) {
log().warn("rds: fetch failure: {}", e->what());
} else {
log().info("rds: fetch failure: network error");
}
}
void RdsRouteConfigProviderImpl::registerInitTarget(Init::Manager& init_manager) {
init_manager.registerTarget(*this);
}
} // Router
|
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include <string>
#include <vector>
#include "nifty/python/converter.hxx"
#include "nifty/tools/changable_priority_queue.hxx"
namespace py = pybind11;
namespace nifty{
namespace tools{
void exportChangeablePriorityQueue(py::module & toolsModule){
typedef ChangeablePriorityQueue<double> QueueType;
typedef typename QueueType::priority_type priority_type;
typedef typename QueueType::ValueType ValueType;
typedef typename QueueType::const_reference const_reference;
const auto clsStr = std::string("ChangeablePriorityQueue");
py::class_<QueueType>(toolsModule, clsStr.c_str())
.def(py::init([](const std::size_t maxSize){
return new QueueType(maxSize);
})
)
.def("__len__",&QueueType::size)
.def("__contains__",&QueueType::contains)
.def("__delitem__",&QueueType::deleteItem)
.def("reset",&QueueType::reset)
.def("empty",&QueueType::empty)
.def("clear",&QueueType::clear)
.def("push",&QueueType::push)
.def("top",&QueueType::top)
.def("pop",&QueueType::pop)
.def("topPriority",&QueueType::topPriority)
.def("deleteItem",&QueueType::deleteItem)
.def("changePriority",&QueueType::changePriority)
;
}
}
}
|
/* Copyright (C) 2015 Ion Torrent Systems, Inc. All Rights Reserved. */
#include "benchmark.h"
#include <stdexcept>
#include <ctime>
// #define CALIBR_DBG
#ifdef CALIBR_DBG
#include <iostream>
#endif
const unsigned USECS_IN_SEC = 1000000;
const unsigned NSECS_IN_USEC = 1000;
const unsigned NSEQS_IN_SEC = NSECS_IN_USEC * USECS_IN_SEC;
static const char* clockerr = "System clock access error";
// returns time difference in micro-seconds
static long long clock_diff (timespec& t1, timespec& t2)
{
long long nsdiff = ((long long) (t1.tv_sec - t2.tv_sec)) * NSEQS_IN_SEC;
nsdiff += t1.tv_nsec;
nsdiff -= t2.tv_nsec;
return nsdiff / NSECS_IN_USEC;
}
Benchmark::Benchmark (const char* name)
:
name_ (name),
facets_ (name)
{
}
Benchmark::Benchmark (const char* name, TestFacet& facet)
:
name_ (name),
facets_ (name)
{
add_facet (&facet, true);
}
Benchmark::~Benchmark ()
{
for (TestFacetSet::FVIter itr = facets_.begin (), sent = facets_.end (); itr != sent; ++ itr)
{
if (external_facets_.count (*itr))
*itr = NULL;
}
}
bool Benchmark::dummy_iter ()
{
return true;
}
long long Benchmark::timing (unsigned repetitions, bool (Benchmark::*proc)())
{
timespec clock_before, clock_after;
long long elapsed;
// measure the loaded time
if (clock_gettime (CLOCK_MONOTONIC, &clock_before) != 0)
throw std::runtime_error (clockerr);
for (unsigned itr = 0; itr != repetitions; ++itr)
if (!(this->*proc) ())
return -1;
if (clock_gettime (CLOCK_MONOTONIC, &clock_after) != 0)
throw std::runtime_error (clockerr);
elapsed = clock_diff (clock_after, clock_before);
return std::max (elapsed, (long long) 0);
}
unsigned Benchmark::calibrate (bool (Benchmark::*proc) (), unsigned long long duration) // returns 0 on error, number of repetitions running in 'duration' ms on success
{
unsigned long long repetitions = 1, iter;
long long elapsed;
timespec clock0, clock1;
for (;;)
{
if (clock_gettime (CLOCK_MONOTONIC, &clock0) != 0)
throw std::runtime_error (clockerr);
for (iter = 0; iter != repetitions; ++iter)
if (!(this->*proc) ())
return 0;
if (clock_gettime (CLOCK_MONOTONIC, &clock1) != 0)
throw std::runtime_error (clockerr);
elapsed = clock_diff (clock1, clock0);
#ifdef CALIBR_DBG
std::cerr << "\r Calibrated for " << repetitions << " in " << elapsed << " usec" << std::endl;
#endif
if (elapsed <= 0)
repetitions *= duration;
else if ((unsigned) elapsed * 2 <= duration) // duration/elapsed >= 2, so that multiplication makes sense
{
repetitions *= duration;
repetitions /= elapsed;
}
else if ((unsigned) elapsed < duration)
{
repetitions += repetitions - elapsed * repetitions / duration;
}
else if (repetitions > 2 && (unsigned) elapsed >= duration * 2)
{
repetitions *= duration;
repetitions /= elapsed;
}
else
break;
}
#ifdef CALIBR_DBG
o_ << "Calibration result is " << repetitions << " in " << elapsed << " usec (requested duration " << duration << " usec)" << std::endl;
#endif
return (unsigned) repetitions;
}
double Benchmark::run (unsigned long long duration)
{
// determine how many times to run a test
unsigned repetitions = calibrate (&Benchmark::loaded_iter, duration);
if (repetitions == 0)
return 0;
// measure the loaded time
long long elapsed_loaded = timing (repetitions, &Benchmark::loaded_iter);
if (elapsed_loaded < 0)
return 0;
// measure the dummy time
long long elapsed_dummy = timing (repetitions, &Benchmark::dummy_iter);
if (elapsed_dummy < 0)
return 0;
// subtract dummy from loaded time
long long elapsed;
if (elapsed_dummy != 0 && elapsed_dummy < elapsed_loaded)
elapsed = elapsed_loaded - elapsed_dummy;
else
elapsed = elapsed_loaded;
// elapsed is in microsecs, scale the speed
return ((double) repetitions) * USECS_IN_SEC / elapsed;
}
void Benchmark::add_facet (TestFacet* facet, bool external)
{
facets_.add (facet);
if (external)
external_facets_.insert (facet);
}
|
#include "PhysicsServerCommandProcessor.h"
#include "../CommonInterfaces/CommonRenderInterface.h"
#include "plugins/b3PluginCollisionInterface.h"
#include "../Importers/ImportURDFDemo/BulletUrdfImporter.h"
#include "../Importers/ImportURDFDemo/MyMultiBodyCreator.h"
#include "../Importers/ImportURDFDemo/URDF2Bullet.h"
#include "../Importers/ImportURDFDemo/UrdfFindMeshFile.h"
#include "../Extras/InverseDynamics/btMultiBodyTreeCreator.hpp"
#include "BulletCollision/CollisionDispatch/btInternalEdgeUtility.h"
#include "../Importers/ImportMeshUtility/b3ImportMeshUtility.h"
#include "BulletDynamics/MLCPSolvers/btDantzigSolver.h"
#include "BulletDynamics/MLCPSolvers/btSolveProjectedGaussSeidel.h"
#include "BulletDynamics/Featherstone/btMultiBodyMLCPConstraintSolver.h"
#include "BulletDynamics/Featherstone/btMultiBodySphericalJointMotor.h"
#include "../Utils/b3BulletDefaultFileIO.h"
#include "BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h"
#include "BulletDynamics/Featherstone/btMultiBodyConstraintSolver.h"
#include "BulletDynamics/Featherstone/btMultiBodyPoint2Point.h"
#include "BulletDynamics/Featherstone/btMultiBodyLinkCollider.h"
#include "BulletDynamics/Featherstone/btMultiBodyJointFeedback.h"
#include "BulletDynamics/Featherstone/btMultiBodyFixedConstraint.h"
#include "BulletDynamics/Featherstone/btMultiBodyGearConstraint.h"
#include "../Importers/ImportURDFDemo/UrdfParser.h"
#include "../Utils/b3ResourcePath.h"
#include "Bullet3Common/b3FileUtils.h"
#include "../OpenGLWindow/GLInstanceGraphicsShape.h"
#include "BulletDynamics/Featherstone/btMultiBodySliderConstraint.h"
#include "BulletDynamics/Featherstone/btMultiBodyPoint2Point.h"
#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h"
#include "Bullet3Common/b3HashMap.h"
#include "../Utils/ChromeTraceUtil.h"
#include "SharedMemoryPublic.h"
#include "stb_image/stb_image.h"
#include "BulletInverseDynamics/MultiBodyTree.hpp"
#include "IKTrajectoryHelper.h"
#include "btBulletDynamicsCommon.h"
#include "../Utils/RobotLoggingUtil.h"
#include "LinearMath/btTransform.h"
#include "../Importers/ImportMJCFDemo/BulletMJCFImporter.h"
#include "../Importers/ImportObjDemo/LoadMeshFromObj.h"
#include "../Importers/ImportSTLDemo/LoadMeshFromSTL.h"
#include "../Extras/Serialize/BulletWorldImporter/btMultiBodyWorldImporter.h"
#include "BulletDynamics/Featherstone/btMultiBodyJointMotor.h"
#include "LinearMath/btSerializer.h"
#include "Bullet3Common/b3Logging.h"
#include "../CommonInterfaces/CommonGUIHelperInterface.h"
#include "SharedMemoryCommands.h"
#include "LinearMath/btRandom.h"
#include "Bullet3Common/b3ResizablePool.h"
#include "../Utils/b3Clock.h"
#include "b3PluginManager.h"
#include "../Extras/Serialize/BulletFileLoader/btBulletFile.h"
#include "BulletCollision/NarrowPhaseCollision/btRaycastCallback.h"
#include "LinearMath/TaskScheduler/btThreadSupportInterface.h"
#include "Wavefront/tiny_obj_loader.h"
#ifndef SKIP_COLLISION_FILTER_PLUGIN
#include "plugins/collisionFilterPlugin/collisionFilterPlugin.h"
#endif
#ifdef ENABLE_STATIC_GRPC_PLUGIN
#include "plugins/grpcPlugin/grpcPlugin.h"
#endif //ENABLE_STATIC_GRPC_PLUGIN
#ifndef SKIP_STATIC_PD_CONTROL_PLUGIN
#include "plugins/pdControlPlugin/pdControlPlugin.h"
#endif //SKIP_STATIC_PD_CONTROL_PLUGIN
#ifdef STATIC_LINK_SPD_PLUGIN
#include "plugins/stablePDPlugin/BulletConversion.h"
#include "plugins/stablePDPlugin/RBDModel.h"
#include "plugins/stablePDPlugin/RBDUtil.h"
#endif
#ifdef STATIC_LINK_VR_PLUGIN
#include "plugins/vrSyncPlugin/vrSyncPlugin.h"
#endif
#ifdef STATIC_EGLRENDERER_PLUGIN
#include "plugins/eglPlugin/eglRendererPlugin.h"
#endif //STATIC_EGLRENDERER_PLUGIN
#ifndef SKIP_STATIC_TINYRENDERER_PLUGIN
#include "plugins/tinyRendererPlugin/tinyRendererPlugin.h"
#endif
#ifdef B3_ENABLE_FILEIO_PLUGIN
#include "plugins/fileIOPlugin/fileIOPlugin.h"
#endif //B3_DISABLE_FILEIO_PLUGIN
#ifdef B3_ENABLE_TINY_AUDIO
#include "../TinyAudio/b3SoundEngine.h"
#endif
#ifdef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
#define SKIP_DEFORMABLE_BODY 1
#endif
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
#include "BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.h"
#include "BulletSoftBody/btSoftBodySolvers.h"
#include "BulletSoftBody/btSoftBodyHelpers.h"
#include "BulletSoftBody/btSoftMultiBodyDynamicsWorld.h"
#include "BulletSoftBody/btDeformableMultiBodyDynamicsWorld.h"
#include "BulletSoftBody/btDeformableBodySolver.h"
#include "BulletSoftBody/btDeformableMultiBodyConstraintSolver.h"
#include "../SoftDemo/BunnyMesh.h"
#endif//SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
#ifndef SKIP_DEFORMABLE_BODY
#include "BulletSoftBody/btDeformableMultiBodyDynamicsWorld.h"
#include "BulletSoftBody/btDeformableBodySolver.h"
#include "BulletSoftBody/btDeformableMultiBodyConstraintSolver.h"
#endif//SKIP_DEFORMABLE_BODY
#include "BulletDynamics/Featherstone/btMultiBodyDynamicsWorld.h"
int gInternalSimFlags = 0;
bool gResetSimulation = 0;
int gVRTrackingObjectUniqueId = -1;
int gVRTrackingObjectFlag = VR_CAMERA_TRACK_OBJECT_ORIENTATION;
btTransform gVRTrackingObjectTr = btTransform::getIdentity();
btVector3 gVRTeleportPos1(0, 0, 0);
btQuaternion gVRTeleportOrn(0, 0, 0, 1);
btScalar simTimeScalingFactor = 1;
btScalar gRhsClamp = 1.f;
#include "../CommonInterfaces/CommonFileIOInterface.h"
class b3ThreadPool
{
public:
b3ThreadPool(const char* name = "b3ThreadPool")
{
btThreadSupportInterface::ConstructionInfo info(name, threadFunction);
m_threadSupportInterface = btThreadSupportInterface::create(info);
}
~b3ThreadPool()
{
delete m_threadSupportInterface;
}
const int numWorkers() const { return m_threadSupportInterface->getNumWorkerThreads(); }
void runTask(int threadIdx, btThreadSupportInterface::ThreadFunc func, void* arg)
{
FunctionContext& ctx = m_functionContexts[threadIdx];
ctx.func = func;
ctx.arg = arg;
m_threadSupportInterface->runTask(threadIdx, (void*)&ctx);
}
void waitForAllTasks()
{
BT_PROFILE("b3ThreadPool_waitForAllTasks");
m_threadSupportInterface->waitForAllTasks();
}
private:
struct FunctionContext
{
btThreadSupportInterface::ThreadFunc func;
void* arg;
};
static void threadFunction(void* userPtr)
{
BT_PROFILE("b3ThreadPool_threadFunction");
FunctionContext* ctx = (FunctionContext*)userPtr;
ctx->func(ctx->arg);
}
btThreadSupportInterface* m_threadSupportInterface;
FunctionContext m_functionContexts[BT_MAX_THREAD_COUNT];
};
struct SharedMemoryDebugDrawer : public btIDebugDraw
{
int m_debugMode;
btAlignedObjectArray<SharedMemLines> m_lines2;
SharedMemoryDebugDrawer()
: m_debugMode(0)
{
}
virtual void drawContactPoint(const btVector3& PointOnB, const btVector3& normalOnB, btScalar distance, int lifeTime, const btVector3& color)
{
}
virtual void reportErrorWarning(const char* warningString)
{
}
virtual void draw3dText(const btVector3& location, const char* textString)
{
}
virtual void setDebugMode(int debugMode)
{
m_debugMode = debugMode;
}
virtual int getDebugMode() const
{
return m_debugMode;
}
virtual void drawLine(const btVector3& from, const btVector3& to, const btVector3& color)
{
SharedMemLines line;
line.m_from = from;
line.m_to = to;
line.m_color = color;
m_lines2.push_back(line);
}
};
struct InternalVisualShapeData
{
int m_tinyRendererVisualShapeIndex;
int m_OpenGLGraphicsIndex;
b3AlignedObjectArray<UrdfVisual> m_visualShapes;
b3AlignedObjectArray<std::string> m_pathPrefixes;
void clear()
{
m_tinyRendererVisualShapeIndex = -1;
m_OpenGLGraphicsIndex = -1;
m_visualShapes.clear();
m_pathPrefixes.clear();
}
};
struct InternalCollisionShapeData
{
btCollisionShape* m_collisionShape;
b3AlignedObjectArray<UrdfCollision> m_urdfCollisionObjects;
int m_used;
InternalCollisionShapeData()
: m_collisionShape(0),
m_used(0)
{
}
void clear()
{
m_collisionShape = 0;
m_used = 0;
}
};
#include "SharedMemoryUserData.h"
struct InternalBodyData
{
btMultiBody* m_multiBody;
btRigidBody* m_rigidBody;
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
btSoftBody* m_softBody;
#endif
int m_testData;
std::string m_bodyName;
btTransform m_rootLocalInertialFrame;
btAlignedObjectArray<btTransform> m_linkLocalInertialFrames;
btAlignedObjectArray<btGeneric6DofSpring2Constraint*> m_rigidBodyJoints;
btAlignedObjectArray<std::string> m_rigidBodyJointNames;
btAlignedObjectArray<std::string> m_rigidBodyLinkNames;
btAlignedObjectArray<int> m_userDataHandles;
#ifdef B3_ENABLE_TINY_AUDIO
b3HashMap<btHashInt, SDFAudioSource> m_audioSources;
#endif //B3_ENABLE_TINY_AUDIO
InternalBodyData()
{
clear();
}
void clear()
{
m_multiBody = 0;
m_rigidBody = 0;
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
m_softBody = 0;
#endif
m_testData = 0;
m_bodyName = "";
m_rootLocalInertialFrame.setIdentity();
m_linkLocalInertialFrames.clear();
m_rigidBodyJoints.clear();
m_rigidBodyJointNames.clear();
m_rigidBodyLinkNames.clear();
m_userDataHandles.clear();
}
};
struct InteralUserConstraintData
{
btTypedConstraint* m_rbConstraint;
btMultiBodyConstraint* m_mbConstraint;
b3UserConstraint m_userConstraintData;
InteralUserConstraintData()
: m_rbConstraint(0),
m_mbConstraint(0)
{
}
};
struct InternalTextureData
{
int m_tinyRendererTextureId;
int m_openglTextureId;
void clear()
{
m_tinyRendererTextureId = -1;
m_openglTextureId = -1;
}
};
typedef b3PoolBodyHandle<InternalTextureData> InternalTextureHandle;
typedef b3PoolBodyHandle<InternalBodyData> InternalBodyHandle;
typedef b3PoolBodyHandle<InternalCollisionShapeData> InternalCollisionShapeHandle;
typedef b3PoolBodyHandle<InternalVisualShapeData> InternalVisualShapeHandle;
class btCommandChunk
{
public:
int m_chunkCode;
int m_length;
void* m_oldPtr;
int m_dna_nr;
int m_number;
};
class bCommandChunkPtr4
{
public:
bCommandChunkPtr4() {}
int code;
int len;
union {
int m_uniqueInt;
};
int dna_nr;
int nr;
};
// ----------------------------------------------------- //
class bCommandChunkPtr8
{
public:
bCommandChunkPtr8() {}
int code, len;
union {
int m_uniqueInts[2];
};
int dna_nr, nr;
};
struct CommandLogger
{
FILE* m_file;
void writeHeader(unsigned char* buffer) const
{
#ifdef BT_USE_DOUBLE_PRECISION
memcpy(buffer, "BT3CMDd", 7);
#else
memcpy(buffer, "BT3CMDf", 7);
#endif //BT_USE_DOUBLE_PRECISION
int littleEndian = 1;
littleEndian = ((char*)&littleEndian)[0];
if (sizeof(void*) == 8)
{
buffer[7] = '-';
}
else
{
buffer[7] = '_';
}
if (littleEndian)
{
buffer[8] = 'v';
}
else
{
buffer[8] = 'V';
}
buffer[9] = 0;
buffer[10] = 0;
buffer[11] = 0;
int ver = btGetVersion();
if (ver >= 0 && ver < 999)
{
sprintf((char*)&buffer[9], "%d", ver);
}
}
void logCommand(const SharedMemoryCommand& command)
{
if (m_file)
{
btCommandChunk chunk;
chunk.m_chunkCode = command.m_type;
chunk.m_oldPtr = 0;
chunk.m_dna_nr = 0;
chunk.m_length = sizeof(SharedMemoryCommand);
chunk.m_number = 1;
fwrite((const char*)&chunk, sizeof(btCommandChunk), 1, m_file);
switch (command.m_type)
{
case CMD_LOAD_MJCF:
{
fwrite((const char*)&command.m_updateFlags, sizeof(int), 1, m_file);
fwrite((const char*)&command.m_mjcfArguments, sizeof(MjcfArgs), 1, m_file);
break;
}
case CMD_REQUEST_BODY_INFO:
{
fwrite((const char*)&command.m_updateFlags, sizeof(int), 1, m_file);
fwrite((const char*)&command.m_sdfRequestInfoArgs, sizeof(SdfRequestInfoArgs), 1, m_file);
break;
}
case CMD_REQUEST_VISUAL_SHAPE_INFO:
{
fwrite((const char*)&command.m_updateFlags, sizeof(int), 1, m_file);
fwrite((const char*)&command.m_requestVisualShapeDataArguments, sizeof(RequestVisualShapeDataArgs), 1, m_file);
break;
}
case CMD_LOAD_URDF:
{
fwrite((const char*)&command.m_updateFlags, sizeof(int), 1, m_file);
fwrite((const char*)&command.m_urdfArguments, sizeof(UrdfArgs), 1, m_file);
break;
}
case CMD_INIT_POSE:
{
fwrite((const char*)&command.m_updateFlags, sizeof(int), 1, m_file);
fwrite((const char*)&command.m_initPoseArgs, sizeof(InitPoseArgs), 1, m_file);
break;
};
case CMD_REQUEST_ACTUAL_STATE:
{
fwrite((const char*)&command.m_updateFlags, sizeof(int), 1, m_file);
fwrite((const char*)&command.m_requestActualStateInformationCommandArgument,
sizeof(RequestActualStateArgs), 1, m_file);
break;
};
case CMD_SEND_DESIRED_STATE:
{
fwrite((const char*)&command.m_updateFlags, sizeof(int), 1, m_file);
fwrite((const char*)&command.m_sendDesiredStateCommandArgument, sizeof(SendDesiredStateArgs), 1, m_file);
break;
}
case CMD_SEND_PHYSICS_SIMULATION_PARAMETERS:
{
fwrite((const char*)&command.m_updateFlags, sizeof(int), 1, m_file);
fwrite((const char*)&command.m_physSimParamArgs, sizeof(b3PhysicsSimulationParameters), 1, m_file);
break;
}
case CMD_REQUEST_CONTACT_POINT_INFORMATION:
{
fwrite((const char*)&command.m_updateFlags, sizeof(int), 1, m_file);
fwrite((const char*)&command.m_requestContactPointArguments, sizeof(RequestContactDataArgs), 1, m_file);
break;
}
case CMD_STEP_FORWARD_SIMULATION:
case CMD_RESET_SIMULATION:
case CMD_REQUEST_INTERNAL_DATA:
{
break;
};
default:
{
fwrite((const char*)&command, sizeof(SharedMemoryCommand), 1, m_file);
}
};
}
}
CommandLogger(const char* fileName)
{
m_file = fopen(fileName, "wb");
if (m_file)
{
unsigned char buf[15];
buf[12] = 12;
buf[13] = 13;
buf[14] = 14;
writeHeader(buf);
fwrite(buf, 12, 1, m_file);
}
}
virtual ~CommandLogger()
{
if (m_file)
{
fclose(m_file);
}
}
};
struct CommandLogPlayback
{
unsigned char m_header[12];
FILE* m_file;
bool m_bitsVary;
bool m_fileIs64bit;
CommandLogPlayback(const char* fileName)
{
m_file = fopen(fileName, "rb");
if (m_file)
{
size_t bytesRead;
bytesRead = fread(m_header, 12, 1, m_file);
}
unsigned char c = m_header[7];
m_fileIs64bit = (c == '-');
const bool VOID_IS_8 = ((sizeof(void*) == 8));
m_bitsVary = (VOID_IS_8 != m_fileIs64bit);
}
virtual ~CommandLogPlayback()
{
if (m_file)
{
fclose(m_file);
m_file = 0;
}
}
bool processNextCommand(SharedMemoryCommand* cmd)
{
//for a little while, keep this flag to be able to read 'old' log files
//#define BACKWARD_COMPAT
#if BACKWARD_COMPAT
SharedMemoryCommand unused;
#endif //BACKWARD_COMPAT
bool result = false;
size_t s = 0;
if (m_file)
{
int commandType = -1;
if (m_fileIs64bit)
{
bCommandChunkPtr8 chunk8;
s = fread((void*)&chunk8, sizeof(bCommandChunkPtr8), 1, m_file);
commandType = chunk8.code;
}
else
{
bCommandChunkPtr4 chunk4;
s = fread((void*)&chunk4, sizeof(bCommandChunkPtr4), 1, m_file);
commandType = chunk4.code;
}
if (s == 1)
{
memset(cmd, 0, sizeof(SharedMemoryCommand));
cmd->m_type = commandType;
#ifdef BACKWARD_COMPAT
s = fread(&unused, sizeof(SharedMemoryCommand), 1, m_file);
cmd->m_updateFlags = unused.m_updateFlags;
#endif
switch (commandType)
{
case CMD_LOAD_MJCF:
{
#ifdef BACKWARD_COMPAT
cmd->m_mjcfArguments = unused.m_mjcfArguments;
#else
s = fread(&cmd->m_updateFlags, sizeof(int), 1, m_file);
s = fread(&cmd->m_mjcfArguments, sizeof(MjcfArgs), 1, m_file);
#endif
result = true;
break;
}
case CMD_REQUEST_BODY_INFO:
{
#ifdef BACKWARD_COMPAT
cmd->m_sdfRequestInfoArgs = unused.m_sdfRequestInfoArgs;
#else
s = fread(&cmd->m_updateFlags, sizeof(int), 1, m_file);
s = fread(&cmd->m_sdfRequestInfoArgs, sizeof(SdfRequestInfoArgs), 1, m_file);
#endif
result = true;
break;
}
case CMD_REQUEST_VISUAL_SHAPE_INFO:
{
#ifdef BACKWARD_COMPAT
cmd->m_requestVisualShapeDataArguments = unused.m_requestVisualShapeDataArguments;
#else
s = fread(&cmd->m_updateFlags, sizeof(int), 1, m_file);
s = fread(&cmd->m_requestVisualShapeDataArguments, sizeof(RequestVisualShapeDataArgs), 1, m_file);
#endif
result = true;
break;
}
case CMD_LOAD_URDF:
{
#ifdef BACKWARD_COMPAT
cmd->m_urdfArguments = unused.m_urdfArguments;
#else
s = fread(&cmd->m_updateFlags, sizeof(int), 1, m_file);
s = fread(&cmd->m_urdfArguments, sizeof(UrdfArgs), 1, m_file);
#endif
result = true;
break;
}
case CMD_INIT_POSE:
{
#ifdef BACKWARD_COMPAT
cmd->m_initPoseArgs = unused.m_initPoseArgs;
#else
s = fread(&cmd->m_updateFlags, sizeof(int), 1, m_file);
s = fread(&cmd->m_initPoseArgs, sizeof(InitPoseArgs), 1, m_file);
#endif
result = true;
break;
};
case CMD_REQUEST_ACTUAL_STATE:
{
#ifdef BACKWARD_COMPAT
cmd->m_requestActualStateInformationCommandArgument = unused.m_requestActualStateInformationCommandArgument;
#else
s = fread(&cmd->m_updateFlags, sizeof(int), 1, m_file);
s = fread(&cmd->m_requestActualStateInformationCommandArgument, sizeof(RequestActualStateArgs), 1, m_file);
#endif
result = true;
break;
};
case CMD_SEND_DESIRED_STATE:
{
#ifdef BACKWARD_COMPAT
cmd->m_sendDesiredStateCommandArgument = unused.m_sendDesiredStateCommandArgument;
#else
s = fread(&cmd->m_updateFlags, sizeof(int), 1, m_file);
s = fread(&cmd->m_sendDesiredStateCommandArgument, sizeof(SendDesiredStateArgs), 1, m_file);
#endif
result = true;
break;
}
case CMD_SEND_PHYSICS_SIMULATION_PARAMETERS:
{
#ifdef BACKWARD_COMPAT
cmd->m_physSimParamArgs = unused.m_physSimParamArgs;
#else
s = fread(&cmd->m_updateFlags, sizeof(int), 1, m_file);
s = fread(&cmd->m_physSimParamArgs, sizeof(b3PhysicsSimulationParameters), 1, m_file);
#endif
result = true;
break;
}
case CMD_REQUEST_CONTACT_POINT_INFORMATION:
{
#ifdef BACKWARD_COMPAT
cmd->m_requestContactPointArguments = unused.m_requestContactPointArguments;
#else
s = fread(&cmd->m_updateFlags, sizeof(int), 1, m_file);
s = fread(&cmd->m_requestContactPointArguments, sizeof(RequestContactDataArgs), 1, m_file);
#endif
result = true;
break;
}
case CMD_STEP_FORWARD_SIMULATION:
case CMD_RESET_SIMULATION:
case CMD_REQUEST_INTERNAL_DATA:
{
result = true;
break;
}
default:
{
s = fread(cmd, sizeof(SharedMemoryCommand), 1, m_file);
result = (s == 1);
}
};
}
}
return result;
}
};
struct SaveWorldObjectData
{
b3AlignedObjectArray<int> m_bodyUniqueIds;
std::string m_fileName;
};
struct MyBroadphaseCallback : public btBroadphaseAabbCallback
{
b3AlignedObjectArray<int> m_bodyUniqueIds;
b3AlignedObjectArray<int> m_links;
MyBroadphaseCallback()
{
}
virtual ~MyBroadphaseCallback()
{
}
void clear()
{
m_bodyUniqueIds.clear();
m_links.clear();
}
virtual bool process(const btBroadphaseProxy* proxy)
{
btCollisionObject* colObj = (btCollisionObject*)proxy->m_clientObject;
btMultiBodyLinkCollider* mbl = btMultiBodyLinkCollider::upcast(colObj);
if (mbl)
{
int bodyUniqueId = mbl->m_multiBody->getUserIndex2();
m_bodyUniqueIds.push_back(bodyUniqueId);
m_links.push_back(mbl->m_link);
return true;
}
int bodyUniqueId = colObj->getUserIndex2();
if (bodyUniqueId >= 0)
{
m_bodyUniqueIds.push_back(bodyUniqueId);
//it is not a multibody, so use -1 otherwise
m_links.push_back(-1);
}
return true;
}
};
struct MyOverlapFilterCallback : public btOverlapFilterCallback
{
int m_filterMode;
b3PluginManager* m_pluginManager;
MyOverlapFilterCallback(b3PluginManager* pluginManager)
: m_filterMode(B3_FILTER_GROUPAMASKB_AND_GROUPBMASKA),
m_pluginManager(pluginManager)
{
}
virtual ~MyOverlapFilterCallback()
{
}
// return true when pairs need collision
virtual bool needBroadphaseCollision(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1) const
{
b3PluginCollisionInterface* collisionInterface = m_pluginManager->getCollisionInterface();
if (collisionInterface && collisionInterface->getNumRules())
{
int objectUniqueIdB = -1, linkIndexB = -1;
btCollisionObject* colObjB = (btCollisionObject*)proxy1->m_clientObject;
btMultiBodyLinkCollider* mblB = btMultiBodyLinkCollider::upcast(colObjB);
if (mblB)
{
objectUniqueIdB = mblB->m_multiBody->getUserIndex2();
linkIndexB = mblB->m_link;
}
else
{
objectUniqueIdB = colObjB->getUserIndex2();
linkIndexB = -1;
}
int objectUniqueIdA = -1, linkIndexA = -1;
btCollisionObject* colObjA = (btCollisionObject*)proxy0->m_clientObject;
btMultiBodyLinkCollider* mblA = btMultiBodyLinkCollider::upcast(colObjA);
if (mblA)
{
objectUniqueIdA = mblA->m_multiBody->getUserIndex2();
linkIndexA = mblA->m_link;
}
else
{
objectUniqueIdA = colObjA->getUserIndex2();
linkIndexA = -1;
}
int collisionFilterGroupA = proxy0->m_collisionFilterGroup;
int collisionFilterMaskA = proxy0->m_collisionFilterMask;
int collisionFilterGroupB = proxy1->m_collisionFilterGroup;
int collisionFilterMaskB = proxy1->m_collisionFilterMask;
return collisionInterface->needsBroadphaseCollision(objectUniqueIdA, linkIndexA,
collisionFilterGroupA, collisionFilterMaskA,
objectUniqueIdB, linkIndexB, collisionFilterGroupB, collisionFilterMaskB, m_filterMode);
}
else
{
if (m_filterMode == B3_FILTER_GROUPAMASKB_AND_GROUPBMASKA)
{
bool collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0;
collides = collides && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask);
return collides;
}
if (m_filterMode == B3_FILTER_GROUPAMASKB_OR_GROUPBMASKA)
{
bool collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0;
collides = collides || (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask);
return collides;
}
return false;
}
}
};
struct InternalStateLogger
{
int m_loggingUniqueId;
int m_loggingType;
InternalStateLogger()
: m_loggingUniqueId(0),
m_loggingType(0)
{
}
virtual ~InternalStateLogger() {}
virtual void stop() = 0;
virtual void logState(btScalar timeStep) = 0;
};
struct VideoMP4Loggger : public InternalStateLogger
{
struct GUIHelperInterface* m_guiHelper;
std::string m_fileName;
VideoMP4Loggger(int loggerUid, const char* fileName, GUIHelperInterface* guiHelper)
: m_guiHelper(guiHelper)
{
m_fileName = fileName;
m_loggingUniqueId = loggerUid;
m_loggingType = STATE_LOGGING_VIDEO_MP4;
m_guiHelper->dumpFramesToVideo(fileName);
}
virtual void stop()
{
m_guiHelper->dumpFramesToVideo(0);
}
virtual void logState(btScalar timeStep)
{
//dumping video frames happens in another thread
//we could add some overlay of timestamp here, if needed/wanted
}
};
struct MinitaurStateLogger : public InternalStateLogger
{
int m_loggingTimeStamp;
std::string m_fileName;
int m_minitaurBodyUniqueId;
FILE* m_logFileHandle;
std::string m_structTypes;
btMultiBody* m_minitaurMultiBody;
btAlignedObjectArray<int> m_motorIdList;
MinitaurStateLogger(int loggingUniqueId, const std::string& fileName, btMultiBody* minitaurMultiBody, btAlignedObjectArray<int>& motorIdList)
: m_loggingTimeStamp(0),
m_logFileHandle(0),
m_minitaurMultiBody(minitaurMultiBody)
{
m_loggingUniqueId = loggingUniqueId;
m_loggingType = STATE_LOGGING_MINITAUR;
m_motorIdList.resize(motorIdList.size());
for (int m = 0; m < motorIdList.size(); m++)
{
m_motorIdList[m] = motorIdList[m];
}
btAlignedObjectArray<std::string> structNames;
//'t', 'r', 'p', 'y', 'q0', 'q1', 'q2', 'q3', 'q4', 'q5', 'q6', 'q7', 'u0', 'u1', 'u2', 'u3', 'u4', 'u5', 'u6', 'u7', 'xd', 'mo'
structNames.push_back("t");
structNames.push_back("r");
structNames.push_back("p");
structNames.push_back("y");
structNames.push_back("q0");
structNames.push_back("q1");
structNames.push_back("q2");
structNames.push_back("q3");
structNames.push_back("q4");
structNames.push_back("q5");
structNames.push_back("q6");
structNames.push_back("q7");
structNames.push_back("u0");
structNames.push_back("u1");
structNames.push_back("u2");
structNames.push_back("u3");
structNames.push_back("u4");
structNames.push_back("u5");
structNames.push_back("u6");
structNames.push_back("u7");
structNames.push_back("dx");
structNames.push_back("mo");
m_structTypes = "IffffffffffffffffffffB";
const char* fileNameC = fileName.c_str();
m_logFileHandle = createMinitaurLogFile(fileNameC, structNames, m_structTypes);
}
virtual void stop()
{
if (m_logFileHandle)
{
closeMinitaurLogFile(m_logFileHandle);
m_logFileHandle = 0;
}
}
virtual void logState(btScalar timeStep)
{
if (m_logFileHandle)
{
//btVector3 pos = m_minitaurMultiBody->getBasePos();
MinitaurLogRecord logData;
//'t', 'r', 'p', 'y', 'q0', 'q1', 'q2', 'q3', 'q4', 'q5', 'q6', 'q7', 'u0', 'u1', 'u2', 'u3', 'u4', 'u5', 'u6', 'u7', 'xd', 'mo'
btScalar motorDir[8] = {1, 1, 1, 1, 1, 1, 1, 1};
btQuaternion orn = m_minitaurMultiBody->getBaseWorldTransform().getRotation();
btMatrix3x3 mat(orn);
btScalar roll = 0;
btScalar pitch = 0;
btScalar yaw = 0;
mat.getEulerZYX(yaw, pitch, roll);
logData.m_values.push_back(m_loggingTimeStamp);
logData.m_values.push_back((float)roll);
logData.m_values.push_back((float)pitch);
logData.m_values.push_back((float)yaw);
for (int i = 0; i < 8; i++)
{
float jointAngle = (float)motorDir[i] * m_minitaurMultiBody->getJointPos(m_motorIdList[i]);
logData.m_values.push_back(jointAngle);
}
for (int i = 0; i < 8; i++)
{
btMultiBodyJointMotor* motor = (btMultiBodyJointMotor*)m_minitaurMultiBody->getLink(m_motorIdList[i]).m_userPtr;
if (motor && timeStep > btScalar(0))
{
btScalar force = motor->getAppliedImpulse(0) / timeStep;
logData.m_values.push_back((float)force);
}
}
//x is forward component, estimated speed forward
float xd_speed = m_minitaurMultiBody->getBaseVel()[0];
logData.m_values.push_back(xd_speed);
char mode = 6;
logData.m_values.push_back(mode);
//at the moment, appendMinitaurLogData will directly write to disk (potential delay)
//better to fill a huge memory buffer and once in a while write it to disk
appendMinitaurLogData(m_logFileHandle, m_structTypes, logData);
fflush(m_logFileHandle);
m_loggingTimeStamp++;
}
}
};
struct b3VRControllerEvents
{
b3VRControllerEvent m_vrEvents[MAX_VR_CONTROLLERS];
b3VRControllerEvents()
{
init();
}
virtual ~b3VRControllerEvents()
{
}
void init()
{
for (int i = 0; i < MAX_VR_CONTROLLERS; i++)
{
m_vrEvents[i].m_deviceType = 0;
m_vrEvents[i].m_numButtonEvents = 0;
m_vrEvents[i].m_numMoveEvents = 0;
for (int b = 0; b < MAX_VR_BUTTONS; b++)
{
m_vrEvents[i].m_buttons[b] = 0;
}
}
}
void addNewVREvents(const struct b3VRControllerEvent* vrEvents, int numVREvents)
{
//update m_vrEvents
for (int i = 0; i < numVREvents; i++)
{
int controlledId = vrEvents[i].m_controllerId;
if (vrEvents[i].m_numMoveEvents)
{
m_vrEvents[controlledId].m_analogAxis = vrEvents[i].m_analogAxis;
for (int a = 0; a < 10; a++)
{
m_vrEvents[controlledId].m_auxAnalogAxis[a] = vrEvents[i].m_auxAnalogAxis[a];
}
}
else
{
m_vrEvents[controlledId].m_analogAxis = 0;
for (int a = 0; a < 10; a++)
{
m_vrEvents[controlledId].m_auxAnalogAxis[a] = 0;
}
}
if (vrEvents[i].m_numMoveEvents + vrEvents[i].m_numButtonEvents)
{
m_vrEvents[controlledId].m_controllerId = vrEvents[i].m_controllerId;
m_vrEvents[controlledId].m_deviceType = vrEvents[i].m_deviceType;
m_vrEvents[controlledId].m_pos[0] = vrEvents[i].m_pos[0];
m_vrEvents[controlledId].m_pos[1] = vrEvents[i].m_pos[1];
m_vrEvents[controlledId].m_pos[2] = vrEvents[i].m_pos[2];
m_vrEvents[controlledId].m_orn[0] = vrEvents[i].m_orn[0];
m_vrEvents[controlledId].m_orn[1] = vrEvents[i].m_orn[1];
m_vrEvents[controlledId].m_orn[2] = vrEvents[i].m_orn[2];
m_vrEvents[controlledId].m_orn[3] = vrEvents[i].m_orn[3];
}
m_vrEvents[controlledId].m_numButtonEvents += vrEvents[i].m_numButtonEvents;
m_vrEvents[controlledId].m_numMoveEvents += vrEvents[i].m_numMoveEvents;
for (int b = 0; b < MAX_VR_BUTTONS; b++)
{
m_vrEvents[controlledId].m_buttons[b] |= vrEvents[i].m_buttons[b];
if (vrEvents[i].m_buttons[b] & eButtonIsDown)
{
m_vrEvents[controlledId].m_buttons[b] |= eButtonIsDown;
}
else
{
m_vrEvents[controlledId].m_buttons[b] &= ~eButtonIsDown;
}
}
}
};
};
struct VRControllerStateLogger : public InternalStateLogger
{
b3VRControllerEvents m_vrEvents;
int m_loggingTimeStamp;
int m_deviceTypeFilter;
std::string m_fileName;
FILE* m_logFileHandle;
std::string m_structTypes;
VRControllerStateLogger(int loggingUniqueId, int deviceTypeFilter, const std::string& fileName)
: m_loggingTimeStamp(0),
m_deviceTypeFilter(deviceTypeFilter),
m_fileName(fileName),
m_logFileHandle(0)
{
m_loggingUniqueId = loggingUniqueId;
m_loggingType = STATE_LOGGING_VR_CONTROLLERS;
btAlignedObjectArray<std::string> structNames;
structNames.push_back("stepCount");
structNames.push_back("timeStamp");
structNames.push_back("controllerId");
structNames.push_back("numMoveEvents");
structNames.push_back("m_numButtonEvents");
structNames.push_back("posX");
structNames.push_back("posY");
structNames.push_back("posZ");
structNames.push_back("oriX");
structNames.push_back("oriY");
structNames.push_back("oriZ");
structNames.push_back("oriW");
structNames.push_back("analogAxis");
structNames.push_back("buttons0");
structNames.push_back("buttons1");
structNames.push_back("buttons2");
structNames.push_back("buttons3");
structNames.push_back("buttons4");
structNames.push_back("buttons5");
structNames.push_back("buttons6");
structNames.push_back("deviceType");
m_structTypes = "IfIIIffffffffIIIIIIII";
const char* fileNameC = fileName.c_str();
m_logFileHandle = createMinitaurLogFile(fileNameC, structNames, m_structTypes);
}
virtual void stop()
{
if (m_logFileHandle)
{
closeMinitaurLogFile(m_logFileHandle);
m_logFileHandle = 0;
}
}
virtual void logState(btScalar timeStep)
{
if (m_logFileHandle)
{
int stepCount = m_loggingTimeStamp;
float timeStamp = m_loggingTimeStamp * timeStep;
for (int i = 0; i < MAX_VR_CONTROLLERS; i++)
{
b3VRControllerEvent& event = m_vrEvents.m_vrEvents[i];
if (m_deviceTypeFilter & event.m_deviceType)
{
if (event.m_numButtonEvents + event.m_numMoveEvents)
{
MinitaurLogRecord logData;
//serverStatusOut.m_sendVREvents.m_controllerEvents[serverStatusOut.m_sendVREvents.m_numVRControllerEvents++] = event;
//log the event
logData.m_values.push_back(stepCount);
logData.m_values.push_back(timeStamp);
logData.m_values.push_back(event.m_controllerId);
logData.m_values.push_back(event.m_numMoveEvents);
logData.m_values.push_back(event.m_numButtonEvents);
logData.m_values.push_back(event.m_pos[0]);
logData.m_values.push_back(event.m_pos[1]);
logData.m_values.push_back(event.m_pos[2]);
logData.m_values.push_back(event.m_orn[0]);
logData.m_values.push_back(event.m_orn[1]);
logData.m_values.push_back(event.m_orn[2]);
logData.m_values.push_back(event.m_orn[3]);
logData.m_values.push_back(event.m_analogAxis);
int packedButtons[7] = {0, 0, 0, 0, 0, 0, 0};
int packedButtonIndex = 0;
int packedButtonShift = 0;
//encode the 64 buttons into 7 int (3 bits each), each int stores 10 buttons
for (int b = 0; b < MAX_VR_BUTTONS; b++)
{
int buttonMask = event.m_buttons[b];
buttonMask = buttonMask << (packedButtonShift * 3);
packedButtons[packedButtonIndex] |= buttonMask;
packedButtonShift++;
if (packedButtonShift >= 10)
{
packedButtonShift = 0;
packedButtonIndex++;
if (packedButtonIndex >= 7)
{
btAssert(0);
break;
}
}
}
for (int b = 0; b < 7; b++)
{
logData.m_values.push_back(packedButtons[b]);
}
logData.m_values.push_back(event.m_deviceType);
appendMinitaurLogData(m_logFileHandle, m_structTypes, logData);
event.m_numButtonEvents = 0;
event.m_numMoveEvents = 0;
for (int b = 0; b < MAX_VR_BUTTONS; b++)
{
event.m_buttons[b] = 0;
}
}
}
}
fflush(m_logFileHandle);
m_loggingTimeStamp++;
}
}
};
struct GenericRobotStateLogger : public InternalStateLogger
{
float m_loggingTimeStamp;
std::string m_fileName;
FILE* m_logFileHandle;
std::string m_structTypes;
const btMultiBodyDynamicsWorld* m_dynamicsWorld;
btAlignedObjectArray<int> m_bodyIdList;
bool m_filterObjectUniqueId;
int m_maxLogDof;
int m_logFlags;
GenericRobotStateLogger(int loggingUniqueId, const std::string& fileName, const btMultiBodyDynamicsWorld* dynamicsWorld, int maxLogDof, int logFlags)
: m_loggingTimeStamp(0),
m_logFileHandle(0),
m_dynamicsWorld(dynamicsWorld),
m_filterObjectUniqueId(false),
m_maxLogDof(maxLogDof),
m_logFlags(logFlags)
{
m_loggingUniqueId = loggingUniqueId;
m_loggingType = STATE_LOGGING_GENERIC_ROBOT;
btAlignedObjectArray<std::string> structNames;
structNames.push_back("stepCount");
structNames.push_back("timeStamp");
structNames.push_back("objectId");
structNames.push_back("posX");
structNames.push_back("posY");
structNames.push_back("posZ");
structNames.push_back("oriX");
structNames.push_back("oriY");
structNames.push_back("oriZ");
structNames.push_back("oriW");
structNames.push_back("velX");
structNames.push_back("velY");
structNames.push_back("velZ");
structNames.push_back("omegaX");
structNames.push_back("omegaY");
structNames.push_back("omegaZ");
structNames.push_back("qNum");
m_structTypes = "IfifffffffffffffI";
for (int i = 0; i < m_maxLogDof; i++)
{
m_structTypes.append("f");
char jointName[256];
sprintf(jointName, "q%d", i);
structNames.push_back(jointName);
}
for (int i = 0; i < m_maxLogDof; i++)
{
m_structTypes.append("f");
char jointName[256];
sprintf(jointName, "u%d", i);
structNames.push_back(jointName);
}
if (m_logFlags & STATE_LOG_JOINT_TORQUES)
{
for (int i = 0; i < m_maxLogDof; i++)
{
m_structTypes.append("f");
char jointName[256];
sprintf(jointName, "t%d", i);
structNames.push_back(jointName);
}
}
const char* fileNameC = fileName.c_str();
m_logFileHandle = createMinitaurLogFile(fileNameC, structNames, m_structTypes);
}
virtual void stop()
{
if (m_logFileHandle)
{
closeMinitaurLogFile(m_logFileHandle);
m_logFileHandle = 0;
}
}
virtual void logState(btScalar timeStep)
{
if (m_logFileHandle)
{
for (int i = 0; i < m_dynamicsWorld->getNumMultibodies(); i++)
{
const btMultiBody* mb = m_dynamicsWorld->getMultiBody(i);
int objectUniqueId = mb->getUserIndex2();
if (m_filterObjectUniqueId && m_bodyIdList.findLinearSearch2(objectUniqueId) < 0)
{
continue;
}
MinitaurLogRecord logData;
int stepCount = m_loggingTimeStamp;
float timeStamp = m_loggingTimeStamp * m_dynamicsWorld->getSolverInfo().m_timeStep;
logData.m_values.push_back(stepCount);
logData.m_values.push_back(timeStamp);
btVector3 pos = mb->getBasePos();
btQuaternion ori = mb->getWorldToBaseRot().inverse();
btVector3 vel = mb->getBaseVel();
btVector3 omega = mb->getBaseOmega();
float posX = pos[0];
float posY = pos[1];
float posZ = pos[2];
float oriX = ori.x();
float oriY = ori.y();
float oriZ = ori.z();
float oriW = ori.w();
float velX = vel[0];
float velY = vel[1];
float velZ = vel[2];
float omegaX = omega[0];
float omegaY = omega[1];
float omegaZ = omega[2];
logData.m_values.push_back(objectUniqueId);
logData.m_values.push_back(posX);
logData.m_values.push_back(posY);
logData.m_values.push_back(posZ);
logData.m_values.push_back(oriX);
logData.m_values.push_back(oriY);
logData.m_values.push_back(oriZ);
logData.m_values.push_back(oriW);
logData.m_values.push_back(velX);
logData.m_values.push_back(velY);
logData.m_values.push_back(velZ);
logData.m_values.push_back(omegaX);
logData.m_values.push_back(omegaY);
logData.m_values.push_back(omegaZ);
int numDofs = mb->getNumDofs();
logData.m_values.push_back(numDofs);
int numJoints = mb->getNumLinks();
for (int j = 0; j < numJoints; ++j)
{
if (mb->getLink(j).m_jointType == 0 || mb->getLink(j).m_jointType == 1)
{
float q = mb->getJointPos(j);
logData.m_values.push_back(q);
}
}
for (int j = numDofs; j < m_maxLogDof; ++j)
{
float q = 0.0;
logData.m_values.push_back(q);
}
for (int j = 0; j < numJoints; ++j)
{
if (mb->getLink(j).m_jointType == 0 || mb->getLink(j).m_jointType == 1)
{
float v = mb->getJointVel(j);
logData.m_values.push_back(v);
}
}
for (int j = numDofs; j < m_maxLogDof; ++j)
{
float v = 0.0;
logData.m_values.push_back(v);
}
if (m_logFlags & STATE_LOG_JOINT_TORQUES)
{
for (int j = 0; j < numJoints; ++j)
{
if (mb->getLink(j).m_jointType == 0 || mb->getLink(j).m_jointType == 1)
{
float jointTorque = 0;
if (m_logFlags & STATE_LOG_JOINT_MOTOR_TORQUES)
{
btMultiBodyJointMotor* motor = (btMultiBodyJointMotor*)mb->getLink(j).m_userPtr;
if (motor)
{
jointTorque += motor->getAppliedImpulse(0) / timeStep;
}
}
if (m_logFlags & STATE_LOG_JOINT_USER_TORQUES)
{
if (mb->getLink(j).m_jointType == 0 || mb->getLink(j).m_jointType == 1)
{
jointTorque += mb->getJointTorque(j); //these are the 'user' applied external torques
}
}
logData.m_values.push_back(jointTorque);
}
}
for (int j = numDofs; j < m_maxLogDof; ++j)
{
float u = 0.0;
logData.m_values.push_back(u);
}
}
//at the moment, appendMinitaurLogData will directly write to disk (potential delay)
//better to fill a huge memory buffer and once in a while write it to disk
appendMinitaurLogData(m_logFileHandle, m_structTypes, logData);
fflush(m_logFileHandle);
}
m_loggingTimeStamp++;
}
}
};
struct ContactPointsStateLogger : public InternalStateLogger
{
int m_loggingTimeStamp;
std::string m_fileName;
FILE* m_logFileHandle;
std::string m_structTypes;
btMultiBodyDynamicsWorld* m_dynamicsWorld;
bool m_filterLinkA;
bool m_filterLinkB;
int m_linkIndexA;
int m_linkIndexB;
int m_bodyUniqueIdA;
int m_bodyUniqueIdB;
ContactPointsStateLogger(int loggingUniqueId, const std::string& fileName, btMultiBodyDynamicsWorld* dynamicsWorld)
: m_loggingTimeStamp(0),
m_fileName(fileName),
m_logFileHandle(0),
m_dynamicsWorld(dynamicsWorld),
m_filterLinkA(false),
m_filterLinkB(false),
m_linkIndexA(-2),
m_linkIndexB(-2),
m_bodyUniqueIdA(-1),
m_bodyUniqueIdB(-1)
{
m_loggingUniqueId = loggingUniqueId;
m_loggingType = STATE_LOGGING_CONTACT_POINTS;
btAlignedObjectArray<std::string> structNames;
structNames.push_back("stepCount");
structNames.push_back("timeStamp");
structNames.push_back("contactFlag");
structNames.push_back("bodyUniqueIdA");
structNames.push_back("bodyUniqueIdB");
structNames.push_back("linkIndexA");
structNames.push_back("linkIndexB");
structNames.push_back("positionOnAX");
structNames.push_back("positionOnAY");
structNames.push_back("positionOnAZ");
structNames.push_back("positionOnBX");
structNames.push_back("positionOnBY");
structNames.push_back("positionOnBZ");
structNames.push_back("contactNormalOnBX");
structNames.push_back("contactNormalOnBY");
structNames.push_back("contactNormalOnBZ");
structNames.push_back("contactDistance");
structNames.push_back("normalForce");
m_structTypes = "IfIiiiifffffffffff";
const char* fileNameC = fileName.c_str();
m_logFileHandle = createMinitaurLogFile(fileNameC, structNames, m_structTypes);
}
virtual void stop()
{
if (m_logFileHandle)
{
closeMinitaurLogFile(m_logFileHandle);
m_logFileHandle = 0;
}
}
virtual void logState(btScalar timeStep)
{
if (m_logFileHandle)
{
int numContactManifolds = m_dynamicsWorld->getDispatcher()->getNumManifolds();
for (int i = 0; i < numContactManifolds; i++)
{
const btPersistentManifold* manifold = m_dynamicsWorld->getDispatcher()->getInternalManifoldPointer()[i];
int linkIndexA = -1;
int linkIndexB = -1;
int objectIndexB = -1;
const btRigidBody* bodyB = btRigidBody::upcast(manifold->getBody1());
if (bodyB)
{
objectIndexB = bodyB->getUserIndex2();
}
const btMultiBodyLinkCollider* mblB = btMultiBodyLinkCollider::upcast(manifold->getBody1());
if (mblB && mblB->m_multiBody)
{
linkIndexB = mblB->m_link;
objectIndexB = mblB->m_multiBody->getUserIndex2();
if (m_filterLinkB && (m_linkIndexB != linkIndexB))
{
continue;
}
}
int objectIndexA = -1;
const btRigidBody* bodyA = btRigidBody::upcast(manifold->getBody0());
if (bodyA)
{
objectIndexA = bodyA->getUserIndex2();
}
const btMultiBodyLinkCollider* mblA = btMultiBodyLinkCollider::upcast(manifold->getBody0());
if (mblA && mblA->m_multiBody)
{
linkIndexA = mblA->m_link;
objectIndexA = mblA->m_multiBody->getUserIndex2();
if (m_filterLinkA && (m_linkIndexA != linkIndexA))
{
continue;
}
}
btAssert(bodyA || mblA);
//apply the filter, if the user provides it
if (m_bodyUniqueIdA >= 0)
{
if ((m_bodyUniqueIdA != objectIndexA) &&
(m_bodyUniqueIdA != objectIndexB))
continue;
}
//apply the second object filter, if the user provides it
if (m_bodyUniqueIdB >= 0)
{
if ((m_bodyUniqueIdB != objectIndexA) &&
(m_bodyUniqueIdB != objectIndexB))
continue;
}
for (int p = 0; p < manifold->getNumContacts(); p++)
{
MinitaurLogRecord logData;
int stepCount = m_loggingTimeStamp;
float timeStamp = m_loggingTimeStamp * timeStep;
logData.m_values.push_back(stepCount);
logData.m_values.push_back(timeStamp);
const btManifoldPoint& srcPt = manifold->getContactPoint(p);
logData.m_values.push_back(0); // reserved contact flag
logData.m_values.push_back(objectIndexA);
logData.m_values.push_back(objectIndexB);
logData.m_values.push_back(linkIndexA);
logData.m_values.push_back(linkIndexB);
logData.m_values.push_back((float)(srcPt.getPositionWorldOnA()[0]));
logData.m_values.push_back((float)(srcPt.getPositionWorldOnA()[1]));
logData.m_values.push_back((float)(srcPt.getPositionWorldOnA()[2]));
logData.m_values.push_back((float)(srcPt.getPositionWorldOnB()[0]));
logData.m_values.push_back((float)(srcPt.getPositionWorldOnB()[1]));
logData.m_values.push_back((float)(srcPt.getPositionWorldOnB()[2]));
logData.m_values.push_back((float)(srcPt.m_normalWorldOnB[0]));
logData.m_values.push_back((float)(srcPt.m_normalWorldOnB[1]));
logData.m_values.push_back((float)(srcPt.m_normalWorldOnB[2]));
logData.m_values.push_back((float)(srcPt.getDistance()));
logData.m_values.push_back((float)(srcPt.getAppliedImpulse() / timeStep));
appendMinitaurLogData(m_logFileHandle, m_structTypes, logData);
fflush(m_logFileHandle);
}
}
m_loggingTimeStamp++;
}
}
};
struct SaveStateData
{
bParse::btBulletFile* m_bulletFile;
btSerializer* m_serializer;
};
struct PhysicsServerCommandProcessorInternalData
{
///handle management
b3ResizablePool<InternalTextureHandle> m_textureHandles;
b3ResizablePool<InternalBodyHandle> m_bodyHandles;
b3ResizablePool<InternalCollisionShapeHandle> m_userCollisionShapeHandles;
b3ResizablePool<InternalVisualShapeHandle> m_userVisualShapeHandles;
b3ResizablePool<b3PoolBodyHandle<SharedMemoryUserData> > m_userDataHandles;
btHashMap<SharedMemoryUserDataHashKey, int> m_userDataHandleLookup;
b3PluginManager m_pluginManager;
bool m_useRealTimeSimulation;
b3VRControllerEvents m_vrControllerEvents;
btAlignedObjectArray<SaveStateData> m_savedStates;
btAlignedObjectArray<b3KeyboardEvent> m_keyboardEvents;
btAlignedObjectArray<b3MouseEvent> m_mouseEvents;
CommandLogger* m_commandLogger;
int m_commandLoggingUid;
CommandLogPlayback* m_logPlayback;
int m_logPlaybackUid;
btScalar m_physicsDeltaTime;
btScalar m_numSimulationSubSteps;
btScalar m_simulationTimestamp;
btAlignedObjectArray<btMultiBodyJointFeedback*> m_multiBodyJointFeedbacks;
b3HashMap<btHashPtr, btInverseDynamics::MultiBodyTree*> m_inverseDynamicsBodies;
b3HashMap<btHashPtr, IKTrajectoryHelper*> m_inverseKinematicsHelpers;
int m_userConstraintUIDGenerator;
b3HashMap<btHashInt, InteralUserConstraintData> m_userConstraints;
b3AlignedObjectArray<SaveWorldObjectData> m_saveWorldBodyData;
btAlignedObjectArray<btMultiBodyWorldImporter*> m_worldImporters;
btAlignedObjectArray<std::string*> m_strings;
btAlignedObjectArray<btCollisionShape*> m_collisionShapes;
btAlignedObjectArray<const unsigned char*> m_heightfieldDatas;
btAlignedObjectArray<int> m_allocatedTextures;
btHashMap<btHashPtr, UrdfCollision> m_bulletCollisionShape2UrdfCollision;
btAlignedObjectArray<btStridingMeshInterface*> m_meshInterfaces;
MyOverlapFilterCallback* m_broadphaseCollisionFilterCallback;
btHashedOverlappingPairCache* m_pairCache;
btBroadphaseInterface* m_broadphase;
btCollisionDispatcher* m_dispatcher;
btMultiBodyConstraintSolver* m_solver;
btDefaultCollisionConfiguration* m_collisionConfiguration;
#ifndef SKIP_DEFORMABLE_BODY
btDeformableBodySolver* m_deformablebodySolver;
btAlignedObjectArray<btDeformableLagrangianForce*> m_lf;
#endif
btMultiBodyDynamicsWorld* m_dynamicsWorld;
int m_constraintSolverType;
SharedMemoryDebugDrawer* m_remoteDebugDrawer;
btAlignedObjectArray<b3ContactPointData> m_cachedContactPoints;
MyBroadphaseCallback m_cachedOverlappingObjects;
btAlignedObjectArray<int> m_sdfRecentLoadedBodies;
btAlignedObjectArray<int> m_graphicsIndexToSegmentationMask;
btAlignedObjectArray<InternalStateLogger*> m_stateLoggers;
int m_stateLoggersUniqueId;
int m_profileTimingLoggingUid;
std::string m_profileTimingFileName;
struct GUIHelperInterface* m_guiHelper;
int m_sharedMemoryKey;
bool m_enableTinyRenderer;
bool m_verboseOutput;
//data for picking objects
class btRigidBody* m_pickedBody;
int m_savedActivationState;
class btTypedConstraint* m_pickedConstraint;
class btMultiBodyPoint2Point* m_pickingMultiBodyPoint2Point;
btVector3 m_oldPickingPos;
btVector3 m_hitPos;
btScalar m_oldPickingDist;
bool m_prevCanSleep;
int m_pdControlPlugin;
int m_collisionFilterPlugin;
int m_grpcPlugin;
#ifdef B3_ENABLE_TINY_AUDIO
b3SoundEngine m_soundEngine;
#endif
b3HashMap<b3HashString, char*> m_profileEvents;
b3HashMap<b3HashString, UrdfVisualShapeCache> m_cachedVUrdfisualShapes;
b3ThreadPool* m_threadPool;
btScalar m_defaultCollisionMargin;
double m_remoteSyncTransformTime;
double m_remoteSyncTransformInterval;
PhysicsServerCommandProcessorInternalData(PhysicsCommandProcessorInterface* proc)
: m_pluginManager(proc),
m_useRealTimeSimulation(false),
m_commandLogger(0),
m_commandLoggingUid(-1),
m_logPlayback(0),
m_logPlaybackUid(-1),
m_physicsDeltaTime(1. / 240.),
m_numSimulationSubSteps(0),
m_simulationTimestamp(0),
m_userConstraintUIDGenerator(1),
m_broadphaseCollisionFilterCallback(0),
m_pairCache(0),
m_broadphase(0),
m_dispatcher(0),
m_solver(0),
m_collisionConfiguration(0),
#ifndef SKIP_DEFORMABLE_BODY
m_deformablebodySolver(0),
#endif
m_dynamicsWorld(0),
m_constraintSolverType(-1),
m_remoteDebugDrawer(0),
m_stateLoggersUniqueId(0),
m_profileTimingLoggingUid(-1),
m_guiHelper(0),
m_sharedMemoryKey(SHARED_MEMORY_KEY),
m_enableTinyRenderer(true),
m_verboseOutput(false),
m_pickedBody(0),
m_pickedConstraint(0),
m_pickingMultiBodyPoint2Point(0),
m_pdControlPlugin(-1),
m_collisionFilterPlugin(-1),
m_grpcPlugin(-1),
m_threadPool(0),
m_defaultCollisionMargin(0.001),
m_remoteSyncTransformTime(1. / 30.),
m_remoteSyncTransformInterval(1. / 30.)
{
{
//register static plugins:
#ifdef STATIC_LINK_VR_PLUGIN
b3PluginFunctions funcs(initPlugin_vrSyncPlugin, exitPlugin_vrSyncPlugin, executePluginCommand_vrSyncPlugin);
funcs.m_preTickFunc = preTickPluginCallback_vrSyncPlugin;
m_pluginManager.registerStaticLinkedPlugin("vrSyncPlugin", funcs);
#endif //STATIC_LINK_VR_PLUGIN
}
#ifndef SKIP_STATIC_PD_CONTROL_PLUGIN
{
//int b3PluginManager::registerStaticLinkedPlugin(const char* pluginPath, PFN_INIT initFunc, PFN_EXIT exitFunc, PFN_EXECUTE executeCommandFunc, PFN_TICK preTickFunc, PFN_TICK postTickFunc, PFN_GET_RENDER_INTERFACE getRendererFunc, PFN_TICK processClientCommandsFunc, PFN_GET_COLLISION_INTERFACE getCollisionFunc, bool initPlugin)
b3PluginFunctions funcs(initPlugin_pdControlPlugin, exitPlugin_pdControlPlugin, executePluginCommand_pdControlPlugin);
funcs.m_preTickFunc = preTickPluginCallback_pdControlPlugin;
m_pdControlPlugin = m_pluginManager.registerStaticLinkedPlugin("pdControlPlugin", funcs);
}
#endif //SKIP_STATIC_PD_CONTROL_PLUGIN
#ifndef SKIP_COLLISION_FILTER_PLUGIN
{
b3PluginFunctions funcs(initPlugin_collisionFilterPlugin, exitPlugin_collisionFilterPlugin, executePluginCommand_collisionFilterPlugin);
funcs.m_getCollisionFunc = getCollisionInterface_collisionFilterPlugin;
m_collisionFilterPlugin = m_pluginManager.registerStaticLinkedPlugin("collisionFilterPlugin", funcs);
m_pluginManager.selectCollisionPlugin(m_collisionFilterPlugin);
}
#endif
#ifdef ENABLE_STATIC_GRPC_PLUGIN
{
b3PluginFunctions funcs(initPlugin_grpcPlugin, exitPlugin_grpcPlugin, executePluginCommand_grpcPlugin);
funcs.m_processClientCommandsFunc = processClientCommands_grpcPlugin;
m_grpcPlugin = m_pluginManager.registerStaticLinkedPlugin("grpcPlugin", funcs);
}
#endif //ENABLE_STATIC_GRPC_PLUGIN
#ifdef STATIC_EGLRENDERER_PLUGIN
{
bool initPlugin = false;
b3PluginFunctions funcs(initPlugin_eglRendererPlugin, exitPlugin_eglRendererPlugin, executePluginCommand_eglRendererPlugin);
funcs.m_getRendererFunc = getRenderInterface_eglRendererPlugin;
int renderPluginId = m_pluginManager.registerStaticLinkedPlugin("eglRendererPlugin", funcs, initPlugin);
m_pluginManager.selectPluginRenderer(renderPluginId);
}
#endif //STATIC_EGLRENDERER_PLUGIN
#ifndef SKIP_STATIC_TINYRENDERER_PLUGIN
{
b3PluginFunctions funcs(initPlugin_tinyRendererPlugin, exitPlugin_tinyRendererPlugin, executePluginCommand_tinyRendererPlugin);
funcs.m_getRendererFunc = getRenderInterface_tinyRendererPlugin;
int renderPluginId = m_pluginManager.registerStaticLinkedPlugin("tinyRendererPlugin", funcs);
m_pluginManager.selectPluginRenderer(renderPluginId);
}
#endif
#ifdef B3_ENABLE_FILEIO_PLUGIN
{
b3PluginFunctions funcs(initPlugin_fileIOPlugin, exitPlugin_fileIOPlugin, executePluginCommand_fileIOPlugin);
funcs.m_fileIoFunc = getFileIOFunc_fileIOPlugin;
int renderPluginId = m_pluginManager.registerStaticLinkedPlugin("fileIOPlugin", funcs);
m_pluginManager.selectFileIOPlugin(renderPluginId);
}
#endif
m_vrControllerEvents.init();
m_bodyHandles.exitHandles();
m_bodyHandles.initHandles();
m_userCollisionShapeHandles.exitHandles();
m_userCollisionShapeHandles.initHandles();
m_userVisualShapeHandles.exitHandles();
m_userVisualShapeHandles.initHandles();
}
#ifdef STATIC_LINK_SPD_PLUGIN
b3HashMap<btHashPtr, cRBDModel*> m_rbdModels;
static void convertPose(const btMultiBody* multiBody, const double* jointPositionsQ, const double* jointVelocitiesQdot, Eigen::VectorXd& pose, Eigen::VectorXd& vel)
{
int baseDofQ = multiBody->hasFixedBase() ? 0 : 7;
int baseDofQdot = multiBody->hasFixedBase() ? 0 : 6;
pose.resize(7 + multiBody->getNumPosVars());
vel.resize(7 + multiBody->getNumPosVars()); //??
btTransform tr = multiBody->getBaseWorldTransform();
int dofsrc = 0;
int velsrcdof = 0;
if (baseDofQ == 7)
{
pose[0] = jointPositionsQ[dofsrc++];
pose[1] = jointPositionsQ[dofsrc++];
pose[2] = jointPositionsQ[dofsrc++];
double quatXYZW[4];
quatXYZW[0] = jointPositionsQ[dofsrc++];
quatXYZW[1] = jointPositionsQ[dofsrc++];
quatXYZW[2] = jointPositionsQ[dofsrc++];
quatXYZW[3] = jointPositionsQ[dofsrc++];
pose[3] = quatXYZW[3];
pose[4] = quatXYZW[0];
pose[5] = quatXYZW[1];
pose[6] = quatXYZW[2];
}
else
{
pose[0] = tr.getOrigin()[0];
pose[1] = tr.getOrigin()[1];
pose[2] = tr.getOrigin()[2];
pose[3] = tr.getRotation()[3];
pose[4] = tr.getRotation()[0];
pose[5] = tr.getRotation()[1];
pose[6] = tr.getRotation()[2];
}
if (baseDofQdot == 6)
{
vel[0] = jointVelocitiesQdot[velsrcdof++];
vel[1] = jointVelocitiesQdot[velsrcdof++];
vel[2] = jointVelocitiesQdot[velsrcdof++];
vel[3] = jointVelocitiesQdot[velsrcdof++];
vel[4] = jointVelocitiesQdot[velsrcdof++];
vel[5] = jointVelocitiesQdot[velsrcdof++];
vel[6] = jointVelocitiesQdot[velsrcdof++];
vel[6] = 0;
}
else
{
vel[0] = multiBody->getBaseVel()[0];
vel[1] = multiBody->getBaseVel()[1];
vel[2] = multiBody->getBaseVel()[2];
vel[3] = multiBody->getBaseOmega()[0];
vel[4] = multiBody->getBaseOmega()[1];
vel[5] = multiBody->getBaseOmega()[2];
vel[6] = 0;
}
int dof = 7;
int veldof = 7;
for (int l = 0; l < multiBody->getNumLinks(); l++)
{
switch (multiBody->getLink(l).m_jointType)
{
case btMultibodyLink::eRevolute:
case btMultibodyLink::ePrismatic:
{
pose[dof++] = jointPositionsQ[dofsrc++];
vel[veldof++] = jointVelocitiesQdot[velsrcdof++];
break;
}
case btMultibodyLink::eSpherical:
{
double quatXYZW[4];
quatXYZW[0] = jointPositionsQ[dofsrc++];
quatXYZW[1] = jointPositionsQ[dofsrc++];
quatXYZW[2] = jointPositionsQ[dofsrc++];
quatXYZW[3] = jointPositionsQ[dofsrc++];
pose[dof++] = quatXYZW[3];
pose[dof++] = quatXYZW[0];
pose[dof++] = quatXYZW[1];
pose[dof++] = quatXYZW[2];
vel[veldof++] = jointVelocitiesQdot[velsrcdof++];
vel[veldof++] = jointVelocitiesQdot[velsrcdof++];
vel[veldof++] = jointVelocitiesQdot[velsrcdof++];
vel[veldof++] = jointVelocitiesQdot[velsrcdof++];
break;
}
case btMultibodyLink::eFixed:
{
break;
}
default:
{
assert(0);
}
}
}
}
cRBDModel* findOrCreateRBDModel(btMultiBody* multiBody, const double* jointPositionsQ, const double* jointVelocitiesQdot)
{
cRBDModel* rbdModel = 0;
cRBDModel** rbdModelPtr = m_rbdModels.find(multiBody);
if (rbdModelPtr)
{
rbdModel = *rbdModelPtr;
}
else
{
rbdModel = new cRBDModel();
Eigen::MatrixXd bodyDefs;
Eigen::MatrixXd jointMat;
btExtractJointBodyFromBullet(multiBody, bodyDefs, jointMat);
btVector3 grav = m_dynamicsWorld->getGravity();
tVector3 gravity(grav[0], grav[1], grav[2], 0);
rbdModel->Init(jointMat, bodyDefs, gravity);
m_rbdModels.insert(multiBody, rbdModel);
}
//sync pose and vel
Eigen::VectorXd pose, vel;
PhysicsServerCommandProcessorInternalData::convertPose(multiBody, jointPositionsQ, jointVelocitiesQdot, pose, vel);
btVector3 gravOrg = m_dynamicsWorld->getGravity();
tVector grav(gravOrg[0], gravOrg[1], gravOrg[2], 0);
rbdModel->SetGravity(grav);
{
BT_PROFILE("rbdModel::Update");
rbdModel->Update(pose, vel);
}
return rbdModel;
}
#endif
btInverseDynamics::MultiBodyTree* findOrCreateTree(btMultiBody* multiBody)
{
btInverseDynamics::MultiBodyTree* tree = 0;
btInverseDynamics::MultiBodyTree** treePtrPtr =
m_inverseDynamicsBodies.find(multiBody);
if (treePtrPtr)
{
tree = *treePtrPtr;
}
else
{
btInverseDynamics::btMultiBodyTreeCreator id_creator;
if (-1 == id_creator.createFromBtMultiBody(multiBody, false))
{
}
else
{
tree = btInverseDynamics::CreateMultiBodyTree(id_creator);
m_inverseDynamicsBodies.insert(multiBody, tree);
}
}
return tree;
}
};
void PhysicsServerCommandProcessor::setGuiHelper(struct GUIHelperInterface* guiHelper)
{
if (guiHelper)
{
guiHelper->createPhysicsDebugDrawer(m_data->m_dynamicsWorld);
}
else
{
//state loggers use guiHelper, so remove them before the guiHelper is deleted
deleteStateLoggers();
if (m_data->m_guiHelper && m_data->m_dynamicsWorld && m_data->m_dynamicsWorld->getDebugDrawer())
{
m_data->m_dynamicsWorld->setDebugDrawer(0);
}
}
m_data->m_guiHelper = guiHelper;
}
PhysicsServerCommandProcessor::PhysicsServerCommandProcessor()
: m_data(0)
{
m_data = new PhysicsServerCommandProcessorInternalData(this);
createEmptyDynamicsWorld();
}
PhysicsServerCommandProcessor::~PhysicsServerCommandProcessor()
{
deleteDynamicsWorld();
if (m_data->m_commandLogger)
{
delete m_data->m_commandLogger;
m_data->m_commandLogger = 0;
}
for (int i = 0; i < m_data->m_profileEvents.size(); i++)
{
char* event = *m_data->m_profileEvents.getAtIndex(i);
delete[] event;
}
if (m_data->m_threadPool)
delete m_data->m_threadPool;
delete m_data;
}
void preTickCallback(btDynamicsWorld* world, btScalar timeStep)
{
PhysicsServerCommandProcessor* proc = (PhysicsServerCommandProcessor*)world->getWorldUserInfo();
proc->tickPlugins(timeStep, true);
}
void logCallback(btDynamicsWorld* world, btScalar timeStep)
{
//handle the logging and playing sounds
PhysicsServerCommandProcessor* proc = (PhysicsServerCommandProcessor*)world->getWorldUserInfo();
proc->processCollisionForces(timeStep);
proc->logObjectStates(timeStep);
proc->tickPlugins(timeStep, false);
}
bool MyContactAddedCallback(btManifoldPoint& cp, const btCollisionObjectWrapper* colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper* colObj1Wrap, int partId1, int index1)
{
btAdjustInternalEdgeContacts(cp, colObj1Wrap, colObj0Wrap, partId1, index1);
return true;
}
bool MyContactDestroyedCallback(void* userPersistentData)
{
//printf("destroyed\n");
return false;
}
bool MyContactProcessedCallback(btManifoldPoint& cp, void* body0, void* body1)
{
//printf("processed\n");
return false;
}
void MyContactStartedCallback(btPersistentManifold* const& manifold)
{
//printf("started\n");
}
void MyContactEndedCallback(btPersistentManifold* const& manifold)
{
// printf("ended\n");
}
void PhysicsServerCommandProcessor::processCollisionForces(btScalar timeStep)
{
#ifdef B3_ENABLE_TINY_AUDIO
//this is experimental at the moment: impulse thresholds, sound parameters will be exposed in C-API/pybullet.
//audio will go into a wav file, as well as real-time output to speakers/headphones using RtAudio/DAC.
int numContactManifolds = m_data->m_dynamicsWorld->getDispatcher()->getNumManifolds();
for (int i = 0; i < numContactManifolds; i++)
{
const btPersistentManifold* manifold = m_data->m_dynamicsWorld->getDispatcher()->getInternalManifoldPointer()[i];
bool objHasSound[2];
objHasSound[0] = (0 != (manifold->getBody0()->getCollisionFlags() & btCollisionObject::CF_HAS_COLLISION_SOUND_TRIGGER));
objHasSound[1] = (0 != (manifold->getBody1()->getCollisionFlags() & btCollisionObject::CF_HAS_COLLISION_SOUND_TRIGGER));
const btCollisionObject* colObjs[2] = {manifold->getBody0(), manifold->getBody1()};
for (int ob = 0; ob < 2; ob++)
{
if (objHasSound[ob])
{
int uid0 = -1;
int linkIndex = -2;
const btMultiBodyLinkCollider* mblB = btMultiBodyLinkCollider::upcast(colObjs[ob]);
if (mblB && mblB->m_multiBody)
{
linkIndex = mblB->m_link;
uid0 = mblB->m_multiBody->getUserIndex2();
}
const btRigidBody* bodyB = btRigidBody::upcast(colObjs[ob]);
if (bodyB)
{
uid0 = bodyB->getUserIndex2();
linkIndex = -1;
}
if ((uid0 < 0) || (linkIndex < -1))
continue;
InternalBodyHandle* bodyHandle0 = m_data->m_bodyHandles.getHandle(uid0);
SDFAudioSource* audioSrc = bodyHandle0->m_audioSources[linkIndex];
if (audioSrc == 0)
continue;
for (int p = 0; p < manifold->getNumContacts(); p++)
{
double imp = manifold->getContactPoint(p).getAppliedImpulse();
//printf ("manifold %d, contact %d, lifeTime:%d, appliedImpulse:%f\n",i,p, manifold->getContactPoint(p).getLifeTime(),imp);
if (imp > audioSrc->m_collisionForceThreshold && manifold->getContactPoint(p).getLifeTime() == 1)
{
int soundSourceIndex = m_data->m_soundEngine.getAvailableSoundSource();
if (soundSourceIndex >= 0)
{
b3SoundMessage msg;
msg.m_attackRate = audioSrc->m_attackRate;
msg.m_decayRate = audioSrc->m_decayRate;
msg.m_sustainLevel = audioSrc->m_sustainLevel;
msg.m_releaseRate = audioSrc->m_releaseRate;
msg.m_amplitude = audioSrc->m_gain;
msg.m_frequency = audioSrc->m_pitch;
msg.m_type = B3_SOUND_SOURCE_WAV_FILE;
msg.m_wavId = audioSrc->m_userIndex;
msg.m_autoKeyOff = true;
m_data->m_soundEngine.startSound(soundSourceIndex, msg);
}
}
}
}
}
}
#endif //B3_ENABLE_TINY_AUDIO
}
void PhysicsServerCommandProcessor::processClientCommands()
{
m_data->m_pluginManager.tickPlugins(0, B3_PROCESS_CLIENT_COMMANDS_TICK);
}
void PhysicsServerCommandProcessor::reportNotifications()
{
m_data->m_pluginManager.reportNotifications();
}
void PhysicsServerCommandProcessor::tickPlugins(btScalar timeStep, bool isPreTick)
{
b3PluginManagerTickMode tickMode = isPreTick ? B3_PRE_TICK_MODE : B3_POST_TICK_MODE;
m_data->m_pluginManager.tickPlugins(timeStep, tickMode);
if (!isPreTick)
{
//clear events after each postTick, so we don't receive events multiple ticks
m_data->m_pluginManager.clearEvents();
}
}
void PhysicsServerCommandProcessor::logObjectStates(btScalar timeStep)
{
for (int i = 0; i < m_data->m_stateLoggers.size(); i++)
{
m_data->m_stateLoggers[i]->logState(timeStep);
}
}
struct ProgrammaticUrdfInterface : public URDFImporterInterface
{
int m_bodyUniqueId;
const b3CreateMultiBodyArgs& m_createBodyArgs;
mutable b3AlignedObjectArray<btCollisionShape*> m_allocatedCollisionShapes;
PhysicsServerCommandProcessorInternalData* m_data;
int m_flags;
ProgrammaticUrdfInterface(const b3CreateMultiBodyArgs& bodyArgs, PhysicsServerCommandProcessorInternalData* data, int flags)
: m_bodyUniqueId(-1),
m_createBodyArgs(bodyArgs),
m_data(data),
m_flags(flags)
{
}
virtual ~ProgrammaticUrdfInterface()
{
}
virtual bool loadURDF(const char* fileName, bool forceFixedBase = false)
{
b3Assert(0);
return false;
}
virtual const char* getPathPrefix()
{
return "";
}
///return >=0 for the root link index, -1 if there is no root link
virtual int getRootLinkIndex() const
{
return m_createBodyArgs.m_baseLinkIndex;
}
///pure virtual interfaces, precondition is a valid linkIndex (you can assert/terminate if the linkIndex is out of range)
virtual std::string getLinkName(int linkIndex) const
{
std::string linkName = "link";
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", linkIndex);
linkName = linkName + numstr;
return linkName;
}
//various derived class in internal source code break with new pure virtual methods, so provide some default implementation
virtual std::string getBodyName() const
{
return m_createBodyArgs.m_bodyName;
}
/// optional method to provide the link color. return true if the color is available and copied into colorRGBA, return false otherwise
virtual bool getLinkColor(int linkIndex, btVector4& colorRGBA) const
{
b3Assert(0);
return false;
}
mutable btHashMap<btHashInt, UrdfMaterialColor> m_linkColors;
virtual bool getLinkColor2(int linkIndex, struct UrdfMaterialColor& matCol) const
{
if (m_flags & URDF_USE_MATERIAL_COLORS_FROM_MTL)
{
const UrdfMaterialColor* matColPtr = m_linkColors[linkIndex];
if (matColPtr)
{
matCol = *matColPtr;
if ((m_flags & CUF_USE_MATERIAL_TRANSPARANCY_FROM_MTL) == 0)
{
matCol.m_rgbaColor[3] = 1;
}
return true;
}
}
else
{
if (m_createBodyArgs.m_linkVisualShapeUniqueIds[linkIndex] >= 0)
{
const InternalVisualShapeHandle* visHandle = m_data->m_userVisualShapeHandles.getHandle(m_createBodyArgs.m_linkVisualShapeUniqueIds[linkIndex]);
if (visHandle)
{
for (int i = 0; i < visHandle->m_visualShapes.size(); i++)
{
if (visHandle->m_visualShapes[i].m_geometry.m_hasLocalMaterial)
{
matCol = visHandle->m_visualShapes[i].m_geometry.m_localMaterial.m_matColor;
return true;
}
}
}
}
}
return false;
}
virtual int getCollisionGroupAndMask(int linkIndex, int& colGroup, int& colMask) const
{
return 0;
}
///this API will likely change, don't override it!
virtual bool getLinkContactInfo(int linkIndex, URDFLinkContactInfo& contactInfo) const
{
return false;
}
virtual bool getLinkAudioSource(int linkIndex, SDFAudioSource& audioSource) const
{
b3Assert(0);
return false;
}
virtual std::string getJointName(int linkIndex) const
{
std::string jointName = "joint";
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", linkIndex);
jointName = jointName + numstr;
return jointName;
}
//fill mass and inertial data. If inertial data is missing, please initialize mass, inertia to sensitive values, and inertialFrame to identity.
virtual void getMassAndInertia(int urdfLinkIndex, btScalar& mass, btVector3& localInertiaDiagonal, btTransform& inertialFrame) const
{
if (urdfLinkIndex >= 0 && urdfLinkIndex < m_createBodyArgs.m_numLinks)
{
mass = m_createBodyArgs.m_linkMasses[urdfLinkIndex];
localInertiaDiagonal.setValue(
m_createBodyArgs.m_linkInertias[urdfLinkIndex * 3 + 0],
m_createBodyArgs.m_linkInertias[urdfLinkIndex * 3 + 1],
m_createBodyArgs.m_linkInertias[urdfLinkIndex * 3 + 2]);
inertialFrame.setOrigin(btVector3(
m_createBodyArgs.m_linkInertialFramePositions[urdfLinkIndex * 3 + 0],
m_createBodyArgs.m_linkInertialFramePositions[urdfLinkIndex * 3 + 1],
m_createBodyArgs.m_linkInertialFramePositions[urdfLinkIndex * 3 + 2]));
inertialFrame.setRotation(btQuaternion(
m_createBodyArgs.m_linkInertialFrameOrientations[urdfLinkIndex * 4 + 0],
m_createBodyArgs.m_linkInertialFrameOrientations[urdfLinkIndex * 4 + 1],
m_createBodyArgs.m_linkInertialFrameOrientations[urdfLinkIndex * 4 + 2],
m_createBodyArgs.m_linkInertialFrameOrientations[urdfLinkIndex * 4 + 3]));
}
else
{
mass = 0;
localInertiaDiagonal.setValue(0, 0, 0);
inertialFrame.setIdentity();
}
}
///fill an array of child link indices for this link, btAlignedObjectArray behaves like a std::vector so just use push_back and resize(0) if needed
virtual void getLinkChildIndices(int urdfLinkIndex, btAlignedObjectArray<int>& childLinkIndices) const
{
for (int i = 0; i < m_createBodyArgs.m_numLinks; i++)
{
if (m_createBodyArgs.m_linkParentIndices[i] == urdfLinkIndex)
{
childLinkIndices.push_back(i);
}
}
}
virtual bool getJointInfo(int urdfLinkIndex, btTransform& parent2joint, btTransform& linkTransformInWorld, btVector3& jointAxisInJointSpace, int& jointType, btScalar& jointLowerLimit, btScalar& jointUpperLimit, btScalar& jointDamping, btScalar& jointFriction) const
{
return false;
};
virtual bool getJointInfo2(int urdfLinkIndex, btTransform& parent2joint, btTransform& linkTransformInWorld, btVector3& jointAxisInJointSpace, int& jointType, btScalar& jointLowerLimit, btScalar& jointUpperLimit, btScalar& jointDamping, btScalar& jointFriction, btScalar& jointMaxForce, btScalar& jointMaxVelocity) const
{
bool isValid = false;
int jointTypeOrg = m_createBodyArgs.m_linkJointTypes[urdfLinkIndex];
switch (jointTypeOrg)
{
case eRevoluteType:
{
isValid = true;
jointType = URDFRevoluteJoint;
break;
}
case ePrismaticType:
{
isValid = true;
jointType = URDFPrismaticJoint;
break;
}
case eFixedType:
{
isValid = true;
jointType = URDFFixedJoint;
break;
}
case eSphericalType:
{
isValid = true;
jointType = URDFSphericalJoint;
break;
}
//case ePlanarType:
//case eFixedType:
//case ePoint2PointType:
//case eGearType:
default:
{
}
};
if (isValid)
{
//backwards compatibility for custom file importers
jointMaxForce = 0;
jointMaxVelocity = 0;
jointFriction = 0;
jointDamping = 0;
jointLowerLimit = 1;
jointUpperLimit = -1;
parent2joint.setOrigin(btVector3(
m_createBodyArgs.m_linkPositions[urdfLinkIndex * 3 + 0],
m_createBodyArgs.m_linkPositions[urdfLinkIndex * 3 + 1],
m_createBodyArgs.m_linkPositions[urdfLinkIndex * 3 + 2]));
parent2joint.setRotation(btQuaternion(
m_createBodyArgs.m_linkOrientations[urdfLinkIndex * 4 + 0],
m_createBodyArgs.m_linkOrientations[urdfLinkIndex * 4 + 1],
m_createBodyArgs.m_linkOrientations[urdfLinkIndex * 4 + 2],
m_createBodyArgs.m_linkOrientations[urdfLinkIndex * 4 + 3]));
linkTransformInWorld.setIdentity();
jointAxisInJointSpace.setValue(
m_createBodyArgs.m_linkJointAxis[3 * urdfLinkIndex + 0],
m_createBodyArgs.m_linkJointAxis[3 * urdfLinkIndex + 1],
m_createBodyArgs.m_linkJointAxis[3 * urdfLinkIndex + 2]);
}
return isValid;
};
virtual bool getRootTransformInWorld(btTransform& rootTransformInWorld) const
{
int baseLinkIndex = m_createBodyArgs.m_baseLinkIndex;
rootTransformInWorld.setOrigin(btVector3(
m_createBodyArgs.m_linkPositions[baseLinkIndex * 3 + 0],
m_createBodyArgs.m_linkPositions[baseLinkIndex * 3 + 1],
m_createBodyArgs.m_linkPositions[baseLinkIndex * 3 + 2]));
rootTransformInWorld.setRotation(btQuaternion(
m_createBodyArgs.m_linkOrientations[baseLinkIndex * 4 + 0],
m_createBodyArgs.m_linkOrientations[baseLinkIndex * 4 + 1],
m_createBodyArgs.m_linkOrientations[baseLinkIndex * 4 + 2],
m_createBodyArgs.m_linkOrientations[baseLinkIndex * 4 + 3]));
return true;
}
virtual void setRootTransformInWorld(const btTransform& rootTransformInWorld)
{
b3Assert(0);
}
virtual int convertLinkVisualShapes(int linkIndex, const char* pathPrefix, const btTransform& localInertiaFrame) const
{
int graphicsIndex = -1;
double globalScaling = 1.f; //todo!
int flags = 0;
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
BulletURDFImporter u2b(m_data->m_guiHelper, m_data->m_pluginManager.getRenderInterface(), fileIO, globalScaling, flags);
u2b.setEnableTinyRenderer(m_data->m_enableTinyRenderer);
btAlignedObjectArray<GLInstanceVertex> vertices;
btAlignedObjectArray<int> indices;
btTransform startTrans;
startTrans.setIdentity();
btAlignedObjectArray<BulletURDFTexture> textures;
if (m_createBodyArgs.m_linkVisualShapeUniqueIds[linkIndex] >= 0)
{
InternalVisualShapeHandle* visHandle = m_data->m_userVisualShapeHandles.getHandle(m_createBodyArgs.m_linkVisualShapeUniqueIds[linkIndex]);
if (visHandle)
{
if (visHandle->m_OpenGLGraphicsIndex >= 0)
{
//instancing. assume the inertial frame is identical
graphicsIndex = visHandle->m_OpenGLGraphicsIndex;
}
else
{
for (int v = 0; v < visHandle->m_visualShapes.size(); v++)
{
b3ImportMeshData meshData;
u2b.convertURDFToVisualShapeInternal(&visHandle->m_visualShapes[v], pathPrefix, localInertiaFrame.inverse() * visHandle->m_visualShapes[v].m_linkLocalFrame, vertices, indices, textures, meshData);
if ((meshData.m_flags & B3_IMPORT_MESH_HAS_RGBA_COLOR) &&
(meshData.m_flags & B3_IMPORT_MESH_HAS_SPECULAR_COLOR))
{
UrdfMaterialColor matCol;
matCol.m_rgbaColor.setValue(meshData.m_rgbaColor[0],
meshData.m_rgbaColor[1],
meshData.m_rgbaColor[2],
meshData.m_rgbaColor[3]);
matCol.m_specularColor.setValue(meshData.m_specularColor[0],
meshData.m_specularColor[1],
meshData.m_specularColor[2]);
m_linkColors.insert(linkIndex, matCol);
}
}
if (vertices.size() && indices.size())
{
if (1)
{
int textureIndex = -1;
if (textures.size())
{
textureIndex = m_data->m_guiHelper->registerTexture(textures[0].textureData1, textures[0].m_width, textures[0].m_height);
}
{
B3_PROFILE("registerGraphicsShape");
graphicsIndex = m_data->m_guiHelper->registerGraphicsShape(&vertices[0].xyzw[0], vertices.size(), &indices[0], indices.size(), B3_GL_TRIANGLES, textureIndex);
visHandle->m_OpenGLGraphicsIndex = graphicsIndex;
}
}
}
}
}
}
return graphicsIndex;
}
virtual void convertLinkVisualShapes2(int linkIndex, int urdfIndex, const char* pathPrefix, const btTransform& localInertiaFrame, class btCollisionObject* colObj, int bodyUniqueId) const
{
//if there is a visual, use it, otherwise convert collision shape back into UrdfCollision...
UrdfModel model; // = m_data->m_urdfParser.getModel();
UrdfLink link;
if (m_createBodyArgs.m_linkVisualShapeUniqueIds[urdfIndex] >= 0)
{
const InternalVisualShapeHandle* visHandle = m_data->m_userVisualShapeHandles.getHandle(m_createBodyArgs.m_linkVisualShapeUniqueIds[urdfIndex]);
if (visHandle)
{
for (int i = 0; i < visHandle->m_visualShapes.size(); i++)
{
link.m_visualArray.push_back(visHandle->m_visualShapes[i]);
}
}
}
if (link.m_visualArray.size() == 0)
{
int colShapeUniqueId = m_createBodyArgs.m_linkCollisionShapeUniqueIds[urdfIndex];
if (colShapeUniqueId >= 0)
{
InternalCollisionShapeHandle* handle = m_data->m_userCollisionShapeHandles.getHandle(colShapeUniqueId);
if (handle)
{
for (int i = 0; i < handle->m_urdfCollisionObjects.size(); i++)
{
link.m_collisionArray.push_back(handle->m_urdfCollisionObjects[i]);
}
}
}
}
//UrdfVisual vis;
//link.m_visualArray.push_back(vis);
//UrdfLink*const* linkPtr = model.m_links.getAtIndex(urdfIndex);
if (m_data->m_pluginManager.getRenderInterface())
{
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
int visualShapeUniqueid = m_data->m_pluginManager.getRenderInterface()->convertVisualShapes(linkIndex, pathPrefix, localInertiaFrame, &link, &model, colObj->getBroadphaseHandle()->getUid(), bodyUniqueId, fileIO);
colObj->setUserIndex3(visualShapeUniqueid);
}
}
virtual void setBodyUniqueId(int bodyId)
{
m_bodyUniqueId = bodyId;
}
virtual int getBodyUniqueId() const
{
return m_bodyUniqueId;
}
//default implementation for backward compatibility
virtual class btCompoundShape* convertLinkCollisionShapes(int linkIndex, const char* pathPrefix, const btTransform& localInertiaFrame) const
{
btCompoundShape* compound = new btCompoundShape();
int colShapeUniqueId = m_createBodyArgs.m_linkCollisionShapeUniqueIds[linkIndex];
if (colShapeUniqueId >= 0)
{
InternalCollisionShapeHandle* handle = m_data->m_userCollisionShapeHandles.getHandle(colShapeUniqueId);
if (handle && handle->m_collisionShape)
{
handle->m_used++;
if (handle->m_collisionShape->getShapeType() == COMPOUND_SHAPE_PROXYTYPE)
{
btCompoundShape* childCompound = (btCompoundShape*)handle->m_collisionShape;
for (int c = 0; c < childCompound->getNumChildShapes(); c++)
{
btTransform childTrans = childCompound->getChildTransform(c);
btCollisionShape* childShape = childCompound->getChildShape(c);
btTransform tr = localInertiaFrame.inverse() * childTrans;
compound->addChildShape(tr, childShape);
}
}
else
{
btTransform childTrans;
childTrans.setIdentity();
compound->addChildShape(localInertiaFrame.inverse() * childTrans, handle->m_collisionShape);
}
}
}
m_allocatedCollisionShapes.push_back(compound);
return compound;
}
virtual int getNumAllocatedCollisionShapes() const
{
return m_allocatedCollisionShapes.size();
}
virtual class btCollisionShape* getAllocatedCollisionShape(int index)
{
return m_allocatedCollisionShapes[index];
}
virtual int getNumModels() const
{
return 1;
}
virtual void activateModel(int /*modelIndex*/)
{
}
};
btDeformableMultiBodyDynamicsWorld* PhysicsServerCommandProcessor::getDeformableWorld()
{
btDeformableMultiBodyDynamicsWorld* world = 0;
if (m_data->m_dynamicsWorld && m_data->m_dynamicsWorld->getWorldType()== BT_DEFORMABLE_MULTIBODY_DYNAMICS_WORLD)
{
world = (btDeformableMultiBodyDynamicsWorld*) m_data->m_dynamicsWorld;
}
return world;
}
btSoftMultiBodyDynamicsWorld* PhysicsServerCommandProcessor::getSoftWorld()
{
btSoftMultiBodyDynamicsWorld* world = 0;
if (m_data->m_dynamicsWorld && m_data->m_dynamicsWorld->getWorldType()== BT_SOFT_MULTIBODY_DYNAMICS_WORLD)
{
world = (btSoftMultiBodyDynamicsWorld*) m_data->m_dynamicsWorld;
}
return world;
}
void PhysicsServerCommandProcessor::createEmptyDynamicsWorld(int flags)
{
m_data->m_constraintSolverType = eConstraintSolverLCP_SI;
///collision configuration contains default setup for memory, collision setup
//m_collisionConfiguration->setConvexConvexMultipointIterations();
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
m_data->m_collisionConfiguration = new btSoftBodyRigidBodyCollisionConfiguration();
#else
m_data->m_collisionConfiguration = new btDefaultCollisionConfiguration();
#endif
///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
m_data->m_dispatcher = new btCollisionDispatcher(m_data->m_collisionConfiguration);
m_data->m_broadphaseCollisionFilterCallback = new MyOverlapFilterCallback(&m_data->m_pluginManager);
m_data->m_broadphaseCollisionFilterCallback->m_filterMode = B3_FILTER_GROUPAMASKB_OR_GROUPBMASKA;
m_data->m_pairCache = new btHashedOverlappingPairCache();
m_data->m_pairCache->setOverlapFilterCallback(m_data->m_broadphaseCollisionFilterCallback);
//int maxProxies = 32768;
if (flags&RESET_USE_SIMPLE_BROADPHASE)
{
m_data->m_broadphase = new btSimpleBroadphase(65536, m_data->m_pairCache);
} else
{
btDbvtBroadphase* bv = new btDbvtBroadphase(m_data->m_pairCache);
bv->setVelocityPrediction(0);
m_data->m_broadphase = bv;
}
if (flags & RESET_USE_DEFORMABLE_WORLD)
{
#ifndef SKIP_DEFORMABLE_BODY
m_data->m_deformablebodySolver = new btDeformableBodySolver();
btDeformableMultiBodyConstraintSolver* solver = new btDeformableMultiBodyConstraintSolver;
m_data->m_solver = solver;
solver->setDeformableSolver(m_data->m_deformablebodySolver);
m_data->m_dynamicsWorld = new btDeformableMultiBodyDynamicsWorld(m_data->m_dispatcher, m_data->m_broadphase, solver, m_data->m_collisionConfiguration, m_data->m_deformablebodySolver);
#endif
}
if ((0==m_data->m_dynamicsWorld) && (0==(flags&RESET_USE_DISCRETE_DYNAMICS_WORLD)))
{
m_data->m_solver = new btMultiBodyConstraintSolver;
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
m_data->m_dynamicsWorld = new btSoftMultiBodyDynamicsWorld(m_data->m_dispatcher, m_data->m_broadphase, m_data->m_solver, m_data->m_collisionConfiguration);
#else
m_data->m_dynamicsWorld = new btMultiBodyDynamicsWorld(m_data->m_dispatcher, m_data->m_broadphase, m_data->m_solver, m_data->m_collisionConfiguration);
#endif
}
if (0==m_data->m_dynamicsWorld)
{
m_data->m_solver = new btMultiBodyConstraintSolver;
m_data->m_dynamicsWorld = new btMultiBodyDynamicsWorld(m_data->m_dispatcher, m_data->m_broadphase, m_data->m_solver, m_data->m_collisionConfiguration);
}
//Workaround: in a VR application, where we avoid synchronizing between GFX/Physics threads, we don't want to resize this array, so pre-allocate it
m_data->m_dynamicsWorld->getCollisionObjectArray().reserve(128 * 1024);
m_data->m_remoteDebugDrawer = new SharedMemoryDebugDrawer();
m_data->m_dynamicsWorld->setGravity(btVector3(0, 0, 0));
m_data->m_dynamicsWorld->getSolverInfo().m_erp2 = 0.08;
m_data->m_dynamicsWorld->getSolverInfo().m_frictionERP = 0.2; //need to check if there are artifacts with frictionERP
m_data->m_dynamicsWorld->getSolverInfo().m_linearSlop = 0.00001;
m_data->m_dynamicsWorld->getSolverInfo().m_numIterations = 50;
m_data->m_dynamicsWorld->getSolverInfo().m_minimumSolverBatchSize = 0;
m_data->m_dynamicsWorld->getSolverInfo().m_warmstartingFactor = 0.1;
gDbvtMargin = btScalar(0);
m_data->m_dynamicsWorld->getSolverInfo().m_leastSquaresResidualThreshold = 1e-7;
if (m_data->m_guiHelper)
{
m_data->m_guiHelper->createPhysicsDebugDrawer(m_data->m_dynamicsWorld);
}
bool isPreTick = false;
m_data->m_dynamicsWorld->setInternalTickCallback(logCallback, this, isPreTick);
isPreTick = true;
m_data->m_dynamicsWorld->setInternalTickCallback(preTickCallback, this, isPreTick);
gContactAddedCallback = MyContactAddedCallback;
#ifdef B3_ENABLE_TINY_AUDIO
m_data->m_soundEngine.init(16, true);
//we don't use those callbacks (yet), experimental
// gContactDestroyedCallback = MyContactDestroyedCallback;
// gContactProcessedCallback = MyContactProcessedCallback;
// gContactStartedCallback = MyContactStartedCallback;
// gContactEndedCallback = MyContactEndedCallback;
#endif
}
void PhysicsServerCommandProcessor::deleteStateLoggers()
{
for (int i = 0; i < m_data->m_stateLoggers.size(); i++)
{
m_data->m_stateLoggers[i]->stop();
delete m_data->m_stateLoggers[i];
}
m_data->m_stateLoggers.clear();
}
void PhysicsServerCommandProcessor::deleteCachedInverseKinematicsBodies()
{
for (int i = 0; i < m_data->m_inverseKinematicsHelpers.size(); i++)
{
IKTrajectoryHelper** ikHelperPtr = m_data->m_inverseKinematicsHelpers.getAtIndex(i);
if (ikHelperPtr)
{
IKTrajectoryHelper* ikHelper = *ikHelperPtr;
delete ikHelper;
}
}
m_data->m_inverseKinematicsHelpers.clear();
}
void PhysicsServerCommandProcessor::deleteCachedInverseDynamicsBodies()
{
for (int i = 0; i < m_data->m_inverseDynamicsBodies.size(); i++)
{
btInverseDynamics::MultiBodyTree** treePtrPtr = m_data->m_inverseDynamicsBodies.getAtIndex(i);
if (treePtrPtr)
{
btInverseDynamics::MultiBodyTree* tree = *treePtrPtr;
delete tree;
}
}
m_data->m_inverseDynamicsBodies.clear();
}
void PhysicsServerCommandProcessor::deleteDynamicsWorld()
{
#ifdef B3_ENABLE_TINY_AUDIO
m_data->m_soundEngine.exit();
//gContactDestroyedCallback = 0;
//gContactProcessedCallback = 0;
//gContactStartedCallback = 0;
//gContactEndedCallback = 0;
#endif
deleteCachedInverseDynamicsBodies();
deleteCachedInverseKinematicsBodies();
deleteStateLoggers();
m_data->m_userConstraints.clear();
m_data->m_saveWorldBodyData.clear();
for (int i = 0; i < m_data->m_multiBodyJointFeedbacks.size(); i++)
{
delete m_data->m_multiBodyJointFeedbacks[i];
}
m_data->m_multiBodyJointFeedbacks.clear();
for (int i = 0; i < m_data->m_worldImporters.size(); i++)
{
m_data->m_worldImporters[i]->deleteAllData();
delete m_data->m_worldImporters[i];
}
m_data->m_worldImporters.clear();
#ifdef ENABLE_LINK_MAPPER
for (int i = 0; i < m_data->m_urdfLinkNameMapper.size(); i++)
{
delete m_data->m_urdfLinkNameMapper[i];
}
m_data->m_urdfLinkNameMapper.clear();
#endif //ENABLE_LINK_MAPPER
for (int i = 0; i < m_data->m_strings.size(); i++)
{
delete m_data->m_strings[i];
}
m_data->m_strings.clear();
btAlignedObjectArray<btTypedConstraint*> constraints;
btAlignedObjectArray<btMultiBodyConstraint*> mbconstraints;
if (m_data->m_dynamicsWorld)
{
int i;
for (i = m_data->m_dynamicsWorld->getNumConstraints() - 1; i >= 0; i--)
{
btTypedConstraint* constraint = m_data->m_dynamicsWorld->getConstraint(i);
constraints.push_back(constraint);
m_data->m_dynamicsWorld->removeConstraint(constraint);
}
for (i = m_data->m_dynamicsWorld->getNumMultiBodyConstraints() - 1; i >= 0; i--)
{
btMultiBodyConstraint* mbconstraint = m_data->m_dynamicsWorld->getMultiBodyConstraint(i);
mbconstraints.push_back(mbconstraint);
m_data->m_dynamicsWorld->removeMultiBodyConstraint(mbconstraint);
}
for (i = m_data->m_dynamicsWorld->getNumCollisionObjects() - 1; i >= 0; i--)
{
btCollisionObject* obj = m_data->m_dynamicsWorld->getCollisionObjectArray()[i];
btRigidBody* body = btRigidBody::upcast(obj);
if (body && body->getMotionState())
{
delete body->getMotionState();
}
m_data->m_dynamicsWorld->removeCollisionObject(obj);
delete obj;
}
for (i = m_data->m_dynamicsWorld->getNumMultibodies() - 1; i >= 0; i--)
{
btMultiBody* mb = m_data->m_dynamicsWorld->getMultiBody(i);
m_data->m_dynamicsWorld->removeMultiBody(mb);
delete mb;
}
#ifndef SKIP_DEFORMABLE_BODY
for (int j = 0; j < m_data->m_lf.size(); j++)
{
btDeformableLagrangianForce* force = m_data->m_lf[j];
delete force;
}
m_data->m_lf.clear();
#endif
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
{
btSoftMultiBodyDynamicsWorld* softWorld = getSoftWorld();
if (softWorld)
{
for (i =softWorld->getSoftBodyArray().size() - 1; i >= 0; i--)
{
btSoftBody* sb =softWorld->getSoftBodyArray()[i];
softWorld->removeSoftBody(sb);
delete sb;
}
}
}
#endif//SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
#ifndef SKIP_DEFORMABLE_BODY
{
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
for (i =deformWorld->getSoftBodyArray().size() - 1; i >= 0; i--)
{
btSoftBody* sb =deformWorld->getSoftBodyArray()[i];
deformWorld->removeSoftBody(sb);
delete sb;
}
}
}
#endif
}
for (int i = 0; i < constraints.size(); i++)
{
delete constraints[i];
}
constraints.clear();
for (int i = 0; i < mbconstraints.size(); i++)
{
delete mbconstraints[i];
}
mbconstraints.clear();
//delete collision shapes
for (int j = 0; j < m_data->m_collisionShapes.size(); j++)
{
btCollisionShape* shape = m_data->m_collisionShapes[j];
//check for internal edge utility, delete memory
if (shape->getShapeType() == TRIANGLE_MESH_SHAPE_PROXYTYPE)
{
btBvhTriangleMeshShape* trimesh = (btBvhTriangleMeshShape*)shape;
if (trimesh->getTriangleInfoMap())
{
delete trimesh->getTriangleInfoMap();
}
}
if (shape->getShapeType() == TERRAIN_SHAPE_PROXYTYPE)
{
btHeightfieldTerrainShape* terrain = (btHeightfieldTerrainShape*)shape;
if (terrain->getTriangleInfoMap())
{
delete terrain->getTriangleInfoMap();
}
}
delete shape;
}
for (int j = 0; j < m_data->m_heightfieldDatas.size(); j++)
{
delete[] m_data->m_heightfieldDatas[j];
}
for (int j = 0; j < m_data->m_meshInterfaces.size(); j++)
{
delete m_data->m_meshInterfaces[j];
}
if (m_data->m_guiHelper)
{
for (int j = 0; j < m_data->m_allocatedTextures.size(); j++)
{
int texId = m_data->m_allocatedTextures[j];
m_data->m_guiHelper->removeTexture(texId);
}
}
m_data->m_heightfieldDatas.clear();
m_data->m_allocatedTextures.clear();
m_data->m_meshInterfaces.clear();
m_data->m_collisionShapes.clear();
m_data->m_bulletCollisionShape2UrdfCollision.clear();
m_data->m_graphicsIndexToSegmentationMask.clear();
delete m_data->m_dynamicsWorld;
m_data->m_dynamicsWorld = 0;
delete m_data->m_remoteDebugDrawer;
m_data->m_remoteDebugDrawer = 0;
#if !defined(SKIP_DEFORMABLE_BODY) && !defined(SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD)
delete m_data->m_deformablebodySolver;
m_data->m_deformablebodySolver = 0;
#endif
delete m_data->m_solver;
m_data->m_solver = 0;
delete m_data->m_broadphase;
m_data->m_broadphase = 0;
delete m_data->m_pairCache;
m_data->m_pairCache = 0;
delete m_data->m_broadphaseCollisionFilterCallback;
m_data->m_broadphaseCollisionFilterCallback = 0;
delete m_data->m_dispatcher;
m_data->m_dispatcher = 0;
delete m_data->m_collisionConfiguration;
m_data->m_collisionConfiguration = 0;
m_data->m_userConstraintUIDGenerator = 1;
#ifdef STATIC_LINK_SPD_PLUGIN
for (int i = 0; i < m_data->m_rbdModels.size(); i++)
{
delete *(m_data->m_rbdModels.getAtIndex(i));
}
m_data->m_rbdModels.clear();
#endif //STATIC_LINK_SPD_PLUGIN
}
bool PhysicsServerCommandProcessor::supportsJointMotor(btMultiBody* mb, int mbLinkIndex)
{
bool canHaveMotor = (mb->getLink(mbLinkIndex).m_jointType == btMultibodyLink::eRevolute || mb->getLink(mbLinkIndex).m_jointType == btMultibodyLink::ePrismatic);
return canHaveMotor;
}
//for testing, create joint motors for revolute and prismatic joints
void PhysicsServerCommandProcessor::createJointMotors(btMultiBody* mb)
{
int numLinks = mb->getNumLinks();
for (int i = 0; i < numLinks; i++)
{
int mbLinkIndex = i;
float maxMotorImpulse = 1.f;
if (supportsJointMotor(mb, mbLinkIndex))
{
int dof = 0;
btScalar desiredVelocity = 0.f;
btMultiBodyJointMotor* motor = new btMultiBodyJointMotor(mb, mbLinkIndex, dof, desiredVelocity, maxMotorImpulse);
motor->setPositionTarget(0, 0);
motor->setVelocityTarget(0, 1);
//motor->setRhsClamp(gRhsClamp);
//motor->setMaxAppliedImpulse(0);
mb->getLink(mbLinkIndex).m_userPtr = motor;
m_data->m_dynamicsWorld->addMultiBodyConstraint(motor);
motor->finalizeMultiDof();
}
if (mb->getLink(mbLinkIndex).m_jointType == btMultibodyLink::eSpherical)
{
btMultiBodySphericalJointMotor* motor = new btMultiBodySphericalJointMotor(mb, mbLinkIndex, 1000 * maxMotorImpulse);
mb->getLink(mbLinkIndex).m_userPtr = motor;
m_data->m_dynamicsWorld->addMultiBodyConstraint(motor);
motor->finalizeMultiDof();
}
}
}
int PhysicsServerCommandProcessor::addUserData(int bodyUniqueId, int linkIndex, int visualShapeIndex, const char* key, const char* valueBytes, int valueLength, int valueType) {
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (!body)
{
return -1;
}
SharedMemoryUserDataHashKey userDataIdentifier(key, bodyUniqueId, linkIndex, visualShapeIndex);
int* userDataHandlePtr = m_data->m_userDataHandleLookup.find(userDataIdentifier);
int userDataHandle = userDataHandlePtr ? *userDataHandlePtr : m_data->m_userDataHandles.allocHandle();
SharedMemoryUserData* userData = m_data->m_userDataHandles.getHandle(userDataHandle);
if (!userData)
{
return -1;
}
if (!userDataHandlePtr)
{
userData->m_key = key;
userData->m_bodyUniqueId = bodyUniqueId;
userData->m_linkIndex = linkIndex;
userData->m_visualShapeIndex = visualShapeIndex;
m_data->m_userDataHandleLookup.insert(userDataIdentifier, userDataHandle);
body->m_userDataHandles.push_back(userDataHandle);
}
userData->replaceValue(valueBytes, valueLength, valueType);
return userDataHandle;
}
void PhysicsServerCommandProcessor::addUserData(const btHashMap<btHashString, std::string>& user_data_entries, int bodyUniqueId, int linkIndex, int visualShapeIndex) {
for (int i = 0; i < user_data_entries.size(); ++i) {
const std::string key = user_data_entries.getKeyAtIndex(i).m_string1;
const std::string* value = user_data_entries.getAtIndex(i);
if (value) {
addUserData(bodyUniqueId, linkIndex, visualShapeIndex, key.c_str(), value->c_str(),
value->size()+1, USER_DATA_VALUE_TYPE_STRING);
}
}
}
bool PhysicsServerCommandProcessor::processImportedObjects(const char* fileName, char* bufferServerToClient, int bufferSizeInBytes, bool useMultiBody, int flags, URDFImporterInterface& u2b)
{
bool loadOk = true;
btTransform rootTrans;
rootTrans.setIdentity();
if (m_data->m_verboseOutput)
{
b3Printf("loaded %s OK!", fileName);
}
SaveWorldObjectData sd;
sd.m_fileName = fileName;
for (int m = 0; m < u2b.getNumModels(); m++)
{
u2b.activateModel(m);
btMultiBody* mb = 0;
btRigidBody* rb = 0;
//get a body index
int bodyUniqueId = m_data->m_bodyHandles.allocHandle();
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(bodyUniqueId);
sd.m_bodyUniqueIds.push_back(bodyUniqueId);
u2b.setBodyUniqueId(bodyUniqueId);
{
btScalar mass = 0;
bodyHandle->m_rootLocalInertialFrame.setIdentity();
bodyHandle->m_bodyName = u2b.getBodyName();
btVector3 localInertiaDiagonal(0, 0, 0);
int urdfLinkIndex = u2b.getRootLinkIndex();
u2b.getMassAndInertia2(urdfLinkIndex, mass, localInertiaDiagonal, bodyHandle->m_rootLocalInertialFrame, flags);
}
//todo: move these internal API called inside the 'ConvertURDF2Bullet' call, hidden from the user
//int rootLinkIndex = u2b.getRootLinkIndex();
//b3Printf("urdf root link index = %d\n",rootLinkIndex);
MyMultiBodyCreator creation(m_data->m_guiHelper);
u2b.getRootTransformInWorld(rootTrans);
//CUF_RESERVED is a temporary flag, for backward compatibility purposes
flags |= CUF_RESERVED;
if (flags & CUF_ENABLE_CACHED_GRAPHICS_SHAPES)
{
{
UrdfVisualShapeCache* tmpPtr = m_data->m_cachedVUrdfisualShapes[fileName];
if (tmpPtr == 0)
{
m_data->m_cachedVUrdfisualShapes.insert(fileName, UrdfVisualShapeCache());
}
}
UrdfVisualShapeCache* cachedVisualShapesPtr = m_data->m_cachedVUrdfisualShapes[fileName];
ConvertURDF2Bullet(u2b, creation, rootTrans, m_data->m_dynamicsWorld, useMultiBody, u2b.getPathPrefix(), flags, cachedVisualShapesPtr);
}
else
{
ConvertURDF2Bullet(u2b, creation, rootTrans, m_data->m_dynamicsWorld, useMultiBody, u2b.getPathPrefix(), flags);
}
mb = creation.getBulletMultiBody();
rb = creation.getRigidBody();
if (rb)
rb->setUserIndex2(bodyUniqueId);
if (mb)
mb->setUserIndex2(bodyUniqueId);
if (mb)
{
bodyHandle->m_multiBody = mb;
m_data->m_sdfRecentLoadedBodies.push_back(bodyUniqueId);
int segmentationMask = bodyUniqueId;
{
int graphicsIndex = -1;
if (mb->getBaseCollider())
{
graphicsIndex = mb->getBaseCollider()->getUserIndex();
}
if (graphicsIndex >= 0)
{
if (m_data->m_graphicsIndexToSegmentationMask.size() < (graphicsIndex + 1))
{
m_data->m_graphicsIndexToSegmentationMask.resize(graphicsIndex + 1);
}
m_data->m_graphicsIndexToSegmentationMask[graphicsIndex] = segmentationMask;
}
}
createJointMotors(mb);
#ifdef B3_ENABLE_TINY_AUDIO
{
SDFAudioSource audioSource;
int urdfRootLink = u2b.getRootLinkIndex(); //LinkIndex = creation.m_mb2urdfLink[-1];
if (u2b.getLinkAudioSource(urdfRootLink, audioSource))
{
int flags = mb->getBaseCollider()->getCollisionFlags();
mb->getBaseCollider()->setCollisionFlags(flags | btCollisionObject::CF_HAS_COLLISION_SOUND_TRIGGER);
audioSource.m_userIndex = m_data->m_soundEngine.loadWavFile(audioSource.m_uri.c_str());
if (audioSource.m_userIndex >= 0)
{
bodyHandle->m_audioSources.insert(-1, audioSource);
}
}
}
#endif
//disable serialization of the collision objects (they are too big, and the client likely doesn't need them);
bodyHandle->m_linkLocalInertialFrames.reserve(mb->getNumLinks());
for (int i = 0; i < mb->getNumLinks(); i++)
{
//disable serialization of the collision objects
int urdfLinkIndex = creation.m_mb2urdfLink[i];
btScalar mass;
btVector3 localInertiaDiagonal(0, 0, 0);
btTransform localInertialFrame;
u2b.getMassAndInertia2(urdfLinkIndex, mass, localInertiaDiagonal, localInertialFrame, flags);
bodyHandle->m_linkLocalInertialFrames.push_back(localInertialFrame);
std::string* linkName = new std::string(u2b.getLinkName(urdfLinkIndex).c_str());
m_data->m_strings.push_back(linkName);
mb->getLink(i).m_linkName = linkName->c_str();
{
int graphicsIndex = -1;
if (mb->getLinkCollider(i))
{
graphicsIndex = mb->getLinkCollider(i)->getUserIndex();
}
if (graphicsIndex >= 0)
{
int linkIndex = i;
if (m_data->m_graphicsIndexToSegmentationMask.size() < (graphicsIndex + 1))
{
m_data->m_graphicsIndexToSegmentationMask.resize(graphicsIndex + 1);
}
int segmentationMask = bodyUniqueId + ((linkIndex + 1) << 24);
m_data->m_graphicsIndexToSegmentationMask[graphicsIndex] = segmentationMask;
}
}
std::string* jointName = new std::string(u2b.getJointName(urdfLinkIndex).c_str());
m_data->m_strings.push_back(jointName);
mb->getLink(i).m_jointName = jointName->c_str();
#ifdef B3_ENABLE_TINY_AUDIO
{
SDFAudioSource audioSource;
int urdfLinkIndex = creation.m_mb2urdfLink[link];
if (u2b.getLinkAudioSource(urdfLinkIndex, audioSource))
{
int flags = mb->getLink(link).m_collider->getCollisionFlags();
mb->getLink(i).m_collider->setCollisionFlags(flags | btCollisionObject::CF_HAS_COLLISION_SOUND_TRIGGER);
audioSource.m_userIndex = m_data->m_soundEngine.loadWavFile(audioSource.m_uri.c_str());
if (audioSource.m_userIndex >= 0)
{
bodyHandle->m_audioSources.insert(link, audioSource);
}
}
}
#endif
}
std::string* baseName = new std::string(u2b.getLinkName(u2b.getRootLinkIndex()));
m_data->m_strings.push_back(baseName);
mb->setBaseName(baseName->c_str());
#if 0
btAlignedObjectArray<char> urdf;
mb->dumpUrdf(urdf);
FILE* f = fopen("e:/pybullet.urdf", "w");
if (f)
{
fwrite(&urdf[0], urdf.size(), 1, f);
fclose(f);
}
#endif
}
else
{
int segmentationMask = bodyUniqueId;
if (rb)
{
int graphicsIndex = -1;
{
graphicsIndex = rb->getUserIndex();
}
if (graphicsIndex >= 0)
{
if (m_data->m_graphicsIndexToSegmentationMask.size() < (graphicsIndex + 1))
{
m_data->m_graphicsIndexToSegmentationMask.resize(graphicsIndex + 1);
}
m_data->m_graphicsIndexToSegmentationMask[graphicsIndex] = segmentationMask;
}
}
//b3Warning("No multibody loaded from URDF. Could add btRigidBody+btTypedConstraint solution later.");
bodyHandle->m_rigidBody = rb;
rb->setUserIndex2(bodyUniqueId);
m_data->m_sdfRecentLoadedBodies.push_back(bodyUniqueId);
std::string* baseName = new std::string(u2b.getLinkName(u2b.getRootLinkIndex()));
m_data->m_strings.push_back(baseName);
bodyHandle->m_bodyName = *baseName;
int numJoints = creation.getNum6DofConstraints();
bodyHandle->m_rigidBodyJoints.reserve(numJoints);
bodyHandle->m_rigidBodyJointNames.reserve(numJoints);
bodyHandle->m_rigidBodyLinkNames.reserve(numJoints);
for (int i = 0; i < numJoints; i++)
{
int urdfLinkIndex = creation.m_mb2urdfLink[i];
btGeneric6DofSpring2Constraint* con = creation.get6DofConstraint(i);
std::string* linkName = new std::string(u2b.getLinkName(urdfLinkIndex).c_str());
m_data->m_strings.push_back(linkName);
std::string* jointName = new std::string(u2b.getJointName(urdfLinkIndex).c_str());
m_data->m_strings.push_back(jointName);
bodyHandle->m_rigidBodyJointNames.push_back(*jointName);
bodyHandle->m_rigidBodyLinkNames.push_back(*linkName);
bodyHandle->m_rigidBodyJoints.push_back(con);
}
}
{
if (m_data->m_pluginManager.getRenderInterface())
{
int currentOpenGLTextureIndex = 0;
int totalNumVisualShapes = m_data->m_pluginManager.getRenderInterface()->getNumVisualShapes(bodyUniqueId);
for (int shapeIndex = 0; shapeIndex < totalNumVisualShapes; shapeIndex++)
{
b3VisualShapeData tmpShape;
int success = m_data->m_pluginManager.getRenderInterface()->getVisualShapesData(bodyUniqueId, shapeIndex, &tmpShape);
if (success)
{
if (tmpShape.m_tinyRendererTextureId >= 0)
{
int openglTextureUniqueId = -1;
//find companion opengl texture unique id and create a 'textureUid'
if (currentOpenGLTextureIndex < u2b.getNumAllocatedTextures())
{
openglTextureUniqueId = u2b.getAllocatedTexture(currentOpenGLTextureIndex++);
}
//if (openglTextureUniqueId>=0)
{
int texHandle = m_data->m_textureHandles.allocHandle();
InternalTextureHandle* texH = m_data->m_textureHandles.getHandle(texHandle);
if (texH)
{
texH->m_tinyRendererTextureId = tmpShape.m_tinyRendererTextureId;
texH->m_openglTextureId = openglTextureUniqueId;
}
}
}
}
}
}
}
const UrdfModel* urdfModel = u2b.getUrdfModel();
if (urdfModel) {
addUserData(urdfModel->m_userData, bodyUniqueId);
for (int linkIndex = 0; linkIndex < urdfModel->m_links.size(); ++linkIndex) {
const UrdfLink* link = *urdfModel->m_links.getAtIndex(linkIndex);
addUserData(link->m_userData, bodyUniqueId, linkIndex - 1);
for (int visualShapeIndex = 0; visualShapeIndex < link->m_visualArray.size(); ++visualShapeIndex) {
addUserData(link->m_visualArray.at(visualShapeIndex).m_userData, bodyUniqueId, linkIndex - 1, visualShapeIndex);
}
}
}
b3Notification notification;
notification.m_notificationType = BODY_ADDED;
notification.m_bodyArgs.m_bodyUniqueId = bodyUniqueId;
m_data->m_pluginManager.addNotification(notification);
}
for (int i = 0; i < u2b.getNumAllocatedTextures(); i++)
{
int texId = u2b.getAllocatedTexture(i);
m_data->m_allocatedTextures.push_back(texId);
}
/*
int texHandle = m_data->m_textureHandles.allocHandle();
InternalTextureHandle* texH = m_data->m_textureHandles.getHandle(texHandle);
if(texH)
{
texH->m_tinyRendererTextureId = -1;
texH->m_openglTextureId = -1;
*/
for (int i = 0; i < u2b.getNumAllocatedMeshInterfaces(); i++)
{
m_data->m_meshInterfaces.push_back(u2b.getAllocatedMeshInterface(i));
}
for (int i = 0; i < u2b.getNumAllocatedCollisionShapes(); i++)
{
btCollisionShape* shape = u2b.getAllocatedCollisionShape(i);
m_data->m_collisionShapes.push_back(shape);
UrdfCollision urdfCollision;
if (u2b.getUrdfFromCollisionShape(shape, urdfCollision))
{
m_data->m_bulletCollisionShape2UrdfCollision.insert(shape, urdfCollision);
}
if (shape->getShapeType() == COMPOUND_SHAPE_PROXYTYPE)
{
btCompoundShape* compound = (btCompoundShape*)shape;
for (int c = 0; c < compound->getNumChildShapes(); c++)
{
btCollisionShape* childShape = compound->getChildShape(c);
if (u2b.getUrdfFromCollisionShape(childShape, urdfCollision))
{
m_data->m_bulletCollisionShape2UrdfCollision.insert(childShape, urdfCollision);
}
}
}
}
m_data->m_saveWorldBodyData.push_back(sd);
syncPhysicsToGraphics2();
return loadOk;
}
struct MyMJCFLogger2 : public MJCFErrorLogger
{
virtual void reportError(const char* error)
{
b3Error(error);
}
virtual void reportWarning(const char* warning)
{
b3Warning(warning);
}
virtual void printMessage(const char* msg)
{
b3Printf(msg);
}
};
bool PhysicsServerCommandProcessor::loadMjcf(const char* fileName, char* bufferServerToClient, int bufferSizeInBytes, bool useMultiBody, int flags)
{
btAssert(m_data->m_dynamicsWorld);
if (!m_data->m_dynamicsWorld)
{
b3Error("loadSdf: No valid m_dynamicsWorld");
return false;
}
m_data->m_sdfRecentLoadedBodies.clear();
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
BulletMJCFImporter u2b(m_data->m_guiHelper, m_data->m_pluginManager.getRenderInterface(), fileIO, flags);
bool useFixedBase = false;
MyMJCFLogger2 logger;
bool loadOk = u2b.loadMJCF(fileName, &logger, useFixedBase);
if (loadOk)
{
processImportedObjects(fileName, bufferServerToClient, bufferSizeInBytes, useMultiBody, flags, u2b);
}
return loadOk;
}
bool PhysicsServerCommandProcessor::loadSdf(const char* fileName, char* bufferServerToClient, int bufferSizeInBytes, bool useMultiBody, int flags, btScalar globalScaling)
{
btAssert(m_data->m_dynamicsWorld);
if (!m_data->m_dynamicsWorld)
{
b3Error("loadSdf: No valid m_dynamicsWorld");
return false;
}
m_data->m_sdfRecentLoadedBodies.clear();
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
BulletURDFImporter u2b(m_data->m_guiHelper, m_data->m_pluginManager.getRenderInterface(), fileIO, globalScaling, flags);
u2b.setEnableTinyRenderer(m_data->m_enableTinyRenderer);
bool forceFixedBase = false;
bool loadOk = u2b.loadSDF(fileName, forceFixedBase);
if (loadOk)
{
processImportedObjects(fileName, bufferServerToClient, bufferSizeInBytes, useMultiBody, flags, u2b);
}
return loadOk;
}
bool PhysicsServerCommandProcessor::loadUrdf(const char* fileName, const btVector3& pos, const btQuaternion& orn,
bool useMultiBody, bool useFixedBase, int* bodyUniqueIdPtr, char* bufferServerToClient, int bufferSizeInBytes, int orgFlags, btScalar globalScaling)
{
//clear the LOAD_SDF_FILE=1 bit, which is reserved for internal use of loadSDF command.
int flags = orgFlags & ~1;
m_data->m_sdfRecentLoadedBodies.clear();
*bodyUniqueIdPtr = -1;
BT_PROFILE("loadURDF");
btAssert(m_data->m_dynamicsWorld);
if (!m_data->m_dynamicsWorld)
{
b3Error("loadUrdf: No valid m_dynamicsWorld");
return false;
}
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
BulletURDFImporter u2b(m_data->m_guiHelper, m_data->m_pluginManager.getRenderInterface(), fileIO, globalScaling, flags);
u2b.setEnableTinyRenderer(m_data->m_enableTinyRenderer);
bool loadOk = u2b.loadURDF(fileName, useFixedBase);
if (loadOk)
{
btTransform rootTrans;
rootTrans.setOrigin(pos);
rootTrans.setRotation(orn);
u2b.setRootTransformInWorld(rootTrans);
bool ok = processImportedObjects(fileName, bufferServerToClient, bufferSizeInBytes, useMultiBody, flags, u2b);
if (ok)
{
if (m_data->m_sdfRecentLoadedBodies.size() == 1)
{
*bodyUniqueIdPtr = m_data->m_sdfRecentLoadedBodies[0];
}
m_data->m_sdfRecentLoadedBodies.clear();
}
return ok;
}
return false;
}
void PhysicsServerCommandProcessor::replayLogCommand(char* bufferServerToClient, int bufferSizeInBytes)
{
if (m_data->m_logPlayback)
{
SharedMemoryCommand clientCmd;
SharedMemoryStatus serverStatus;
bool hasCommand = m_data->m_logPlayback->processNextCommand(&clientCmd);
if (hasCommand)
{
processCommand(clientCmd, serverStatus, bufferServerToClient, bufferSizeInBytes);
}
}
}
int PhysicsServerCommandProcessor::createBodyInfoStream(int bodyUniqueId, char* bufferServerToClient, int bufferSizeInBytes)
{
int streamSizeInBytes = 0;
//serialize the btMultiBody and send the data to the client. This is one way to get the link/joint names across the (shared memory) wire
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (!bodyHandle) return 0;
if (bodyHandle->m_multiBody)
{
btMultiBody* mb = bodyHandle->m_multiBody;
btDefaultSerializer ser(bufferSizeInBytes, (unsigned char*)bufferServerToClient);
ser.startSerialization();
//disable serialization of the collision objects (they are too big, and the client likely doesn't need them);
ser.m_skipPointers.insert(mb->getBaseCollider(), 0);
if (mb->getBaseName())
{
ser.registerNameForPointer(mb->getBaseName(), mb->getBaseName());
}
bodyHandle->m_linkLocalInertialFrames.reserve(mb->getNumLinks());
for (int i = 0; i < mb->getNumLinks(); i++)
{
//disable serialization of the collision objects
ser.m_skipPointers.insert(mb->getLink(i).m_collider, 0);
ser.registerNameForPointer(mb->getLink(i).m_linkName, mb->getLink(i).m_linkName);
ser.registerNameForPointer(mb->getLink(i).m_jointName, mb->getLink(i).m_jointName);
}
ser.registerNameForPointer(mb->getBaseName(), mb->getBaseName());
int len = mb->calculateSerializeBufferSize();
btChunk* chunk = ser.allocate(len, 1);
const char* structType = mb->serialize(chunk->m_oldPtr, &ser);
ser.finalizeChunk(chunk, structType, BT_MULTIBODY_CODE, mb);
streamSizeInBytes = ser.getCurrentBufferSize();
}
else if (bodyHandle->m_rigidBody)
{
btRigidBody* rb = bodyHandle->m_rigidBody;
btDefaultSerializer ser(bufferSizeInBytes, (unsigned char*)bufferServerToClient);
ser.startSerialization();
ser.registerNameForPointer(bodyHandle->m_rigidBody, bodyHandle->m_bodyName.c_str());
//disable serialization of the collision objects (they are too big, and the client likely doesn't need them);
for (int i = 0; i < bodyHandle->m_rigidBodyJoints.size(); i++)
{
const btGeneric6DofSpring2Constraint* con = bodyHandle->m_rigidBodyJoints.at(i);
ser.registerNameForPointer(con, bodyHandle->m_rigidBodyJointNames[i].c_str());
ser.registerNameForPointer(&con->getRigidBodyB(), bodyHandle->m_rigidBodyLinkNames[i].c_str());
const btRigidBody& bodyA = con->getRigidBodyA();
int len = con->calculateSerializeBufferSize();
btChunk* chunk = ser.allocate(len, 1);
const char* structType = con->serialize(chunk->m_oldPtr, &ser);
ser.finalizeChunk(chunk, structType, BT_CONSTRAINT_CODE, (void*)con);
}
streamSizeInBytes = ser.getCurrentBufferSize();
}
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
else if (bodyHandle->m_softBody)
{
//minimum serialization, registerNameForPointer
btSoftBody* sb = bodyHandle->m_softBody;
btDefaultSerializer ser(bufferSizeInBytes, (unsigned char*)bufferServerToClient);
ser.startSerialization();
int len = sb->calculateSerializeBufferSize();
btChunk* chunk = ser.allocate(len, 1);
const char* structType = sb->serialize(chunk->m_oldPtr, &ser);
ser.finalizeChunk(chunk, structType, BT_SOFTBODY_CODE, sb);
streamSizeInBytes = ser.getCurrentBufferSize();
}
#endif
return streamSizeInBytes;
}
bool PhysicsServerCommandProcessor::processStateLoggingCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
BT_PROFILE("CMD_STATE_LOGGING");
serverStatusOut.m_type = CMD_STATE_LOGGING_FAILED;
bool hasStatus = true;
if (clientCmd.m_updateFlags & STATE_LOGGING_START_LOG)
{
if (clientCmd.m_stateLoggingArguments.m_logType == STATE_LOGGING_ALL_COMMANDS)
{
if (m_data->m_commandLogger == 0)
{
enableCommandLogging(true, clientCmd.m_stateLoggingArguments.m_fileName);
serverStatusOut.m_type = CMD_STATE_LOGGING_START_COMPLETED;
int loggerUid = m_data->m_stateLoggersUniqueId++;
m_data->m_commandLoggingUid = loggerUid;
serverStatusOut.m_stateLoggingResultArgs.m_loggingUniqueId = loggerUid;
}
}
if (clientCmd.m_stateLoggingArguments.m_logType == STATE_REPLAY_ALL_COMMANDS)
{
if (m_data->m_logPlayback == 0)
{
replayFromLogFile(clientCmd.m_stateLoggingArguments.m_fileName);
serverStatusOut.m_type = CMD_STATE_LOGGING_START_COMPLETED;
int loggerUid = m_data->m_stateLoggersUniqueId++;
m_data->m_logPlaybackUid = loggerUid;
serverStatusOut.m_stateLoggingResultArgs.m_loggingUniqueId = loggerUid;
}
}
if (clientCmd.m_stateLoggingArguments.m_logType == STATE_LOGGING_PROFILE_TIMINGS)
{
if (m_data->m_profileTimingLoggingUid < 0)
{
b3ChromeUtilsStartTimings();
m_data->m_profileTimingFileName = clientCmd.m_stateLoggingArguments.m_fileName;
int loggerUid = m_data->m_stateLoggersUniqueId++;
serverStatusOut.m_type = CMD_STATE_LOGGING_START_COMPLETED;
serverStatusOut.m_stateLoggingResultArgs.m_loggingUniqueId = loggerUid;
m_data->m_profileTimingLoggingUid = loggerUid;
}
}
if (clientCmd.m_stateLoggingArguments.m_logType == STATE_LOGGING_VIDEO_MP4)
{
//if (clientCmd.m_stateLoggingArguments.m_fileName)
{
int loggerUid = m_data->m_stateLoggersUniqueId++;
VideoMP4Loggger* logger = new VideoMP4Loggger(loggerUid, clientCmd.m_stateLoggingArguments.m_fileName, this->m_data->m_guiHelper);
m_data->m_stateLoggers.push_back(logger);
serverStatusOut.m_type = CMD_STATE_LOGGING_START_COMPLETED;
serverStatusOut.m_stateLoggingResultArgs.m_loggingUniqueId = loggerUid;
}
}
if (clientCmd.m_stateLoggingArguments.m_logType == STATE_LOGGING_MINITAUR)
{
std::string fileName = clientCmd.m_stateLoggingArguments.m_fileName;
//either provide the minitaur by object unique Id, or search for first multibody with 8 motors...
if ((clientCmd.m_updateFlags & STATE_LOGGING_FILTER_OBJECT_UNIQUE_ID) && (clientCmd.m_stateLoggingArguments.m_numBodyUniqueIds > 0))
{
int bodyUniqueId = clientCmd.m_stateLoggingArguments.m_bodyUniqueIds[0];
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (body)
{
if (body->m_multiBody)
{
btAlignedObjectArray<std::string> motorNames;
motorNames.push_back("motor_front_leftR_joint");
motorNames.push_back("motor_front_leftL_joint");
motorNames.push_back("motor_back_leftR_joint");
motorNames.push_back("motor_back_leftL_joint");
motorNames.push_back("motor_front_rightL_joint");
motorNames.push_back("motor_front_rightR_joint");
motorNames.push_back("motor_back_rightL_joint");
motorNames.push_back("motor_back_rightR_joint");
btAlignedObjectArray<int> motorIdList;
for (int m = 0; m < motorNames.size(); m++)
{
for (int i = 0; i < body->m_multiBody->getNumLinks(); i++)
{
std::string jointName;
if (body->m_multiBody->getLink(i).m_jointName)
{
jointName = body->m_multiBody->getLink(i).m_jointName;
}
if (motorNames[m] == jointName)
{
motorIdList.push_back(i);
}
}
}
if (motorIdList.size() == 8)
{
int loggerUid = m_data->m_stateLoggersUniqueId++;
MinitaurStateLogger* logger = new MinitaurStateLogger(loggerUid, fileName, body->m_multiBody, motorIdList);
m_data->m_stateLoggers.push_back(logger);
serverStatusOut.m_type = CMD_STATE_LOGGING_START_COMPLETED;
serverStatusOut.m_stateLoggingResultArgs.m_loggingUniqueId = loggerUid;
}
}
}
}
}
if (clientCmd.m_stateLoggingArguments.m_logType == STATE_LOGGING_GENERIC_ROBOT)
{
std::string fileName = clientCmd.m_stateLoggingArguments.m_fileName;
int loggerUid = m_data->m_stateLoggersUniqueId++;
int maxLogDof = 12;
if ((clientCmd.m_updateFlags & STATE_LOGGING_MAX_LOG_DOF))
{
maxLogDof = clientCmd.m_stateLoggingArguments.m_maxLogDof;
}
int logFlags = 0;
if (clientCmd.m_updateFlags & STATE_LOGGING_LOG_FLAGS)
{
logFlags = clientCmd.m_stateLoggingArguments.m_logFlags;
}
GenericRobotStateLogger* logger = new GenericRobotStateLogger(loggerUid, fileName, m_data->m_dynamicsWorld, maxLogDof, logFlags);
if ((clientCmd.m_updateFlags & STATE_LOGGING_FILTER_OBJECT_UNIQUE_ID) && (clientCmd.m_stateLoggingArguments.m_numBodyUniqueIds > 0))
{
logger->m_filterObjectUniqueId = true;
for (int i = 0; i < clientCmd.m_stateLoggingArguments.m_numBodyUniqueIds; ++i)
{
int objectUniqueId = clientCmd.m_stateLoggingArguments.m_bodyUniqueIds[i];
logger->m_bodyIdList.push_back(objectUniqueId);
}
}
m_data->m_stateLoggers.push_back(logger);
serverStatusOut.m_type = CMD_STATE_LOGGING_START_COMPLETED;
serverStatusOut.m_stateLoggingResultArgs.m_loggingUniqueId = loggerUid;
}
if (clientCmd.m_stateLoggingArguments.m_logType == STATE_LOGGING_CONTACT_POINTS)
{
std::string fileName = clientCmd.m_stateLoggingArguments.m_fileName;
int loggerUid = m_data->m_stateLoggersUniqueId++;
ContactPointsStateLogger* logger = new ContactPointsStateLogger(loggerUid, fileName, m_data->m_dynamicsWorld);
if ((clientCmd.m_updateFlags & STATE_LOGGING_FILTER_LINK_INDEX_A) && clientCmd.m_stateLoggingArguments.m_linkIndexA >= -1)
{
logger->m_filterLinkA = true;
logger->m_linkIndexA = clientCmd.m_stateLoggingArguments.m_linkIndexA;
}
if ((clientCmd.m_updateFlags & STATE_LOGGING_FILTER_LINK_INDEX_B) && clientCmd.m_stateLoggingArguments.m_linkIndexB >= -1)
{
logger->m_filterLinkB = true;
logger->m_linkIndexB = clientCmd.m_stateLoggingArguments.m_linkIndexB;
}
if ((clientCmd.m_updateFlags & STATE_LOGGING_FILTER_BODY_UNIQUE_ID_A) && clientCmd.m_stateLoggingArguments.m_bodyUniqueIdA > -1)
{
logger->m_bodyUniqueIdA = clientCmd.m_stateLoggingArguments.m_bodyUniqueIdA;
}
if ((clientCmd.m_updateFlags & STATE_LOGGING_FILTER_BODY_UNIQUE_ID_B) && clientCmd.m_stateLoggingArguments.m_bodyUniqueIdB > -1)
{
logger->m_bodyUniqueIdB = clientCmd.m_stateLoggingArguments.m_bodyUniqueIdB;
}
m_data->m_stateLoggers.push_back(logger);
serverStatusOut.m_type = CMD_STATE_LOGGING_START_COMPLETED;
serverStatusOut.m_stateLoggingResultArgs.m_loggingUniqueId = loggerUid;
}
if (clientCmd.m_stateLoggingArguments.m_logType == STATE_LOGGING_VR_CONTROLLERS)
{
std::string fileName = clientCmd.m_stateLoggingArguments.m_fileName;
int loggerUid = m_data->m_stateLoggersUniqueId++;
int deviceFilterType = VR_DEVICE_CONTROLLER;
if (clientCmd.m_updateFlags & STATE_LOGGING_FILTER_DEVICE_TYPE)
{
deviceFilterType = clientCmd.m_stateLoggingArguments.m_deviceFilterType;
}
VRControllerStateLogger* logger = new VRControllerStateLogger(loggerUid, deviceFilterType, fileName);
m_data->m_stateLoggers.push_back(logger);
serverStatusOut.m_type = CMD_STATE_LOGGING_START_COMPLETED;
serverStatusOut.m_stateLoggingResultArgs.m_loggingUniqueId = loggerUid;
}
}
if ((clientCmd.m_updateFlags & STATE_LOGGING_STOP_LOG) && clientCmd.m_stateLoggingArguments.m_loggingUniqueId >= 0)
{
if (clientCmd.m_stateLoggingArguments.m_loggingUniqueId == m_data->m_logPlaybackUid)
{
if (m_data->m_logPlayback)
{
delete m_data->m_logPlayback;
m_data->m_logPlayback = 0;
m_data->m_logPlaybackUid = -1;
}
}
if (clientCmd.m_stateLoggingArguments.m_loggingUniqueId == m_data->m_commandLoggingUid)
{
if (m_data->m_commandLogger)
{
enableCommandLogging(false, 0);
serverStatusOut.m_type = CMD_STATE_LOGGING_COMPLETED;
m_data->m_commandLoggingUid = -1;
}
}
if (clientCmd.m_stateLoggingArguments.m_loggingUniqueId == m_data->m_profileTimingLoggingUid)
{
serverStatusOut.m_type = CMD_STATE_LOGGING_COMPLETED;
b3ChromeUtilsStopTimingsAndWriteJsonFile(m_data->m_profileTimingFileName.c_str());
m_data->m_profileTimingLoggingUid = -1;
}
else
{
serverStatusOut.m_type = CMD_STATE_LOGGING_COMPLETED;
for (int i = 0; i < m_data->m_stateLoggers.size(); i++)
{
if (m_data->m_stateLoggers[i]->m_loggingUniqueId == clientCmd.m_stateLoggingArguments.m_loggingUniqueId)
{
m_data->m_stateLoggers[i]->stop();
delete m_data->m_stateLoggers[i];
m_data->m_stateLoggers.removeAtIndex(i);
}
}
}
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestCameraImageCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_CAMERA_IMAGE_DATA");
int startPixelIndex = clientCmd.m_requestPixelDataArguments.m_startPixelIndex;
int width = clientCmd.m_requestPixelDataArguments.m_pixelWidth;
int height = clientCmd.m_requestPixelDataArguments.m_pixelHeight;
int numPixelsCopied = 0;
if ((clientCmd.m_requestPixelDataArguments.m_startPixelIndex == 0) &&
(clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_SET_PIXEL_WIDTH_HEIGHT) != 0)
{
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->setWidthAndHeight(clientCmd.m_requestPixelDataArguments.m_pixelWidth,
clientCmd.m_requestPixelDataArguments.m_pixelHeight);
}
}
int flags = 0;
if (clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_HAS_FLAGS)
{
flags = clientCmd.m_requestPixelDataArguments.m_flags;
}
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->setFlags(flags);
}
int numTotalPixels = width * height;
int numRemainingPixels = numTotalPixels - startPixelIndex;
if (numRemainingPixels > 0)
{
int totalBytesPerPixel = 4 + 4 + 4; //4 for rgb, 4 for depth, 4 for segmentation mask
int maxNumPixels = bufferSizeInBytes / totalBytesPerPixel - 1;
unsigned char* pixelRGBA = (unsigned char*)bufferServerToClient;
int numRequestedPixels = btMin(maxNumPixels, numRemainingPixels);
float* depthBuffer = (float*)(bufferServerToClient + numRequestedPixels * 4);
int* segmentationMaskBuffer = (int*)(bufferServerToClient + numRequestedPixels * 8);
serverStatusOut.m_numDataStreamBytes = numRequestedPixels * totalBytesPerPixel;
float viewMat[16];
float projMat[16];
float projTextureViewMat[16];
float projTextureProjMat[16];
for (int i = 0; i < 16; i++)
{
viewMat[i] = clientCmd.m_requestPixelDataArguments.m_viewMatrix[i];
projMat[i] = clientCmd.m_requestPixelDataArguments.m_projectionMatrix[i];
}
if ((clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_HAS_CAMERA_MATRICES) == 0)
{
b3OpenGLVisualizerCameraInfo tmpCamResult;
bool result = this->m_data->m_guiHelper->getCameraInfo(
&tmpCamResult.m_width,
&tmpCamResult.m_height,
tmpCamResult.m_viewMatrix,
tmpCamResult.m_projectionMatrix,
tmpCamResult.m_camUp,
tmpCamResult.m_camForward,
tmpCamResult.m_horizontal,
tmpCamResult.m_vertical,
&tmpCamResult.m_yaw,
&tmpCamResult.m_pitch,
&tmpCamResult.m_dist,
tmpCamResult.m_target);
if (result)
{
for (int i = 0; i < 16; i++)
{
viewMat[i] = tmpCamResult.m_viewMatrix[i];
projMat[i] = tmpCamResult.m_projectionMatrix[i];
}
}
}
bool handled = false;
if ((clientCmd.m_updateFlags & ER_BULLET_HARDWARE_OPENGL) != 0)
{
if ((flags & ER_USE_PROJECTIVE_TEXTURE) != 0)
{
this->m_data->m_guiHelper->setProjectiveTexture(true);
if ((clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_HAS_PROJECTIVE_TEXTURE_MATRICES) != 0)
{
for (int i = 0; i < 16; i++)
{
projTextureViewMat[i] = clientCmd.m_requestPixelDataArguments.m_projectiveTextureViewMatrix[i];
projTextureProjMat[i] = clientCmd.m_requestPixelDataArguments.m_projectiveTextureProjectionMatrix[i];
}
}
else // If no specified matrices for projective texture, then use the camera matrices.
{
for (int i = 0; i < 16; i++)
{
projTextureViewMat[i] = viewMat[i];
projTextureProjMat[i] = projMat[i];
}
}
this->m_data->m_guiHelper->setProjectiveTextureMatrices(projTextureViewMat, projTextureProjMat);
}
else
{
this->m_data->m_guiHelper->setProjectiveTexture(false);
}
if ((flags & ER_NO_SEGMENTATION_MASK) != 0)
{
segmentationMaskBuffer = 0;
}
m_data->m_guiHelper->copyCameraImageData(viewMat,
projMat, pixelRGBA, numRequestedPixels,
depthBuffer, numRequestedPixels,
segmentationMaskBuffer, numRequestedPixels,
startPixelIndex, width, height, &numPixelsCopied);
if (numPixelsCopied > 0)
{
//convert segmentation mask
if (segmentationMaskBuffer)
{
for (int i = 0; i < numPixelsCopied; i++)
{
int graphicsSegMask = segmentationMaskBuffer[i];
int segMask = -1;
if ((graphicsSegMask >= 0) && (graphicsSegMask < m_data->m_graphicsIndexToSegmentationMask.size()))
{
segMask = m_data->m_graphicsIndexToSegmentationMask[graphicsSegMask];
}
if ((flags & ER_SEGMENTATION_MASK_OBJECT_AND_LINKINDEX) == 0)
{
if (segMask >= 0)
{
segMask &= ((1 << 24) - 1);
}
}
segmentationMaskBuffer[i] = segMask;
}
}
handled = true;
m_data->m_guiHelper->debugDisplayCameraImageData(viewMat,
projMat, pixelRGBA, numRequestedPixels,
depthBuffer, numRequestedPixels,
segmentationMaskBuffer, numRequestedPixels,
startPixelIndex, width, height, &numPixelsCopied);
}
}
if (!handled)
{
if (m_data->m_pluginManager.getRenderInterface())
{
if (clientCmd.m_requestPixelDataArguments.m_startPixelIndex == 0)
{
// printf("-------------------------------\nRendering\n");
if ((clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_SET_LIGHT_DIRECTION) != 0)
{
m_data->m_pluginManager.getRenderInterface()->setLightDirection(clientCmd.m_requestPixelDataArguments.m_lightDirection[0], clientCmd.m_requestPixelDataArguments.m_lightDirection[1], clientCmd.m_requestPixelDataArguments.m_lightDirection[2]);
}
if ((clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_SET_LIGHT_COLOR) != 0)
{
m_data->m_pluginManager.getRenderInterface()->setLightColor(clientCmd.m_requestPixelDataArguments.m_lightColor[0], clientCmd.m_requestPixelDataArguments.m_lightColor[1], clientCmd.m_requestPixelDataArguments.m_lightColor[2]);
}
if ((clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_SET_LIGHT_DISTANCE) != 0)
{
m_data->m_pluginManager.getRenderInterface()->setLightDistance(clientCmd.m_requestPixelDataArguments.m_lightDistance);
}
if ((clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_SET_SHADOW) != 0)
{
m_data->m_pluginManager.getRenderInterface()->setShadow((clientCmd.m_requestPixelDataArguments.m_hasShadow != 0));
}
if ((clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_SET_AMBIENT_COEFF) != 0)
{
m_data->m_pluginManager.getRenderInterface()->setLightAmbientCoeff(clientCmd.m_requestPixelDataArguments.m_lightAmbientCoeff);
}
if ((clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_SET_DIFFUSE_COEFF) != 0)
{
m_data->m_pluginManager.getRenderInterface()->setLightDiffuseCoeff(clientCmd.m_requestPixelDataArguments.m_lightDiffuseCoeff);
}
if ((clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_SET_SPECULAR_COEFF) != 0)
{
m_data->m_pluginManager.getRenderInterface()->setLightSpecularCoeff(clientCmd.m_requestPixelDataArguments.m_lightSpecularCoeff);
}
for (int i = 0; i < m_data->m_dynamicsWorld->getNumCollisionObjects(); i++)
{
const btCollisionObject* colObj = m_data->m_dynamicsWorld->getCollisionObjectArray()[i];
m_data->m_pluginManager.getRenderInterface()->syncTransform(colObj->getUserIndex3(), colObj->getWorldTransform(), colObj->getCollisionShape()->getLocalScaling());
}
if ((clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_HAS_CAMERA_MATRICES) != 0)
{
m_data->m_pluginManager.getRenderInterface()->render(
clientCmd.m_requestPixelDataArguments.m_viewMatrix,
clientCmd.m_requestPixelDataArguments.m_projectionMatrix);
}
else
{
b3OpenGLVisualizerCameraInfo tmpCamResult;
bool result = this->m_data->m_guiHelper->getCameraInfo(
&tmpCamResult.m_width,
&tmpCamResult.m_height,
tmpCamResult.m_viewMatrix,
tmpCamResult.m_projectionMatrix,
tmpCamResult.m_camUp,
tmpCamResult.m_camForward,
tmpCamResult.m_horizontal,
tmpCamResult.m_vertical,
&tmpCamResult.m_yaw,
&tmpCamResult.m_pitch,
&tmpCamResult.m_dist,
tmpCamResult.m_target);
if (result)
{
m_data->m_pluginManager.getRenderInterface()->render(tmpCamResult.m_viewMatrix, tmpCamResult.m_projectionMatrix);
}
else
{
m_data->m_pluginManager.getRenderInterface()->render();
}
}
}
}
if (m_data->m_pluginManager.getRenderInterface())
{
if ((flags & ER_USE_PROJECTIVE_TEXTURE) != 0)
{
m_data->m_pluginManager.getRenderInterface()->setProjectiveTexture(true);
if ((clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_HAS_PROJECTIVE_TEXTURE_MATRICES) != 0)
{
for (int i = 0; i < 16; i++)
{
projTextureViewMat[i] = clientCmd.m_requestPixelDataArguments.m_projectiveTextureViewMatrix[i];
projTextureProjMat[i] = clientCmd.m_requestPixelDataArguments.m_projectiveTextureProjectionMatrix[i];
}
}
else // If no specified matrices for projective texture, then use the camera matrices.
{
for (int i = 0; i < 16; i++)
{
projTextureViewMat[i] = viewMat[i];
projTextureProjMat[i] = projMat[i];
}
}
m_data->m_pluginManager.getRenderInterface()->setProjectiveTextureMatrices(projTextureViewMat, projTextureProjMat);
}
else
{
m_data->m_pluginManager.getRenderInterface()->setProjectiveTexture(false);
}
if ((flags & ER_NO_SEGMENTATION_MASK) != 0)
{
segmentationMaskBuffer = 0;
}
m_data->m_pluginManager.getRenderInterface()->copyCameraImageData(pixelRGBA, numRequestedPixels,
depthBuffer, numRequestedPixels,
segmentationMaskBuffer, numRequestedPixels,
startPixelIndex, &width, &height, &numPixelsCopied);
m_data->m_pluginManager.getRenderInterface()->setProjectiveTexture(false);
}
m_data->m_guiHelper->debugDisplayCameraImageData(clientCmd.m_requestPixelDataArguments.m_viewMatrix,
clientCmd.m_requestPixelDataArguments.m_projectionMatrix, pixelRGBA, numRequestedPixels,
depthBuffer, numRequestedPixels,
segmentationMaskBuffer, numRequestedPixels,
startPixelIndex, width, height, &numPixelsCopied);
}
//each pixel takes 4 RGBA values and 1 float = 8 bytes
}
else
{
}
serverStatusOut.m_type = CMD_CAMERA_IMAGE_COMPLETED;
serverStatusOut.m_sendPixelDataArguments.m_numPixelsCopied = numPixelsCopied;
serverStatusOut.m_sendPixelDataArguments.m_numRemainingPixels = numRemainingPixels - numPixelsCopied;
serverStatusOut.m_sendPixelDataArguments.m_startingPixelIndex = startPixelIndex;
serverStatusOut.m_sendPixelDataArguments.m_imageWidth = width;
serverStatusOut.m_sendPixelDataArguments.m_imageHeight = height;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processSaveWorldCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = false;
BT_PROFILE("CMD_SAVE_WORLD");
serverStatusOut.m_type = CMD_SAVE_WORLD_FAILED;
///this is a very rudimentary way to save the state of the world, for scene authoring
///many todo's, for example save the state of motor controllers etc.
{
//saveWorld(clientCmd.m_sdfArguments.m_sdfFileName);
int constraintCount = 0;
FILE* f = fopen(clientCmd.m_sdfArguments.m_sdfFileName, "w");
if (f)
{
char line[2048];
{
sprintf(line, "import pybullet as p\n");
int len = strlen(line);
fwrite(line, len, 1, f);
}
{
sprintf(line, "cin = p.connect(p.SHARED_MEMORY)\n");
int len = strlen(line);
fwrite(line, len, 1, f);
}
{
sprintf(line, "if (cin < 0):\n");
int len = strlen(line);
fwrite(line, len, 1, f);
}
{
sprintf(line, " cin = p.connect(p.GUI)\n");
int len = strlen(line);
fwrite(line, len, 1, f);
}
//for each objects ...
for (int i = 0; i < m_data->m_saveWorldBodyData.size(); i++)
{
SaveWorldObjectData& sd = m_data->m_saveWorldBodyData[i];
for (int i = 0; i < sd.m_bodyUniqueIds.size(); i++)
{
{
int bodyUniqueId = sd.m_bodyUniqueIds[i];
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (body)
{
if (body->m_multiBody)
{
btMultiBody* mb = body->m_multiBody;
btTransform comTr = mb->getBaseWorldTransform();
btTransform tr = comTr * body->m_rootLocalInertialFrame.inverse();
if (strstr(sd.m_fileName.c_str(), ".urdf"))
{
sprintf(line, "objects = [p.loadURDF(\"%s\", %f,%f,%f,%f,%f,%f,%f)]\n", sd.m_fileName.c_str(),
tr.getOrigin()[0], tr.getOrigin()[1], tr.getOrigin()[2],
tr.getRotation()[0], tr.getRotation()[1], tr.getRotation()[2], tr.getRotation()[3]);
int len = strlen(line);
fwrite(line, len, 1, f);
}
if (strstr(sd.m_fileName.c_str(), ".sdf") && i == 0)
{
sprintf(line, "objects = p.loadSDF(\"%s\")\n", sd.m_fileName.c_str());
int len = strlen(line);
fwrite(line, len, 1, f);
}
if (strstr(sd.m_fileName.c_str(), ".xml") && i == 0)
{
sprintf(line, "objects = p.loadMJCF(\"%s\")\n", sd.m_fileName.c_str());
int len = strlen(line);
fwrite(line, len, 1, f);
}
if (strstr(sd.m_fileName.c_str(), ".sdf") || strstr(sd.m_fileName.c_str(), ".xml") || ((strstr(sd.m_fileName.c_str(), ".urdf")) && mb->getNumLinks()))
{
sprintf(line, "ob = objects[%d]\n", i);
int len = strlen(line);
fwrite(line, len, 1, f);
}
if (strstr(sd.m_fileName.c_str(), ".sdf") || strstr(sd.m_fileName.c_str(), ".xml"))
{
sprintf(line, "p.resetBasePositionAndOrientation(ob,[%f,%f,%f],[%f,%f,%f,%f])\n",
comTr.getOrigin()[0], comTr.getOrigin()[1], comTr.getOrigin()[2],
comTr.getRotation()[0], comTr.getRotation()[1], comTr.getRotation()[2], comTr.getRotation()[3]);
int len = strlen(line);
fwrite(line, len, 1, f);
}
if (mb->getNumLinks())
{
{
sprintf(line, "jointPositions=[");
int len = strlen(line);
fwrite(line, len, 1, f);
}
for (int i = 0; i < mb->getNumLinks(); i++)
{
btScalar jointPos = mb->getJointPosMultiDof(i)[0];
if (i < mb->getNumLinks() - 1)
{
sprintf(line, " %f,", jointPos);
int len = strlen(line);
fwrite(line, len, 1, f);
}
else
{
sprintf(line, " %f ", jointPos);
int len = strlen(line);
fwrite(line, len, 1, f);
}
}
{
sprintf(line, "]\nfor jointIndex in range (p.getNumJoints(ob)):\n\tp.resetJointState(ob,jointIndex,jointPositions[jointIndex])\n\n");
int len = strlen(line);
fwrite(line, len, 1, f);
}
}
}
else
{
//todo: btRigidBody/btSoftBody etc case
}
}
}
}
//for URDF, load at origin, then reposition...
struct SaveWorldObjectData
{
b3AlignedObjectArray<int> m_bodyUniqueIds;
std::string m_fileName;
};
}
//user constraints
{
for (int i = 0; i < m_data->m_userConstraints.size(); i++)
{
InteralUserConstraintData* ucptr = m_data->m_userConstraints.getAtIndex(i);
b3UserConstraint& uc = ucptr->m_userConstraintData;
int parentBodyIndex = uc.m_parentBodyIndex;
int parentJointIndex = uc.m_parentJointIndex;
int childBodyIndex = uc.m_childBodyIndex;
int childJointIndex = uc.m_childJointIndex;
btVector3 jointAxis(uc.m_jointAxis[0], uc.m_jointAxis[1], uc.m_jointAxis[2]);
btVector3 pivotParent(uc.m_parentFrame[0], uc.m_parentFrame[1], uc.m_parentFrame[2]);
btVector3 pivotChild(uc.m_childFrame[0], uc.m_childFrame[1], uc.m_childFrame[2]);
btQuaternion ornFrameParent(uc.m_parentFrame[3], uc.m_parentFrame[4], uc.m_parentFrame[5], uc.m_parentFrame[6]);
btQuaternion ornFrameChild(uc.m_childFrame[3], uc.m_childFrame[4], uc.m_childFrame[5], uc.m_childFrame[6]);
{
char jointTypeStr[1024] = "FIXED";
bool hasKnownJointType = true;
switch (uc.m_jointType)
{
case eRevoluteType:
{
sprintf(jointTypeStr, "p.JOINT_REVOLUTE");
break;
}
case ePrismaticType:
{
sprintf(jointTypeStr, "p.JOINT_PRISMATIC");
break;
}
case eSphericalType:
{
sprintf(jointTypeStr, "p.JOINT_SPHERICAL");
break;
}
case ePlanarType:
{
sprintf(jointTypeStr, "p.JOINT_PLANAR");
break;
}
case eFixedType:
{
sprintf(jointTypeStr, "p.JOINT_FIXED");
break;
}
case ePoint2PointType:
{
sprintf(jointTypeStr, "p.JOINT_POINT2POINT");
break;
}
case eGearType:
{
sprintf(jointTypeStr, "p.JOINT_GEAR");
break;
}
default:
{
hasKnownJointType = false;
b3Warning("unknown constraint type in SAVE_WORLD");
}
};
if (hasKnownJointType)
{
{
sprintf(line, "cid%d = p.createConstraint(%d,%d,%d,%d,%s,[%f,%f,%f],[%f,%f,%f],[%f,%f,%f],[%f,%f,%f,%f],[%f,%f,%f,%f])\n",
constraintCount,
parentBodyIndex,
parentJointIndex,
childBodyIndex,
childJointIndex,
jointTypeStr,
jointAxis[0], jointAxis[1], jointAxis[2],
pivotParent[0], pivotParent[1], pivotParent[2],
pivotChild[0], pivotChild[1], pivotChild[2],
ornFrameParent[0], ornFrameParent[1], ornFrameParent[2], ornFrameParent[3],
ornFrameChild[0], ornFrameChild[1], ornFrameChild[2], ornFrameChild[3]);
int len = strlen(line);
fwrite(line, len, 1, f);
}
{
sprintf(line, "p.changeConstraint(cid%d,maxForce=%f)\n", constraintCount, uc.m_maxAppliedForce);
int len = strlen(line);
fwrite(line, len, 1, f);
constraintCount++;
}
}
}
}
}
{
btVector3 grav = this->m_data->m_dynamicsWorld->getGravity();
sprintf(line, "p.setGravity(%f,%f,%f)\n", grav[0], grav[1], grav[2]);
int len = strlen(line);
fwrite(line, len, 1, f);
}
{
sprintf(line, "p.stepSimulation()\np.disconnect()\n");
int len = strlen(line);
fwrite(line, len, 1, f);
}
fclose(f);
}
serverStatusOut.m_type = CMD_SAVE_WORLD_COMPLETED;
hasStatus = true;
}
return hasStatus;
}
#define MYLINELENGTH 16 * 32768
static unsigned char* MyGetRawHeightfieldData(CommonFileIOInterface& fileIO, PHY_ScalarType type, const char* fileName, int& width, int& height,
btScalar& minHeight,
btScalar& maxHeight)
{
std::string ext;
std::string fn(fileName);
std::string ext_ = fn.substr(fn.size() - 4);
for (std::string::iterator i = ext_.begin(); i != ext_.end(); ++i)
{
ext += char(tolower(*i));
}
if (ext != ".txt")
{
char relativeFileName[1024];
int found = fileIO.findResourcePath(fileName, relativeFileName, 1024);
b3AlignedObjectArray<char> buffer;
buffer.reserve(1024);
int fileId = fileIO.fileOpen(relativeFileName, "rb");
if (fileId >= 0)
{
int size = fileIO.getFileSize(fileId);
if (size > 0)
{
buffer.resize(size);
int actual = fileIO.fileRead(fileId, &buffer[0], size);
if (actual != size)
{
b3Warning("STL filesize mismatch!\n");
buffer.resize(0);
}
}
fileIO.fileClose(fileId);
}
if (buffer.size())
{
int n;
unsigned char* image = stbi_load_from_memory((const unsigned char*)&buffer[0], buffer.size(), &width, &height, &n, 3);
if (image)
{
fileIO.fileClose(fileId);
int nElements = width * height;
int bytesPerElement = sizeof(btScalar);
btAssert(bytesPerElement > 0 && "bad bytes per element");
int nBytes = nElements * bytesPerElement;
unsigned char* raw = new unsigned char[nBytes];
btAssert(raw && "out of memory");
unsigned char* p = raw;
for (int j = 0; j < height; ++j)
{
for (int i = 0; i < width; ++i)
{
float z = double(image[(width - 1 - i) * 3 + width * j * 3]) * (1. / 255.);
btScalar* pf = (btScalar*)p;
*pf = z;
p += bytesPerElement;
// update min/max
if (!i && !j)
{
minHeight = z;
maxHeight = z;
}
else
{
if (z < minHeight)
{
minHeight = z;
}
if (z > maxHeight)
{
maxHeight = z;
}
}
}
}
free(image);
return raw;
}
}
}
if (ext == ".txt")
{
//read a csv file as used in DeepLoco
{
char relativePath[1024];
int found = fileIO.findResourcePath(fileName, relativePath, 1024);
btAlignedObjectArray<char> lineBuffer;
lineBuffer.resize(MYLINELENGTH);
int slot = fileIO.fileOpen(relativePath, "r");
int rows = 0;
int cols = 0;
btAlignedObjectArray<double> allValues;
if (slot >= 0)
{
char* lineChar;
while (lineChar = fileIO.readLine(slot, &lineBuffer[0], MYLINELENGTH))
{
rows = 0;
std::string line(lineChar);
int pos = 0;
while (pos < line.length())
{
int nextPos = pos + 1;
while (nextPos < line.length())
{
if (line[nextPos - 1] == ',')
{
break;
}
nextPos++;
}
std::string substr = line.substr(pos, nextPos - pos - 1);
double v;
if (sscanf(substr.c_str(), "%lf", &v) == 1)
{
allValues.push_back(v);
rows++;
}
pos = nextPos;
}
cols++;
}
width = rows;
height = cols;
fileIO.fileClose(slot);
int nElements = width * height;
// std::cerr << " nElements = " << nElements << "\n";
int bytesPerElement = sizeof(btScalar);
// std::cerr << " bytesPerElement = " << bytesPerElement << "\n";
btAssert(bytesPerElement > 0 && "bad bytes per element");
long nBytes = nElements * bytesPerElement;
// std::cerr << " nBytes = " << nBytes << "\n";
unsigned char* raw = new unsigned char[nBytes];
btAssert(raw && "out of memory");
unsigned char* p = raw;
for (int i = 0; i < width; ++i)
{
for (int j = 0; j < height; ++j)
{
double z = allValues[i + width * j];
//convertFromFloat(p, z, type);
btScalar* pf = (btScalar*)p;
*pf = z;
p += bytesPerElement;
// update min/max
if (!i && !j)
{
minHeight = z;
maxHeight = z;
}
else
{
if (z < minHeight)
{
minHeight = z;
}
if (z > maxHeight)
{
maxHeight = z;
}
}
}
}
return raw;
}
}
}
return 0;
}
class MyTriangleCollector4 : public btTriangleCallback
{
public:
btAlignedObjectArray<GLInstanceVertex>* m_pVerticesOut;
btAlignedObjectArray<int>* m_pIndicesOut;
MyTriangleCollector4()
{
m_pVerticesOut = 0;
m_pIndicesOut = 0;
}
virtual void processTriangle(btVector3* tris, int partId, int triangleIndex)
{
for (int k = 0; k < 3; k++)
{
GLInstanceVertex v;
v.xyzw[3] = 0;
v.uv[0] = v.uv[1] = 0.5f;
btVector3 normal = (tris[0] - tris[1]).cross(tris[0] - tris[2]);
normal.safeNormalize();
for (int l = 0; l < 3; l++)
{
v.xyzw[l] = tris[k][l];
v.normal[l] = normal[l];
}
m_pIndicesOut->push_back(m_pVerticesOut->size());
m_pVerticesOut->push_back(v);
}
}
};
bool PhysicsServerCommandProcessor::processCreateCollisionShapeCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
serverStatusOut.m_type = CMD_CREATE_COLLISION_SHAPE_FAILED;
btMultiBodyWorldImporter* worldImporter = new btMultiBodyWorldImporter(m_data->m_dynamicsWorld);
btCollisionShape* shape = 0;
b3AlignedObjectArray<UrdfCollision> urdfCollisionObjects;
btCompoundShape* compound = 0;
if (clientCmd.m_createUserShapeArgs.m_numUserShapes > 1)
{
compound = worldImporter->createCompoundShape();
compound->setMargin(m_data->m_defaultCollisionMargin);
}
for (int i = 0; i < clientCmd.m_createUserShapeArgs.m_numUserShapes; i++)
{
GLInstanceGraphicsShape* glmesh = 0;
char pathPrefix[1024] = "";
char relativeFileName[1024] = "";
UrdfCollision urdfColObj;
btTransform childTransform;
childTransform.setIdentity();
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_hasChildTransform)
{
childTransform.setOrigin(btVector3(clientCmd.m_createUserShapeArgs.m_shapes[i].m_childPosition[0],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_childPosition[1],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_childPosition[2]));
childTransform.setRotation(btQuaternion(
clientCmd.m_createUserShapeArgs.m_shapes[i].m_childOrientation[0],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_childOrientation[1],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_childOrientation[2],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_childOrientation[3]));
if (compound == 0)
{
compound = worldImporter->createCompoundShape();
}
}
urdfColObj.m_linkLocalFrame = childTransform;
urdfColObj.m_sourceFileLocation = "memory";
urdfColObj.m_name = "memory";
urdfColObj.m_geometry.m_type = URDF_GEOM_UNKNOWN;
switch (clientCmd.m_createUserShapeArgs.m_shapes[i].m_type)
{
case GEOM_SPHERE:
{
double radius = clientCmd.m_createUserShapeArgs.m_shapes[i].m_sphereRadius;
shape = worldImporter->createSphereShape(radius);
shape->setMargin(m_data->m_defaultCollisionMargin);
if (compound)
{
compound->addChildShape(childTransform, shape);
}
urdfColObj.m_geometry.m_type = URDF_GEOM_SPHERE;
urdfColObj.m_geometry.m_sphereRadius = radius;
break;
}
case GEOM_BOX:
{
//double halfExtents[3] = clientCmd.m_createUserShapeArgs.m_shapes[i].m_sphereRadius;
btVector3 halfExtents(
clientCmd.m_createUserShapeArgs.m_shapes[i].m_boxHalfExtents[0],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_boxHalfExtents[1],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_boxHalfExtents[2]);
shape = worldImporter->createBoxShape(halfExtents);
shape->setMargin(m_data->m_defaultCollisionMargin);
if (compound)
{
compound->addChildShape(childTransform, shape);
}
urdfColObj.m_geometry.m_type = URDF_GEOM_BOX;
urdfColObj.m_geometry.m_boxSize = 2. * halfExtents;
break;
}
case GEOM_CAPSULE:
{
shape = worldImporter->createCapsuleShapeZ(clientCmd.m_createUserShapeArgs.m_shapes[i].m_capsuleRadius,
clientCmd.m_createUserShapeArgs.m_shapes[i].m_capsuleHeight);
shape->setMargin(m_data->m_defaultCollisionMargin);
if (compound)
{
compound->addChildShape(childTransform, shape);
}
urdfColObj.m_geometry.m_type = URDF_GEOM_CAPSULE;
urdfColObj.m_geometry.m_capsuleRadius = clientCmd.m_createUserShapeArgs.m_shapes[i].m_capsuleRadius;
urdfColObj.m_geometry.m_capsuleHeight = clientCmd.m_createUserShapeArgs.m_shapes[i].m_capsuleHeight;
break;
}
case GEOM_CYLINDER:
{
shape = worldImporter->createCylinderShapeZ(clientCmd.m_createUserShapeArgs.m_shapes[i].m_capsuleRadius,
0.5 * clientCmd.m_createUserShapeArgs.m_shapes[i].m_capsuleHeight);
shape->setMargin(m_data->m_defaultCollisionMargin);
if (compound)
{
compound->addChildShape(childTransform, shape);
}
urdfColObj.m_geometry.m_type = URDF_GEOM_CYLINDER;
urdfColObj.m_geometry.m_capsuleRadius = clientCmd.m_createUserShapeArgs.m_shapes[i].m_capsuleRadius;
urdfColObj.m_geometry.m_capsuleHeight = clientCmd.m_createUserShapeArgs.m_shapes[i].m_capsuleHeight;
break;
}
case GEOM_HEIGHTFIELD:
{
int width;
int height;
btScalar minHeight, maxHeight;
PHY_ScalarType scalarType = PHY_FLOAT;
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
const unsigned char* heightfieldData = 0;
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_numHeightfieldColumns > 0 &&
clientCmd.m_createUserShapeArgs.m_shapes[i].m_numHeightfieldRows > 0)
{
width = clientCmd.m_createUserShapeArgs.m_shapes[i].m_numHeightfieldRows;
height = clientCmd.m_createUserShapeArgs.m_shapes[i].m_numHeightfieldColumns;
float* heightfieldDataSrc = (float*)bufferServerToClient;
heightfieldData = new unsigned char[width * height * sizeof(btScalar)];
btScalar* datafl = (btScalar*)heightfieldData;
minHeight = heightfieldDataSrc[0];
maxHeight = heightfieldDataSrc[0];
for (int i = 0; i < width * height; i++)
{
datafl[i] = heightfieldDataSrc[i];
minHeight = btMin(minHeight, (btScalar)datafl[i]);
maxHeight = btMax(maxHeight, (btScalar)datafl[i]);
}
}
else
{
heightfieldData = MyGetRawHeightfieldData(*fileIO, scalarType, clientCmd.m_createUserShapeArgs.m_shapes[i].m_meshFileName, width, height, minHeight, maxHeight);
}
if (heightfieldData)
{
//replace heightfield data or create new heightfield
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_replaceHeightfieldIndex >= 0)
{
int collisionShapeUid = clientCmd.m_createUserShapeArgs.m_shapes[i].m_replaceHeightfieldIndex;
InternalCollisionShapeHandle* handle = m_data->m_userCollisionShapeHandles.getHandle(collisionShapeUid);
if (handle && handle->m_collisionShape && handle->m_collisionShape->getShapeType() == TERRAIN_SHAPE_PROXYTYPE)
{
btHeightfieldTerrainShape* terrainShape = (btHeightfieldTerrainShape*)handle->m_collisionShape;
btScalar* heightfieldDest = (btScalar*)terrainShape->getHeightfieldRawData();
//replace the data
btScalar* datafl = (btScalar*)heightfieldData;
for (int i = 0; i < width * height; i++)
{
heightfieldDest[i] = datafl[i];
}
//update graphics
btAlignedObjectArray<GLInstanceVertex> gfxVertices;
btAlignedObjectArray<int> indices;
int strideInBytes = 9 * sizeof(float);
MyTriangleCollector4 col;
col.m_pVerticesOut = &gfxVertices;
col.m_pIndicesOut = &indices;
btVector3 aabbMin, aabbMax;
for (int k = 0; k < 3; k++)
{
aabbMin[k] = -BT_LARGE_FLOAT;
aabbMax[k] = BT_LARGE_FLOAT;
}
terrainShape->processAllTriangles(&col, aabbMin, aabbMax);
if (gfxVertices.size() && indices.size())
{
m_data->m_guiHelper->updateShape(terrainShape->getUserIndex(), &gfxVertices[0].xyzw[0]);
}
terrainShape->clearAccelerator();
terrainShape->buildAccelerator();
btTriangleInfoMap* oldTriangleInfoMap = terrainShape->getTriangleInfoMap();
delete (oldTriangleInfoMap);
terrainShape->setTriangleInfoMap(0);
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_collisionFlags & GEOM_CONCAVE_INTERNAL_EDGE)
{
btTriangleInfoMap* triangleInfoMap = new btTriangleInfoMap();
btGenerateInternalEdgeInfo(terrainShape, triangleInfoMap);
}
serverStatusOut.m_createUserShapeResultArgs.m_userShapeUniqueId = collisionShapeUid;
delete worldImporter;
serverStatusOut.m_type = CMD_CREATE_COLLISION_SHAPE_COMPLETED;
}
delete heightfieldData;
return hasStatus;
}
else
{
btScalar gridSpacing = 0.5;
btScalar gridHeightScale = 1. / 256.;
bool flipQuadEdges = false;
int upAxis = 2;
/*btHeightfieldTerrainShape* heightfieldShape = worldImporter->createHeightfieldShape( width, height,
heightfieldData,
gridHeightScale,
minHeight, maxHeight,
upAxis, int(scalarType), flipQuadEdges);
*/
btHeightfieldTerrainShape* heightfieldShape = new btHeightfieldTerrainShape(width, height,
heightfieldData,
gridHeightScale,
minHeight, maxHeight,
upAxis, scalarType, flipQuadEdges);
m_data->m_collisionShapes.push_back(heightfieldShape);
heightfieldShape->setUserValue3(clientCmd.m_createUserShapeArgs.m_shapes[i].m_heightfieldTextureScaling);
shape = heightfieldShape;
if (upAxis == 2)
heightfieldShape->setFlipTriangleWinding(true);
// scale the shape
btVector3 localScaling(clientCmd.m_createUserShapeArgs.m_shapes[i].m_meshScale[0],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_meshScale[1],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_meshScale[2]);
heightfieldShape->setLocalScaling(localScaling);
//buildAccelerator is optional, it may not support all features.
heightfieldShape->buildAccelerator();
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_collisionFlags & GEOM_CONCAVE_INTERNAL_EDGE)
{
btTriangleInfoMap* triangleInfoMap = new btTriangleInfoMap();
btGenerateInternalEdgeInfo(heightfieldShape, triangleInfoMap);
}
this->m_data->m_heightfieldDatas.push_back(heightfieldData);
}
}
break;
}
case GEOM_PLANE:
{
btVector3 planeNormal(clientCmd.m_createUserShapeArgs.m_shapes[i].m_planeNormal[0],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_planeNormal[1],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_planeNormal[2]);
shape = worldImporter->createPlaneShape(planeNormal, clientCmd.m_createUserShapeArgs.m_shapes[i].m_planeConstant);
shape->setMargin(m_data->m_defaultCollisionMargin);
if (compound)
{
compound->addChildShape(childTransform, shape);
}
urdfColObj.m_geometry.m_type = URDF_GEOM_PLANE;
urdfColObj.m_geometry.m_planeNormal.setValue(
clientCmd.m_createUserShapeArgs.m_shapes[i].m_planeNormal[0],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_planeNormal[1],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_planeNormal[2]);
break;
}
case GEOM_MESH:
{
btVector3 meshScale(clientCmd.m_createUserShapeArgs.m_shapes[i].m_meshScale[0],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_meshScale[1],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_meshScale[2]);
const std::string& urdf_path = "";
std::string fileName = clientCmd.m_createUserShapeArgs.m_shapes[i].m_meshFileName;
urdfColObj.m_geometry.m_type = URDF_GEOM_MESH;
urdfColObj.m_geometry.m_meshFileName = fileName;
urdfColObj.m_geometry.m_meshScale = meshScale;
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
pathPrefix[0] = 0;
if (fileIO->findResourcePath(fileName.c_str(), relativeFileName, 1024))
{
b3FileUtils::extractPath(relativeFileName, pathPrefix, 1024);
}
const std::string& error_message_prefix = "";
std::string out_found_filename;
int out_type;
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_numVertices)
{
int numVertices = clientCmd.m_createUserShapeArgs.m_shapes[i].m_numVertices;
int numIndices = clientCmd.m_createUserShapeArgs.m_shapes[i].m_numIndices;
//int totalUploadSizeInBytes = numVertices * sizeof(double) * 3 + numIndices * sizeof(int);
char* data = bufferServerToClient;
double* vertexUpload = (double*)data;
int* indexUpload = (int*)(data + numVertices * sizeof(double) * 3);
if (compound == 0)
{
compound = worldImporter->createCompoundShape();
}
compound->setMargin(m_data->m_defaultCollisionMargin);
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_numIndices)
{
BT_PROFILE("convert trimesh2");
btTriangleMesh* meshInterface = new btTriangleMesh();
this->m_data->m_meshInterfaces.push_back(meshInterface);
{
BT_PROFILE("convert vertices2");
for (int j = 0; j < clientCmd.m_createUserShapeArgs.m_shapes[i].m_numIndices / 3; j++)
{
int i0 = indexUpload[j * 3 + 0];
int i1 = indexUpload[j * 3 + 1];
int i2 = indexUpload[j * 3 + 2];
btVector3 v0(vertexUpload[i0 * 3 + 0],
vertexUpload[i0 * 3 + 1],
vertexUpload[i0 * 3 + 2]);
btVector3 v1(vertexUpload[i1 * 3 + 0],
vertexUpload[i1 * 3 + 1],
vertexUpload[i1 * 3 + 2]);
btVector3 v2(vertexUpload[i2 * 3 + 0],
vertexUpload[i2 * 3 + 1],
vertexUpload[i2 * 3 + 2]);
meshInterface->addTriangle(v0 * meshScale, v1 * meshScale, v2 * meshScale);
}
}
{
BT_PROFILE("create btBvhTriangleMeshShape");
btBvhTriangleMeshShape* trimesh = new btBvhTriangleMeshShape(meshInterface, true, true);
m_data->m_collisionShapes.push_back(trimesh);
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_collisionFlags & GEOM_CONCAVE_INTERNAL_EDGE)
{
btTriangleInfoMap* triangleInfoMap = new btTriangleInfoMap();
btGenerateInternalEdgeInfo(trimesh, triangleInfoMap);
}
shape = trimesh;
if (compound)
{
compound->addChildShape(childTransform, shape);
shape->setMargin(m_data->m_defaultCollisionMargin);
}
}
}
else
{
btConvexHullShape* convexHull = worldImporter->createConvexHullShape();
convexHull->setMargin(m_data->m_defaultCollisionMargin);
for (int v = 0; v < clientCmd.m_createUserShapeArgs.m_shapes[i].m_numVertices; v++)
{
btVector3 pt(vertexUpload[v * 3 + 0],
vertexUpload[v * 3 + 1],
vertexUpload[v * 3 + 2]);
convexHull->addPoint(pt * meshScale, false);
}
convexHull->recalcLocalAabb();
convexHull->optimizeConvexHull();
compound->addChildShape(childTransform, convexHull);
}
urdfColObj.m_geometry.m_meshFileType = UrdfGeometry::MEMORY_VERTICES;
break;
}
bool foundFile = UrdfFindMeshFile(fileIO, pathPrefix, relativeFileName, error_message_prefix, &out_found_filename, &out_type);
if (foundFile)
{
urdfColObj.m_geometry.m_meshFileType = out_type;
if (out_type == UrdfGeometry::FILE_STL)
{
CommonFileIOInterface* fileIO(m_data->m_pluginManager.getFileIOInterface());
glmesh = LoadMeshFromSTL(relativeFileName, fileIO);
}
if (out_type == UrdfGeometry::FILE_OBJ)
{
//create a convex hull for each shape, and store it in a btCompoundShape
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_collisionFlags & GEOM_FORCE_CONCAVE_TRIMESH)
{
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
glmesh = LoadMeshFromObj(relativeFileName, pathPrefix, fileIO);
}
else
{
std::vector<tinyobj::shape_t> shapes;
tinyobj::attrib_t attribute;
std::string err = tinyobj::LoadObj(attribute, shapes, out_found_filename.c_str(), "", fileIO);
//shape = createConvexHullFromShapes(shapes, collision->m_geometry.m_meshScale);
//static btCollisionShape* createConvexHullFromShapes(std::vector<tinyobj::shape_t>& shapes, const btVector3& geomScale)
B3_PROFILE("createConvexHullFromShapes");
if (compound == 0)
{
compound = worldImporter->createCompoundShape();
}
compound->setMargin(m_data->m_defaultCollisionMargin);
for (int s = 0; s < (int)shapes.size(); s++)
{
btConvexHullShape* convexHull = worldImporter->createConvexHullShape();
convexHull->setMargin(m_data->m_defaultCollisionMargin);
tinyobj::shape_t& shape = shapes[s];
int faceCount = shape.mesh.indices.size();
for (int f = 0; f < faceCount; f += 3)
{
btVector3 pt;
pt.setValue(attribute.vertices[3 * shape.mesh.indices[f + 0].vertex_index + 0],
attribute.vertices[3 * shape.mesh.indices[f + 0].vertex_index + 1],
attribute.vertices[3 * shape.mesh.indices[f + 0].vertex_index + 2]);
convexHull->addPoint(pt * meshScale, false);
pt.setValue(attribute.vertices[3 * shape.mesh.indices[f + 1].vertex_index + 0],
attribute.vertices[3 * shape.mesh.indices[f + 1].vertex_index + 1],
attribute.vertices[3 * shape.mesh.indices[f + 1].vertex_index + 2]);
convexHull->addPoint(pt * meshScale, false);
pt.setValue(attribute.vertices[3 * shape.mesh.indices[f + 2].vertex_index + 0],
attribute.vertices[3 * shape.mesh.indices[f + 2].vertex_index + 1],
attribute.vertices[3 * shape.mesh.indices[f + 2].vertex_index + 2]);
convexHull->addPoint(pt * meshScale, false);
}
convexHull->recalcLocalAabb();
convexHull->optimizeConvexHull();
compound->addChildShape(childTransform, convexHull);
}
}
}
}
break;
}
default:
{
}
}
if (urdfColObj.m_geometry.m_type != URDF_GEOM_UNKNOWN)
{
urdfCollisionObjects.push_back(urdfColObj);
}
if (glmesh)
{
btVector3 meshScale(clientCmd.m_createUserShapeArgs.m_shapes[i].m_meshScale[0],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_meshScale[1],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_meshScale[2]);
if (!glmesh || glmesh->m_numvertices <= 0)
{
b3Warning("%s: cannot extract mesh from '%s'\n", pathPrefix, relativeFileName);
delete glmesh;
}
else
{
btAlignedObjectArray<btVector3> convertedVerts;
convertedVerts.reserve(glmesh->m_numvertices);
for (int v = 0; v < glmesh->m_numvertices; v++)
{
convertedVerts.push_back(btVector3(
glmesh->m_vertices->at(v).xyzw[0] * meshScale[0],
glmesh->m_vertices->at(v).xyzw[1] * meshScale[1],
glmesh->m_vertices->at(v).xyzw[2] * meshScale[2]));
}
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_collisionFlags & GEOM_FORCE_CONCAVE_TRIMESH)
{
BT_PROFILE("convert trimesh");
btTriangleMesh* meshInterface = new btTriangleMesh();
this->m_data->m_meshInterfaces.push_back(meshInterface);
{
BT_PROFILE("convert vertices");
for (int i = 0; i < glmesh->m_numIndices / 3; i++)
{
const btVector3& v0 = convertedVerts[glmesh->m_indices->at(i * 3)];
const btVector3& v1 = convertedVerts[glmesh->m_indices->at(i * 3 + 1)];
const btVector3& v2 = convertedVerts[glmesh->m_indices->at(i * 3 + 2)];
meshInterface->addTriangle(v0, v1, v2);
}
}
{
BT_PROFILE("create btBvhTriangleMeshShape");
btBvhTriangleMeshShape* trimesh = new btBvhTriangleMeshShape(meshInterface, true, true);
m_data->m_collisionShapes.push_back(trimesh);
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_collisionFlags & GEOM_CONCAVE_INTERNAL_EDGE)
{
btTriangleInfoMap* triangleInfoMap = new btTriangleInfoMap();
btGenerateInternalEdgeInfo(trimesh, triangleInfoMap);
}
//trimesh->setLocalScaling(collision->m_geometry.m_meshScale);
shape = trimesh;
if (compound)
{
compound->addChildShape(childTransform, shape);
shape->setMargin(m_data->m_defaultCollisionMargin);
}
}
delete glmesh;
}
else
{
//convex mesh
if (compound == 0)
{
compound = worldImporter->createCompoundShape();
}
compound->setMargin(m_data->m_defaultCollisionMargin);
{
btConvexHullShape* convexHull = worldImporter->createConvexHullShape();
convexHull->setMargin(m_data->m_defaultCollisionMargin);
for (int v = 0; v < convertedVerts.size(); v++)
{
btVector3 pt = convertedVerts[v];
convexHull->addPoint(pt, false);
}
convexHull->recalcLocalAabb();
convexHull->optimizeConvexHull();
compound->addChildShape(childTransform, convexHull);
}
}
}
}
}
if (compound && compound->getNumChildShapes())
{
shape = compound;
}
if (shape)
{
int collisionShapeUid = m_data->m_userCollisionShapeHandles.allocHandle();
InternalCollisionShapeHandle* handle = m_data->m_userCollisionShapeHandles.getHandle(collisionShapeUid);
handle->m_collisionShape = shape;
for (int i = 0; i < urdfCollisionObjects.size(); i++)
{
handle->m_urdfCollisionObjects.push_back(urdfCollisionObjects[i]);
}
serverStatusOut.m_createUserShapeResultArgs.m_userShapeUniqueId = collisionShapeUid;
m_data->m_worldImporters.push_back(worldImporter);
serverStatusOut.m_type = CMD_CREATE_COLLISION_SHAPE_COMPLETED;
}
else
{
delete worldImporter;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestMeshDataCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_MESH_DATA");
serverStatusOut.m_type = CMD_REQUEST_MESH_DATA_FAILED;
serverStatusOut.m_numDataStreamBytes = 0;
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(clientCmd.m_requestMeshDataArgs.m_bodyUniqueId);
if (bodyHandle)
{
if (bodyHandle->m_multiBody)
{
//todo
}
if (bodyHandle->m_rigidBody)
{
//todo
}
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
if (bodyHandle->m_softBody)
{
btSoftBody* psb = bodyHandle->m_softBody;
int totalBytesPerVertex = sizeof(btVector3);
bool separateRenderMesh = (psb->m_renderNodes.size() != 0);
int numVertices = separateRenderMesh ? psb->m_renderNodes.size() : psb->m_nodes.size();
int maxNumVertices = bufferSizeInBytes / totalBytesPerVertex - 1;
int numVerticesRemaining = numVertices - clientCmd.m_requestMeshDataArgs.m_startingVertex;
int verticesCopied = btMin(maxNumVertices, numVerticesRemaining);
btVector3* verticesOut = (btVector3*)bufferServerToClient;
for (int i = 0; i < verticesCopied; ++i)
{
if (separateRenderMesh)
{
const btSoftBody::Node& n = psb->m_renderNodes[i + clientCmd.m_requestMeshDataArgs.m_startingVertex];
verticesOut[i] = n.m_x;
}
else
{
const btSoftBody::Node& n = psb->m_nodes[i + clientCmd.m_requestMeshDataArgs.m_startingVertex];
verticesOut[i] = n.m_x;
}
}
serverStatusOut.m_type = CMD_REQUEST_MESH_DATA_COMPLETED;
serverStatusOut.m_sendMeshDataArgs.m_numVerticesCopied = verticesCopied;
serverStatusOut.m_sendMeshDataArgs.m_startingVertex = clientCmd.m_requestMeshDataArgs.m_startingVertex;
serverStatusOut.m_sendMeshDataArgs.m_numVerticesRemaining = numVerticesRemaining - verticesCopied;
}
#endif //SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
}
serverStatusOut.m_numDataStreamBytes = 0;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCreateVisualShapeCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
serverStatusOut.m_type = CMD_CREATE_VISUAL_SHAPE_FAILED;
double globalScaling = 1.f;
int flags = 0;
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
BulletURDFImporter u2b(m_data->m_guiHelper, m_data->m_pluginManager.getRenderInterface(), fileIO, globalScaling, flags);
u2b.setEnableTinyRenderer(m_data->m_enableTinyRenderer);
btTransform localInertiaFrame;
localInertiaFrame.setIdentity();
const char* pathPrefix = "";
int visualShapeUniqueId = -1;
UrdfVisual visualShape;
for (int userShapeIndex = 0; userShapeIndex < clientCmd.m_createUserShapeArgs.m_numUserShapes; userShapeIndex++)
{
btTransform childTrans;
childTrans.setIdentity();
visualShape.m_geometry.m_type = (UrdfGeomTypes)clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_type;
char relativeFileName[1024];
char pathPrefix[1024];
pathPrefix[0] = 0;
const b3CreateUserShapeData& visShape = clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex];
switch (visualShape.m_geometry.m_type)
{
case URDF_GEOM_CYLINDER:
{
visualShape.m_geometry.m_capsuleHeight = visShape.m_capsuleHeight;
visualShape.m_geometry.m_capsuleRadius = visShape.m_capsuleRadius;
break;
}
case URDF_GEOM_BOX:
{
visualShape.m_geometry.m_boxSize.setValue(2. * visShape.m_boxHalfExtents[0],
2. * visShape.m_boxHalfExtents[1],
2. * visShape.m_boxHalfExtents[2]);
break;
}
case URDF_GEOM_SPHERE:
{
visualShape.m_geometry.m_sphereRadius = visShape.m_sphereRadius;
break;
}
case URDF_GEOM_CAPSULE:
{
visualShape.m_geometry.m_hasFromTo = visShape.m_hasFromTo;
if (visualShape.m_geometry.m_hasFromTo)
{
visualShape.m_geometry.m_capsuleFrom.setValue(visShape.m_capsuleFrom[0],
visShape.m_capsuleFrom[1],
visShape.m_capsuleFrom[2]);
visualShape.m_geometry.m_capsuleTo.setValue(visShape.m_capsuleTo[0],
visShape.m_capsuleTo[1],
visShape.m_capsuleTo[2]);
}
else
{
visualShape.m_geometry.m_capsuleHeight = visShape.m_capsuleHeight;
visualShape.m_geometry.m_capsuleRadius = visShape.m_capsuleRadius;
}
break;
}
case URDF_GEOM_MESH:
{
std::string fileName = clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_meshFileName;
if (fileName.length())
{
const std::string& error_message_prefix = "";
std::string out_found_filename;
int out_type;
if (fileIO->findResourcePath(fileName.c_str(), relativeFileName, 1024))
{
b3FileUtils::extractPath(relativeFileName, pathPrefix, 1024);
}
bool foundFile = UrdfFindMeshFile(fileIO, pathPrefix, relativeFileName, error_message_prefix, &out_found_filename, &out_type);
if (foundFile)
{
visualShape.m_geometry.m_meshFileType = out_type;
visualShape.m_geometry.m_meshFileName = fileName;
}
else
{
}
}
else
{
visualShape.m_geometry.m_meshFileType = UrdfGeometry::MEMORY_VERTICES;
int numVertices = clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_numVertices;
int numIndices = clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_numIndices;
int numUVs = clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_numUVs;
int numNormals = clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_numNormals;
if (numVertices > 0 && numIndices > 0)
{
char* data = bufferServerToClient;
double* vertexUpload = (double*)data;
int* indexUpload = (int*)(data + numVertices * sizeof(double) * 3);
double* normalUpload = (double*)(data + numVertices * sizeof(double) * 3 + numIndices * sizeof(int));
double* uvUpload = (double*)(data + numVertices * sizeof(double) * 3 + numIndices * sizeof(int) + numNormals * sizeof(double) * 3);
for (int i = 0; i < numIndices; i++)
{
visualShape.m_geometry.m_indices.push_back(indexUpload[i]);
}
for (int i = 0; i < numVertices; i++)
{
btVector3 v0(vertexUpload[i * 3 + 0],
vertexUpload[i * 3 + 1],
vertexUpload[i * 3 + 2]);
visualShape.m_geometry.m_vertices.push_back(v0);
}
for (int i = 0; i < numNormals; i++)
{
btVector3 normal(normalUpload[i * 3 + 0],
normalUpload[i * 3 + 1],
normalUpload[i * 3 + 2]);
visualShape.m_geometry.m_normals.push_back(normal);
}
for (int i = 0; i < numUVs; i++)
{
btVector3 uv(uvUpload[i * 2 + 0], uvUpload[i * 2 + 1], 0);
visualShape.m_geometry.m_uvs.push_back(uv);
}
}
}
visualShape.m_geometry.m_meshScale.setValue(clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_meshScale[0],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_meshScale[1],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_meshScale[2]);
break;
}
default:
{
}
};
visualShape.m_name = "in_memory";
visualShape.m_materialName = "";
visualShape.m_sourceFileLocation = "in_memory_unknown_line";
visualShape.m_linkLocalFrame.setIdentity();
visualShape.m_geometry.m_hasLocalMaterial = false;
bool hasRGBA = (clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_visualFlags & GEOM_VISUAL_HAS_RGBA_COLOR) != 0;
;
bool hasSpecular = (clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_visualFlags & GEOM_VISUAL_HAS_SPECULAR_COLOR) != 0;
;
visualShape.m_geometry.m_hasLocalMaterial = hasRGBA | hasSpecular;
if (visualShape.m_geometry.m_hasLocalMaterial)
{
if (hasRGBA)
{
visualShape.m_geometry.m_localMaterial.m_matColor.m_rgbaColor.setValue(
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_rgbaColor[0],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_rgbaColor[1],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_rgbaColor[2],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_rgbaColor[3]);
}
else
{
visualShape.m_geometry.m_localMaterial.m_matColor.m_rgbaColor.setValue(1, 1, 1, 1);
}
if (hasSpecular)
{
visualShape.m_geometry.m_localMaterial.m_matColor.m_specularColor.setValue(
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_specularColor[0],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_specularColor[1],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_specularColor[2]);
}
else
{
visualShape.m_geometry.m_localMaterial.m_matColor.m_specularColor.setValue(0.4, 0.4, 0.4);
}
}
if (clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_hasChildTransform != 0)
{
childTrans.setOrigin(btVector3(clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_childPosition[0],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_childPosition[1],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_childPosition[2]));
childTrans.setRotation(btQuaternion(
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_childOrientation[0],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_childOrientation[1],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_childOrientation[2],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_childOrientation[3]));
}
if (visualShapeUniqueId < 0)
{
visualShapeUniqueId = m_data->m_userVisualShapeHandles.allocHandle();
}
InternalVisualShapeHandle* visualHandle = m_data->m_userVisualShapeHandles.getHandle(visualShapeUniqueId);
visualHandle->m_OpenGLGraphicsIndex = -1;
visualHandle->m_tinyRendererVisualShapeIndex = -1;
//tinyrenderer doesn't separate shape versus instance, so create it when creating the multibody instance
//store needed info for tinyrenderer
visualShape.m_linkLocalFrame = childTrans;
visualHandle->m_visualShapes.push_back(visualShape);
visualHandle->m_pathPrefixes.push_back(pathPrefix[0] ? pathPrefix : "");
serverStatusOut.m_createUserShapeResultArgs.m_userShapeUniqueId = visualShapeUniqueId;
serverStatusOut.m_type = CMD_CREATE_VISUAL_SHAPE_COMPLETED;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCustomCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CUSTOM_COMMAND_FAILED;
serverCmd.m_customCommandResultArgs.m_pluginUniqueId = -1;
if (clientCmd.m_updateFlags & CMD_CUSTOM_COMMAND_LOAD_PLUGIN)
{
//pluginPath could be registered or load from disk
const char* postFix = "";
if (clientCmd.m_updateFlags & CMD_CUSTOM_COMMAND_LOAD_PLUGIN_POSTFIX)
{
postFix = clientCmd.m_customCommandArgs.m_postFix;
}
int pluginUniqueId = m_data->m_pluginManager.loadPlugin(clientCmd.m_customCommandArgs.m_pluginPath, postFix);
if (pluginUniqueId >= 0)
{
serverCmd.m_customCommandResultArgs.m_pluginUniqueId = pluginUniqueId;
serverCmd.m_type = CMD_CUSTOM_COMMAND_COMPLETED;
}
}
if (clientCmd.m_updateFlags & CMD_CUSTOM_COMMAND_UNLOAD_PLUGIN)
{
m_data->m_pluginManager.unloadPlugin(clientCmd.m_customCommandArgs.m_pluginUniqueId);
serverCmd.m_type = CMD_CUSTOM_COMMAND_COMPLETED;
}
if (clientCmd.m_updateFlags & CMD_CUSTOM_COMMAND_EXECUTE_PLUGIN_COMMAND)
{
int result = m_data->m_pluginManager.executePluginCommand(clientCmd.m_customCommandArgs.m_pluginUniqueId, &clientCmd.m_customCommandArgs.m_arguments);
serverCmd.m_customCommandResultArgs.m_executeCommandResult = result;
serverCmd.m_type = CMD_CUSTOM_COMMAND_COMPLETED;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processUserDebugDrawCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_USER_DEBUG_DRAW");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_USER_DEBUG_DRAW_FAILED;
int trackingVisualShapeIndex = -1;
if (clientCmd.m_userDebugDrawArgs.m_parentObjectUniqueId >= 0)
{
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(clientCmd.m_userDebugDrawArgs.m_parentObjectUniqueId);
if (bodyHandle)
{
int linkIndex = -1;
if (bodyHandle->m_multiBody)
{
int linkIndex = clientCmd.m_userDebugDrawArgs.m_parentLinkIndex;
if (linkIndex == -1)
{
if (bodyHandle->m_multiBody->getBaseCollider())
{
trackingVisualShapeIndex = bodyHandle->m_multiBody->getBaseCollider()->getUserIndex();
}
}
else
{
if (linkIndex >= 0 && linkIndex < bodyHandle->m_multiBody->getNumLinks())
{
if (bodyHandle->m_multiBody->getLink(linkIndex).m_collider)
{
trackingVisualShapeIndex = bodyHandle->m_multiBody->getLink(linkIndex).m_collider->getUserIndex();
}
}
}
}
if (bodyHandle->m_rigidBody)
{
trackingVisualShapeIndex = bodyHandle->m_rigidBody->getUserIndex();
}
}
}
if (clientCmd.m_updateFlags & USER_DEBUG_ADD_PARAMETER)
{
int uid = m_data->m_guiHelper->addUserDebugParameter(
clientCmd.m_userDebugDrawArgs.m_text,
clientCmd.m_userDebugDrawArgs.m_rangeMin,
clientCmd.m_userDebugDrawArgs.m_rangeMax,
clientCmd.m_userDebugDrawArgs.m_startValue);
serverCmd.m_userDebugDrawArgs.m_debugItemUniqueId = uid;
serverCmd.m_type = CMD_USER_DEBUG_DRAW_COMPLETED;
}
if (clientCmd.m_updateFlags & USER_DEBUG_READ_PARAMETER)
{
int ok = m_data->m_guiHelper->readUserDebugParameter(
clientCmd.m_userDebugDrawArgs.m_itemUniqueId,
&serverCmd.m_userDebugDrawArgs.m_parameterValue);
if (ok)
{
serverCmd.m_type = CMD_USER_DEBUG_DRAW_PARAMETER_COMPLETED;
}
}
if ((clientCmd.m_updateFlags & USER_DEBUG_SET_CUSTOM_OBJECT_COLOR) || (clientCmd.m_updateFlags & USER_DEBUG_REMOVE_CUSTOM_OBJECT_COLOR))
{
int bodyUniqueId = clientCmd.m_userDebugDrawArgs.m_objectUniqueId;
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (body)
{
btCollisionObject* destColObj = 0;
if (body->m_multiBody)
{
if (clientCmd.m_userDebugDrawArgs.m_linkIndex == -1)
{
destColObj = body->m_multiBody->getBaseCollider();
}
else
{
if (clientCmd.m_userDebugDrawArgs.m_linkIndex >= 0 && clientCmd.m_userDebugDrawArgs.m_linkIndex < body->m_multiBody->getNumLinks())
{
destColObj = body->m_multiBody->getLink(clientCmd.m_userDebugDrawArgs.m_linkIndex).m_collider;
}
}
}
if (body->m_rigidBody)
{
destColObj = body->m_rigidBody;
}
if (destColObj)
{
if (clientCmd.m_updateFlags & USER_DEBUG_REMOVE_CUSTOM_OBJECT_COLOR)
{
destColObj->removeCustomDebugColor();
serverCmd.m_type = CMD_USER_DEBUG_DRAW_COMPLETED;
}
if (clientCmd.m_updateFlags & USER_DEBUG_SET_CUSTOM_OBJECT_COLOR)
{
btVector3 objectColorRGB;
objectColorRGB.setValue(clientCmd.m_userDebugDrawArgs.m_objectDebugColorRGB[0],
clientCmd.m_userDebugDrawArgs.m_objectDebugColorRGB[1],
clientCmd.m_userDebugDrawArgs.m_objectDebugColorRGB[2]);
destColObj->setCustomDebugColor(objectColorRGB);
serverCmd.m_type = CMD_USER_DEBUG_DRAW_COMPLETED;
}
}
}
}
if (clientCmd.m_updateFlags & USER_DEBUG_HAS_TEXT)
{
//addUserDebugText3D( const double orientation[4], const double textColorRGB[3], double size, double lifeTime, int trackingObjectUniqueId, int optionFlags){return -1;}
int optionFlags = clientCmd.m_userDebugDrawArgs.m_optionFlags;
if ((clientCmd.m_updateFlags & USER_DEBUG_HAS_TEXT_ORIENTATION) == 0)
{
optionFlags |= DEB_DEBUG_TEXT_ALWAYS_FACE_CAMERA;
}
int replaceItemUniqueId = -1;
if ((clientCmd.m_updateFlags & USER_DEBUG_HAS_REPLACE_ITEM_UNIQUE_ID) != 0)
{
replaceItemUniqueId = clientCmd.m_userDebugDrawArgs.m_replaceItemUniqueId;
}
int uid = m_data->m_guiHelper->addUserDebugText3D(clientCmd.m_userDebugDrawArgs.m_text,
clientCmd.m_userDebugDrawArgs.m_textPositionXYZ,
clientCmd.m_userDebugDrawArgs.m_textOrientation,
clientCmd.m_userDebugDrawArgs.m_textColorRGB,
clientCmd.m_userDebugDrawArgs.m_textSize,
clientCmd.m_userDebugDrawArgs.m_lifeTime,
trackingVisualShapeIndex,
optionFlags,
replaceItemUniqueId);
if (uid >= 0)
{
serverCmd.m_userDebugDrawArgs.m_debugItemUniqueId = uid;
serverCmd.m_type = CMD_USER_DEBUG_DRAW_COMPLETED;
}
}
if (clientCmd.m_updateFlags & USER_DEBUG_HAS_LINE)
{
int replaceItemUid = -1;
if (clientCmd.m_updateFlags & USER_DEBUG_HAS_REPLACE_ITEM_UNIQUE_ID)
{
replaceItemUid = clientCmd.m_userDebugDrawArgs.m_replaceItemUniqueId;
}
int uid = m_data->m_guiHelper->addUserDebugLine(
clientCmd.m_userDebugDrawArgs.m_debugLineFromXYZ,
clientCmd.m_userDebugDrawArgs.m_debugLineToXYZ,
clientCmd.m_userDebugDrawArgs.m_debugLineColorRGB,
clientCmd.m_userDebugDrawArgs.m_lineWidth,
clientCmd.m_userDebugDrawArgs.m_lifeTime,
trackingVisualShapeIndex,
replaceItemUid);
if (uid >= 0)
{
serverCmd.m_userDebugDrawArgs.m_debugItemUniqueId = uid;
serverCmd.m_type = CMD_USER_DEBUG_DRAW_COMPLETED;
}
}
if (clientCmd.m_updateFlags & USER_DEBUG_REMOVE_ALL)
{
m_data->m_guiHelper->removeAllUserDebugItems();
serverCmd.m_type = CMD_USER_DEBUG_DRAW_COMPLETED;
}
if (clientCmd.m_updateFlags & USER_DEBUG_REMOVE_ONE_ITEM)
{
m_data->m_guiHelper->removeUserDebugItem(clientCmd.m_userDebugDrawArgs.m_itemUniqueId);
serverCmd.m_type = CMD_USER_DEBUG_DRAW_COMPLETED;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processSetVRCameraStateCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_SET_VR_CAMERA_STATE");
if (clientCmd.m_updateFlags & VR_CAMERA_ROOT_POSITION)
{
gVRTeleportPos1[0] = clientCmd.m_vrCameraStateArguments.m_rootPosition[0];
gVRTeleportPos1[1] = clientCmd.m_vrCameraStateArguments.m_rootPosition[1];
gVRTeleportPos1[2] = clientCmd.m_vrCameraStateArguments.m_rootPosition[2];
}
if (clientCmd.m_updateFlags & VR_CAMERA_ROOT_ORIENTATION)
{
gVRTeleportOrn[0] = clientCmd.m_vrCameraStateArguments.m_rootOrientation[0];
gVRTeleportOrn[1] = clientCmd.m_vrCameraStateArguments.m_rootOrientation[1];
gVRTeleportOrn[2] = clientCmd.m_vrCameraStateArguments.m_rootOrientation[2];
gVRTeleportOrn[3] = clientCmd.m_vrCameraStateArguments.m_rootOrientation[3];
}
if (clientCmd.m_updateFlags & VR_CAMERA_ROOT_TRACKING_OBJECT)
{
gVRTrackingObjectUniqueId = clientCmd.m_vrCameraStateArguments.m_trackingObjectUniqueId;
}
if (clientCmd.m_updateFlags & VR_CAMERA_FLAG)
{
gVRTrackingObjectFlag = clientCmd.m_vrCameraStateArguments.m_trackingObjectFlag;
}
serverStatusOut.m_type = CMD_CLIENT_COMMAND_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestVREventsCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
//BT_PROFILE("CMD_REQUEST_VR_EVENTS_DATA");
serverStatusOut.m_sendVREvents.m_numVRControllerEvents = 0;
for (int i = 0; i < MAX_VR_CONTROLLERS; i++)
{
b3VRControllerEvent& event = m_data->m_vrControllerEvents.m_vrEvents[i];
if (clientCmd.m_updateFlags & event.m_deviceType)
{
if (event.m_numButtonEvents + event.m_numMoveEvents)
{
serverStatusOut.m_sendVREvents.m_controllerEvents[serverStatusOut.m_sendVREvents.m_numVRControllerEvents++] = event;
event.m_numButtonEvents = 0;
event.m_numMoveEvents = 0;
for (int b = 0; b < MAX_VR_BUTTONS; b++)
{
event.m_buttons[b] = 0;
}
}
}
}
serverStatusOut.m_type = CMD_REQUEST_VR_EVENTS_DATA_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestMouseEventsCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
serverStatusOut.m_sendMouseEvents.m_numMouseEvents = m_data->m_mouseEvents.size();
if (serverStatusOut.m_sendMouseEvents.m_numMouseEvents > MAX_MOUSE_EVENTS)
{
serverStatusOut.m_sendMouseEvents.m_numMouseEvents = MAX_MOUSE_EVENTS;
}
for (int i = 0; i < serverStatusOut.m_sendMouseEvents.m_numMouseEvents; i++)
{
serverStatusOut.m_sendMouseEvents.m_mouseEvents[i] = m_data->m_mouseEvents[i];
}
m_data->m_mouseEvents.resize(0);
serverStatusOut.m_type = CMD_REQUEST_MOUSE_EVENTS_DATA_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestKeyboardEventsCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
//BT_PROFILE("CMD_REQUEST_KEYBOARD_EVENTS_DATA");
bool hasStatus = true;
serverStatusOut.m_sendKeyboardEvents.m_numKeyboardEvents = m_data->m_keyboardEvents.size();
if (serverStatusOut.m_sendKeyboardEvents.m_numKeyboardEvents > MAX_KEYBOARD_EVENTS)
{
serverStatusOut.m_sendKeyboardEvents.m_numKeyboardEvents = MAX_KEYBOARD_EVENTS;
}
for (int i = 0; i < serverStatusOut.m_sendKeyboardEvents.m_numKeyboardEvents; i++)
{
serverStatusOut.m_sendKeyboardEvents.m_keyboardEvents[i] = m_data->m_keyboardEvents[i];
}
btAlignedObjectArray<b3KeyboardEvent> events;
//remove out-of-date events
for (int i = 0; i < m_data->m_keyboardEvents.size(); i++)
{
b3KeyboardEvent event = m_data->m_keyboardEvents[i];
if (event.m_keyState & eButtonIsDown)
{
event.m_keyState = eButtonIsDown;
events.push_back(event);
}
}
m_data->m_keyboardEvents.resize(events.size());
for (int i = 0; i < events.size(); i++)
{
m_data->m_keyboardEvents[i] = events[i];
}
serverStatusOut.m_type = CMD_REQUEST_KEYBOARD_EVENTS_DATA_COMPLETED;
return hasStatus;
}
#if __cplusplus >= 201103L
#include <atomic>
struct CastSyncInfo
{
std::atomic<int> m_nextTaskNumber;
CastSyncInfo() : m_nextTaskNumber(0) {}
inline int getNextTask()
{
return m_nextTaskNumber++;
}
};
#else // __cplusplus >= 201103L
struct CastSyncInfo
{
volatile int m_nextTaskNumber;
btSpinMutex m_taskLock;
CastSyncInfo() : m_nextTaskNumber(0) {}
inline int getNextTask()
{
m_taskLock.lock();
const int taskNr = m_nextTaskNumber++;
m_taskLock.unlock();
return taskNr;
}
};
#endif // __cplusplus >= 201103L
struct BatchRayCaster
{
b3ThreadPool* m_threadPool;
CastSyncInfo* m_syncInfo;
const btCollisionWorld* m_world;
const b3RayData* m_rayInputBuffer;
b3RayHitInfo* m_hitInfoOutputBuffer;
int m_numRays;
BatchRayCaster(b3ThreadPool* threadPool, const btCollisionWorld* world, const b3RayData* rayInputBuffer, b3RayHitInfo* hitInfoOutputBuffer, int numRays)
: m_threadPool(threadPool), m_world(world), m_rayInputBuffer(rayInputBuffer), m_hitInfoOutputBuffer(hitInfoOutputBuffer), m_numRays(numRays)
{
m_syncInfo = new CastSyncInfo;
}
~BatchRayCaster()
{
delete m_syncInfo;
}
void castRays(int numWorkers)
{
#if BT_THREADSAFE
if (numWorkers <= 1)
{
castSequentially();
}
else
{
{
BT_PROFILE("BatchRayCaster_startingWorkerThreads");
int numTasks = btMin(m_threadPool->numWorkers(), numWorkers - 1);
for (int i = 0; i < numTasks; i++)
{
m_threadPool->runTask(i, BatchRayCaster::rayCastWorker, this);
}
}
rayCastWorker(this);
m_threadPool->waitForAllTasks();
}
#else // BT_THREADSAFE
castSequentially();
#endif // BT_THREADSAFE
}
static void rayCastWorker(void* arg)
{
BT_PROFILE("BatchRayCaster_raycastWorker");
BatchRayCaster* const obj = (BatchRayCaster*)arg;
const int numRays = obj->m_numRays;
int taskNr;
while (true)
{
{
BT_PROFILE("CastSyncInfo_getNextTask");
taskNr = obj->m_syncInfo->getNextTask();
}
if (taskNr >= numRays)
return;
obj->processRay(taskNr);
}
}
void castSequentially()
{
for (int i = 0; i < m_numRays; i++)
{
processRay(i);
}
}
void processRay(int ray)
{
BT_PROFILE("BatchRayCaster_processRay");
const double* from = m_rayInputBuffer[ray].m_rayFromPosition;
const double* to = m_rayInputBuffer[ray].m_rayToPosition;
btVector3 rayFromWorld(from[0], from[1], from[2]);
btVector3 rayToWorld(to[0], to[1], to[2]);
btCollisionWorld::ClosestRayResultCallback rayResultCallback(rayFromWorld, rayToWorld);
rayResultCallback.m_flags |= btTriangleRaycastCallback::kF_UseGjkConvexCastRaytest;
m_world->rayTest(rayFromWorld, rayToWorld, rayResultCallback);
b3RayHitInfo& hit = m_hitInfoOutputBuffer[ray];
if (rayResultCallback.hasHit())
{
hit.m_hitFraction = rayResultCallback.m_closestHitFraction;
int objectUniqueId = -1;
int linkIndex = -1;
const btRigidBody* body = btRigidBody::upcast(rayResultCallback.m_collisionObject);
if (body)
{
objectUniqueId = rayResultCallback.m_collisionObject->getUserIndex2();
}
else
{
const btMultiBodyLinkCollider* mblB = btMultiBodyLinkCollider::upcast(rayResultCallback.m_collisionObject);
if (mblB && mblB->m_multiBody)
{
linkIndex = mblB->m_link;
objectUniqueId = mblB->m_multiBody->getUserIndex2();
}
}
hit.m_hitObjectUniqueId = objectUniqueId;
hit.m_hitObjectLinkIndex = linkIndex;
hit.m_hitPositionWorld[0] = rayResultCallback.m_hitPointWorld[0];
hit.m_hitPositionWorld[1] = rayResultCallback.m_hitPointWorld[1];
hit.m_hitPositionWorld[2] = rayResultCallback.m_hitPointWorld[2];
hit.m_hitNormalWorld[0] = rayResultCallback.m_hitNormalWorld[0];
hit.m_hitNormalWorld[1] = rayResultCallback.m_hitNormalWorld[1];
hit.m_hitNormalWorld[2] = rayResultCallback.m_hitNormalWorld[2];
}
else
{
hit.m_hitFraction = 1;
hit.m_hitObjectUniqueId = -1;
hit.m_hitObjectLinkIndex = -1;
hit.m_hitPositionWorld[0] = 0;
hit.m_hitPositionWorld[1] = 0;
hit.m_hitPositionWorld[2] = 0;
hit.m_hitNormalWorld[0] = 0;
hit.m_hitNormalWorld[1] = 0;
hit.m_hitNormalWorld[2] = 0;
}
}
};
void PhysicsServerCommandProcessor::createThreadPool()
{
#ifdef BT_THREADSAFE
if (m_data->m_threadPool == 0)
{
m_data->m_threadPool = new b3ThreadPool("PhysicsServerCommandProcessorThreadPool");
}
#endif //BT_THREADSAFE
}
bool PhysicsServerCommandProcessor::processRequestRaycastIntersectionsCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_RAY_CAST_INTERSECTIONS");
serverStatusOut.m_raycastHits.m_numRaycastHits = 0;
const int numCommandRays = clientCmd.m_requestRaycastIntersections.m_numCommandRays;
const int numStreamingRays = clientCmd.m_requestRaycastIntersections.m_numStreamingRays;
const int totalRays = numCommandRays + numStreamingRays;
int numThreads = clientCmd.m_requestRaycastIntersections.m_numThreads;
if (numThreads == 0)
{
// When 0 is specified, Bullet can decide how many threads to use.
// About 16 rays per thread seems to work reasonably well.
numThreads = btMax(1, totalRays / 16);
}
if (numThreads > 1)
{
createThreadPool();
}
btAlignedObjectArray<b3RayData> rays;
rays.resize(totalRays);
if (numCommandRays)
{
memcpy(&rays[0], &clientCmd.m_requestRaycastIntersections.m_fromToRays[0], numCommandRays * sizeof(b3RayData));
}
if (numStreamingRays)
{
memcpy(&rays[numCommandRays], bufferServerToClient, numStreamingRays * sizeof(b3RayData));
}
if (clientCmd.m_requestRaycastIntersections.m_parentObjectUniqueId >= 0)
{
btTransform tr;
tr.setIdentity();
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(clientCmd.m_requestRaycastIntersections.m_parentObjectUniqueId);
if (bodyHandle)
{
int linkIndex = -1;
if (bodyHandle->m_multiBody)
{
int linkIndex = clientCmd.m_requestRaycastIntersections.m_parentLinkIndex;
if (linkIndex == -1)
{
tr = bodyHandle->m_multiBody->getBaseWorldTransform();
}
else
{
if (linkIndex >= 0 && linkIndex < bodyHandle->m_multiBody->getNumLinks())
{
tr = bodyHandle->m_multiBody->getLink(linkIndex).m_cachedWorldTransform;
}
}
}
if (bodyHandle->m_rigidBody)
{
tr = bodyHandle->m_rigidBody->getWorldTransform();
}
//convert all rays into world space
for (int i = 0; i < totalRays; i++)
{
btVector3 localPosTo(rays[i].m_rayToPosition[0], rays[i].m_rayToPosition[1], rays[i].m_rayToPosition[2]);
btVector3 worldPosTo = tr * localPosTo;
btVector3 localPosFrom(rays[i].m_rayFromPosition[0], rays[i].m_rayFromPosition[1], rays[i].m_rayFromPosition[2]);
btVector3 worldPosFrom = tr * localPosFrom;
rays[i].m_rayFromPosition[0] = worldPosFrom[0];
rays[i].m_rayFromPosition[1] = worldPosFrom[1];
rays[i].m_rayFromPosition[2] = worldPosFrom[2];
rays[i].m_rayToPosition[0] = worldPosTo[0];
rays[i].m_rayToPosition[1] = worldPosTo[1];
rays[i].m_rayToPosition[2] = worldPosTo[2];
}
}
}
BatchRayCaster batchRayCaster(m_data->m_threadPool, m_data->m_dynamicsWorld, &rays[0], (b3RayHitInfo*)bufferServerToClient, totalRays);
batchRayCaster.castRays(numThreads);
serverStatusOut.m_raycastHits.m_numRaycastHits = totalRays;
serverStatusOut.m_type = CMD_REQUEST_RAY_CAST_INTERSECTIONS_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestDebugLinesCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_DEBUG_LINES");
int curFlags = m_data->m_remoteDebugDrawer->getDebugMode();
int debugMode = clientCmd.m_requestDebugLinesArguments.m_debugMode; //clientCmd.btIDebugDraw::DBG_DrawWireframe|btIDebugDraw::DBG_DrawAabb;
int startingLineIndex = clientCmd.m_requestDebugLinesArguments.m_startingLineIndex;
if (startingLineIndex < 0)
{
b3Warning("startingLineIndex should be non-negative");
startingLineIndex = 0;
}
if (clientCmd.m_requestDebugLinesArguments.m_startingLineIndex == 0)
{
m_data->m_remoteDebugDrawer->m_lines2.resize(0);
//|btIDebugDraw::DBG_DrawAabb|
// btIDebugDraw::DBG_DrawConstraints |btIDebugDraw::DBG_DrawConstraintLimits ;
m_data->m_remoteDebugDrawer->setDebugMode(debugMode);
btIDebugDraw* oldDebugDrawer = m_data->m_dynamicsWorld->getDebugDrawer();
m_data->m_dynamicsWorld->setDebugDrawer(m_data->m_remoteDebugDrawer);
m_data->m_dynamicsWorld->debugDrawWorld();
m_data->m_dynamicsWorld->setDebugDrawer(oldDebugDrawer);
m_data->m_remoteDebugDrawer->setDebugMode(curFlags);
}
//9 floats per line: 3 floats for 'from', 3 floats for 'to' and 3 floats for 'color'
int bytesPerLine = (sizeof(float) * 9);
int maxNumLines = bufferSizeInBytes / bytesPerLine - 1;
if (startingLineIndex > m_data->m_remoteDebugDrawer->m_lines2.size())
{
b3Warning("m_startingLineIndex exceeds total number of debug lines");
startingLineIndex = m_data->m_remoteDebugDrawer->m_lines2.size();
}
int numLines = btMin(maxNumLines, m_data->m_remoteDebugDrawer->m_lines2.size() - startingLineIndex);
if (numLines)
{
float* linesFrom = (float*)bufferServerToClient;
float* linesTo = (float*)(bufferServerToClient + numLines * 3 * sizeof(float));
float* linesColor = (float*)(bufferServerToClient + 2 * numLines * 3 * sizeof(float));
for (int i = 0; i < numLines; i++)
{
linesFrom[i * 3] = m_data->m_remoteDebugDrawer->m_lines2[i + startingLineIndex].m_from.x();
linesTo[i * 3] = m_data->m_remoteDebugDrawer->m_lines2[i + startingLineIndex].m_to.x();
linesColor[i * 3] = m_data->m_remoteDebugDrawer->m_lines2[i + startingLineIndex].m_color.x();
linesFrom[i * 3 + 1] = m_data->m_remoteDebugDrawer->m_lines2[i + startingLineIndex].m_from.y();
linesTo[i * 3 + 1] = m_data->m_remoteDebugDrawer->m_lines2[i + startingLineIndex].m_to.y();
linesColor[i * 3 + 1] = m_data->m_remoteDebugDrawer->m_lines2[i + startingLineIndex].m_color.y();
linesFrom[i * 3 + 2] = m_data->m_remoteDebugDrawer->m_lines2[i + startingLineIndex].m_from.z();
linesTo[i * 3 + 2] = m_data->m_remoteDebugDrawer->m_lines2[i + startingLineIndex].m_to.z();
linesColor[i * 3 + 2] = m_data->m_remoteDebugDrawer->m_lines2[i + startingLineIndex].m_color.z();
}
}
serverStatusOut.m_type = CMD_DEBUG_LINES_COMPLETED;
serverStatusOut.m_numDataStreamBytes = numLines * bytesPerLine;
serverStatusOut.m_sendDebugLinesArgs.m_numDebugLines = numLines;
serverStatusOut.m_sendDebugLinesArgs.m_startingLineIndex = startingLineIndex;
serverStatusOut.m_sendDebugLinesArgs.m_numRemainingDebugLines = m_data->m_remoteDebugDrawer->m_lines2.size() - (startingLineIndex + numLines);
return hasStatus;
}
bool PhysicsServerCommandProcessor::processSyncBodyInfoCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_SYNC_BODY_INFO");
b3AlignedObjectArray<int> usedHandles;
m_data->m_bodyHandles.getUsedHandles(usedHandles);
int actualNumBodies = 0;
int* bodyUids = (int*)bufferServerToClient;
for (int i = 0; i < usedHandles.size(); i++)
{
int usedHandle = usedHandles[i];
InternalBodyData* body = m_data->m_bodyHandles.getHandle(usedHandle);
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
if (body && (body->m_multiBody || body->m_rigidBody || body->m_softBody))
#else
if (body && (body->m_multiBody || body->m_rigidBody))
#endif
{
bodyUids[actualNumBodies++] = usedHandle;
}
}
serverStatusOut.m_sdfLoadedArgs.m_numBodies = actualNumBodies;
int usz = m_data->m_userConstraints.size();
int* constraintUid = bodyUids + actualNumBodies;
serverStatusOut.m_sdfLoadedArgs.m_numUserConstraints = usz;
for (int i = 0; i < usz; i++)
{
int key = m_data->m_userConstraints.getKeyAtIndex(i).getUid1();
constraintUid[i] = key;
}
serverStatusOut.m_type = CMD_SYNC_BODY_INFO_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processSyncUserDataCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_SYNC_USER_DATA");
b3AlignedObjectArray<int> userDataHandles;
if (clientCmd.m_syncUserDataRequestArgs.m_numRequestedBodies == 0)
{
m_data->m_userDataHandles.getUsedHandles(userDataHandles);
}
else
{
for (int i=0; i<clientCmd.m_syncUserDataRequestArgs.m_numRequestedBodies; ++i) {
const int bodyUniqueId = clientCmd.m_syncUserDataRequestArgs.m_requestedBodyIds[i];
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (!body)
{
return hasStatus;
}
for (int j=0; j < body->m_userDataHandles.size(); ++j) {
userDataHandles.push_back(body->m_userDataHandles[j]);
}
}
}
if (userDataHandles.size())
{
memcpy(bufferServerToClient, &userDataHandles[0], sizeof(int) * userDataHandles.size());
}
// Only clear the client-side cache when a full sync is requested
serverStatusOut.m_syncUserDataArgs.m_clearCachedUserDataEntries = clientCmd.m_syncUserDataRequestArgs.m_numRequestedBodies == 0;
serverStatusOut.m_syncUserDataArgs.m_numUserDataIdentifiers = userDataHandles.size();
serverStatusOut.m_type = CMD_SYNC_USER_DATA_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestUserDataCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_USER_DATA");
serverStatusOut.m_type = CMD_REQUEST_USER_DATA_FAILED;
SharedMemoryUserData* userData = m_data->m_userDataHandles.getHandle(clientCmd.m_userDataRequestArgs.m_userDataId);
if (!userData)
{
return hasStatus;
}
btAssert(bufferSizeInBytes >= userData->m_bytes.size());
serverStatusOut.m_userDataResponseArgs.m_userDataId = clientCmd.m_userDataRequestArgs.m_userDataId;
serverStatusOut.m_userDataResponseArgs.m_bodyUniqueId = userData->m_bodyUniqueId;
serverStatusOut.m_userDataResponseArgs.m_linkIndex = userData->m_linkIndex;
serverStatusOut.m_userDataResponseArgs.m_visualShapeIndex = userData->m_visualShapeIndex;
serverStatusOut.m_userDataResponseArgs.m_valueType = userData->m_type;
serverStatusOut.m_userDataResponseArgs.m_valueLength = userData->m_bytes.size();
serverStatusOut.m_type = CMD_REQUEST_USER_DATA_COMPLETED;
strcpy(serverStatusOut.m_userDataResponseArgs.m_key, userData->m_key.c_str());
if (userData->m_bytes.size())
{
memcpy(bufferServerToClient, &userData->m_bytes[0], userData->m_bytes.size());
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processAddUserDataCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_ADD_USER_DATA");
serverStatusOut.m_type = CMD_ADD_USER_DATA_FAILED;
const AddUserDataRequestArgs& addUserDataArgs = clientCmd.m_addUserDataRequestArgs;
if (addUserDataArgs.m_bodyUniqueId < 0 || addUserDataArgs.m_bodyUniqueId >= m_data->m_bodyHandles.getNumHandles())
{
return hasStatus;
}
int userDataHandle = addUserData(
addUserDataArgs.m_bodyUniqueId, addUserDataArgs.m_linkIndex,
addUserDataArgs.m_visualShapeIndex, addUserDataArgs.m_key,
bufferServerToClient, addUserDataArgs.m_valueLength,
addUserDataArgs.m_valueType);
if (userDataHandle < 0) {
return hasStatus;
}
serverStatusOut.m_type = CMD_ADD_USER_DATA_COMPLETED;
UserDataResponseArgs& userDataResponseArgs = serverStatusOut.m_userDataResponseArgs;
userDataResponseArgs.m_userDataId = userDataHandle;
userDataResponseArgs.m_bodyUniqueId = addUserDataArgs.m_bodyUniqueId;
userDataResponseArgs.m_linkIndex = addUserDataArgs.m_linkIndex;
userDataResponseArgs.m_visualShapeIndex = addUserDataArgs.m_visualShapeIndex;
userDataResponseArgs.m_valueLength = addUserDataArgs.m_valueLength;
userDataResponseArgs.m_valueType = addUserDataArgs.m_valueType;
strcpy(userDataResponseArgs.m_key, addUserDataArgs.m_key);
b3Notification notification;
notification.m_notificationType = USER_DATA_ADDED;
b3UserDataNotificationArgs& userDataArgs = notification.m_userDataArgs;
userDataArgs.m_userDataId = userDataHandle;
userDataArgs.m_bodyUniqueId = addUserDataArgs.m_bodyUniqueId;
userDataArgs.m_linkIndex = addUserDataArgs.m_linkIndex;
userDataArgs.m_visualShapeIndex = addUserDataArgs.m_visualShapeIndex;
strcpy(userDataArgs.m_key, addUserDataArgs.m_key);
m_data->m_pluginManager.addNotification(notification);
// Keep bufferServerToClient as-is.
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCollisionFilterCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
serverStatusOut.m_type = CMD_CLIENT_COMMAND_COMPLETED;
b3PluginCollisionInterface* collisionInterface = m_data->m_pluginManager.getCollisionInterface();
if (collisionInterface)
{
if (clientCmd.m_updateFlags & B3_COLLISION_FILTER_PAIR)
{
collisionInterface->setBroadphaseCollisionFilter(clientCmd.m_collisionFilterArgs.m_bodyUniqueIdA,
clientCmd.m_collisionFilterArgs.m_bodyUniqueIdB,
clientCmd.m_collisionFilterArgs.m_linkIndexA,
clientCmd.m_collisionFilterArgs.m_linkIndexB,
clientCmd.m_collisionFilterArgs.m_enableCollision);
btAlignedObjectArray<InternalBodyData*> bodies;
//now also 'refresh' the broadphase collision pairs involved
if (clientCmd.m_collisionFilterArgs.m_bodyUniqueIdA >= 0)
{
bodies.push_back(m_data->m_bodyHandles.getHandle(clientCmd.m_collisionFilterArgs.m_bodyUniqueIdA));
}
if (clientCmd.m_collisionFilterArgs.m_bodyUniqueIdB >= 0)
{
bodies.push_back(m_data->m_bodyHandles.getHandle(clientCmd.m_collisionFilterArgs.m_bodyUniqueIdB));
}
for (int i = 0; i < bodies.size(); i++)
{
InternalBodyData* body = bodies[i];
if (body)
{
if (body->m_multiBody)
{
if (body->m_multiBody->getBaseCollider())
{
m_data->m_dynamicsWorld->refreshBroadphaseProxy(body->m_multiBody->getBaseCollider());
}
for (int i = 0; i < body->m_multiBody->getNumLinks(); i++)
{
if (body->m_multiBody->getLinkCollider(i))
{
m_data->m_dynamicsWorld->refreshBroadphaseProxy(body->m_multiBody->getLinkCollider(i));
}
}
}
else
{
//btRigidBody case
if (body->m_rigidBody)
{
m_data->m_dynamicsWorld->refreshBroadphaseProxy(body->m_rigidBody);
}
}
}
}
}
if (clientCmd.m_updateFlags & B3_COLLISION_FILTER_GROUP_MASK)
{
InternalBodyData* body = m_data->m_bodyHandles.getHandle(clientCmd.m_collisionFilterArgs.m_bodyUniqueIdA);
btCollisionObject* colObj = 0;
if (body->m_multiBody)
{
if (clientCmd.m_collisionFilterArgs.m_linkIndexA == -1)
{
colObj = body->m_multiBody->getBaseCollider();
}
else
{
if (clientCmd.m_collisionFilterArgs.m_linkIndexA >= 0 && clientCmd.m_collisionFilterArgs.m_linkIndexA < body->m_multiBody->getNumLinks())
{
colObj = body->m_multiBody->getLinkCollider(clientCmd.m_collisionFilterArgs.m_linkIndexA);
}
}
}
else
{
if (body->m_rigidBody)
{
colObj = body->m_rigidBody;
}
}
if (colObj)
{
colObj->getBroadphaseHandle()->m_collisionFilterGroup = clientCmd.m_collisionFilterArgs.m_collisionFilterGroup;
colObj->getBroadphaseHandle()->m_collisionFilterMask = clientCmd.m_collisionFilterArgs.m_collisionFilterMask;
m_data->m_dynamicsWorld->refreshBroadphaseProxy(colObj);
}
}
}
return true;
}
bool PhysicsServerCommandProcessor::processRemoveUserDataCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REMOVE_USER_DATA");
serverStatusOut.m_type = CMD_REMOVE_USER_DATA_FAILED;
SharedMemoryUserData* userData = m_data->m_userDataHandles.getHandle(clientCmd.m_removeUserDataRequestArgs.m_userDataId);
if (!userData)
{
return hasStatus;
}
InternalBodyData* body = m_data->m_bodyHandles.getHandle(userData->m_bodyUniqueId);
if (!body)
{
return hasStatus;
}
body->m_userDataHandles.remove(clientCmd.m_removeUserDataRequestArgs.m_userDataId);
b3Notification notification;
notification.m_notificationType = USER_DATA_REMOVED;
b3UserDataNotificationArgs& userDataArgs = notification.m_userDataArgs;
userDataArgs.m_userDataId = clientCmd.m_removeUserDataRequestArgs.m_userDataId;
userDataArgs.m_bodyUniqueId = userData->m_bodyUniqueId;
userDataArgs.m_linkIndex = userData->m_linkIndex;
userDataArgs.m_visualShapeIndex = userData->m_visualShapeIndex;
strcpy(userDataArgs.m_key, userData->m_key.c_str());
m_data->m_userDataHandleLookup.remove(SharedMemoryUserDataHashKey(userData));
m_data->m_userDataHandles.freeHandle(clientCmd.m_removeUserDataRequestArgs.m_userDataId);
serverStatusOut.m_removeUserDataResponseArgs = clientCmd.m_removeUserDataRequestArgs;
serverStatusOut.m_type = CMD_REMOVE_USER_DATA_COMPLETED;
m_data->m_pluginManager.addNotification(notification);
return hasStatus;
}
bool PhysicsServerCommandProcessor::processSendDesiredStateCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_SEND_DESIRED_STATE");
if (m_data->m_verboseOutput)
{
b3Printf("Processed CMD_SEND_DESIRED_STATE");
}
int bodyUniqueId = clientCmd.m_sendDesiredStateCommandArgument.m_bodyUniqueId;
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (body && body->m_multiBody)
{
btMultiBody* mb = body->m_multiBody;
btAssert(mb);
switch (clientCmd.m_sendDesiredStateCommandArgument.m_controlMode)
{
case CONTROL_MODE_PD:
{
if (m_data->m_verboseOutput)
{
b3Printf("Using CONTROL_MODE_PD");
}
b3PluginArguments args;
args.m_ints[1] = bodyUniqueId;
//find the joint motors and apply the desired velocity and maximum force/torque
{
args.m_numInts = 0;
args.m_numFloats = 0;
//syncBodies is expensive/slow, use it only once
m_data->m_pluginManager.executePluginCommand(m_data->m_pdControlPlugin, &args);
int velIndex = 6; //skip the 3 linear + 3 angular degree of freedom velocity entries of the base
int posIndex = 7; //skip 3 positional and 4 orientation (quaternion) positional degrees of freedom of the base
for (int link = 0; link < mb->getNumLinks(); link++)
{
if (supportsJointMotor(mb, link))
{
bool hasDesiredPosOrVel = false;
btScalar desiredVelocity = 0.f;
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_QDOT) != 0)
{
hasDesiredPosOrVel = true;
desiredVelocity = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQdot[velIndex];
args.m_floats[2] = 0.1; // kd
}
btScalar desiredPosition = 0.f;
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[posIndex] & SIM_DESIRED_STATE_HAS_Q) != 0)
{
hasDesiredPosOrVel = true;
desiredPosition = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQ[posIndex];
args.m_floats[3] = 0.1; // kp
}
if (hasDesiredPosOrVel)
{
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_KP) != 0)
{
args.m_floats[3] = clientCmd.m_sendDesiredStateCommandArgument.m_Kp[velIndex];
}
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_KD) != 0)
{
args.m_floats[2] = clientCmd.m_sendDesiredStateCommandArgument.m_Kd[velIndex];
}
args.m_floats[1] = desiredVelocity;
//clamp position
if (mb->getLink(link).m_jointLowerLimit <= mb->getLink(link).m_jointUpperLimit)
{
btClamp(desiredPosition, mb->getLink(link).m_jointLowerLimit, mb->getLink(link).m_jointUpperLimit);
}
args.m_floats[0] = desiredPosition;
btScalar maxImp = 1000000.f;
if ((clientCmd.m_updateFlags & SIM_DESIRED_STATE_HAS_MAX_FORCE) != 0)
maxImp = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateForceTorque[velIndex];
args.m_floats[4] = maxImp;
args.m_ints[2] = link;
args.m_numInts = 3;
args.m_numFloats = 5;
args.m_ints[0] = eSetPDControl;
if (args.m_floats[4] < B3_EPSILON)
{
args.m_ints[0] = eRemovePDControl;
}
m_data->m_pluginManager.executePluginCommand(m_data->m_pdControlPlugin, &args);
}
}
velIndex += mb->getLink(link).m_dofCount;
posIndex += mb->getLink(link).m_posVarCount;
}
}
break;
}
case CONTROL_MODE_TORQUE:
{
if (m_data->m_verboseOutput)
{
b3Printf("Using CONTROL_MODE_TORQUE");
}
// mb->clearForcesAndTorques();
int torqueIndex = 6;
if ((clientCmd.m_updateFlags & SIM_DESIRED_STATE_HAS_MAX_FORCE) != 0)
{
for (int link = 0; link < mb->getNumLinks(); link++)
{
for (int dof = 0; dof < mb->getLink(link).m_dofCount; dof++)
{
double torque = 0.f;
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[torqueIndex] & SIM_DESIRED_STATE_HAS_MAX_FORCE) != 0)
{
torque = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateForceTorque[torqueIndex];
mb->addJointTorqueMultiDof(link, dof, torque);
}
torqueIndex++;
}
}
}
break;
}
case CONTROL_MODE_VELOCITY:
{
if (m_data->m_verboseOutput)
{
b3Printf("Using CONTROL_MODE_VELOCITY");
}
int numMotors = 0;
//find the joint motors and apply the desired velocity and maximum force/torque
{
int dofIndex = 6; //skip the 3 linear + 3 angular degree of freedom entries of the base
for (int link = 0; link < mb->getNumLinks(); link++)
{
if (supportsJointMotor(mb, link))
{
btMultiBodyJointMotor* motor = (btMultiBodyJointMotor*)mb->getLink(link).m_userPtr;
if (motor)
{
btScalar desiredVelocity = 0.f;
bool hasDesiredVelocity = false;
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[dofIndex] & SIM_DESIRED_STATE_HAS_QDOT) != 0)
{
desiredVelocity = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQdot[dofIndex];
btScalar kd = 0.1f;
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[dofIndex] & SIM_DESIRED_STATE_HAS_KD) != 0)
{
kd = clientCmd.m_sendDesiredStateCommandArgument.m_Kd[dofIndex];
}
motor->setVelocityTarget(desiredVelocity, kd);
btScalar kp = 0.f;
motor->setPositionTarget(0, kp);
hasDesiredVelocity = true;
}
if (hasDesiredVelocity)
{
//disable velocity clamp in velocity mode
motor->setRhsClamp(SIMD_INFINITY);
btScalar maxImp = 1000000.f * m_data->m_physicsDeltaTime;
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[dofIndex] & SIM_DESIRED_STATE_HAS_MAX_FORCE) != 0)
{
maxImp = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateForceTorque[dofIndex] * m_data->m_physicsDeltaTime;
}
motor->setMaxAppliedImpulse(maxImp);
}
numMotors++;
}
}
dofIndex += mb->getLink(link).m_dofCount;
}
}
break;
}
case CONTROL_MODE_POSITION_VELOCITY_PD:
{
if (m_data->m_verboseOutput)
{
b3Printf("Using CONTROL_MODE_POSITION_VELOCITY_PD");
}
//compute the force base on PD control
int numMotors = 0;
//find the joint motors and apply the desired velocity and maximum force/torque
{
int velIndex = 6; //skip the 3 linear + 3 angular degree of freedom velocity entries of the base
int posIndex = 7; //skip 3 positional and 4 orientation (quaternion) positional degrees of freedom of the base
for (int link = 0; link < mb->getNumLinks(); link++)
{
if (supportsJointMotor(mb, link))
{
btMultiBodyJointMotor* motor = (btMultiBodyJointMotor*)mb->getLink(link).m_userPtr;
if (motor)
{
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_RHS_CLAMP) != 0)
{
motor->setRhsClamp(clientCmd.m_sendDesiredStateCommandArgument.m_rhsClamp[velIndex]);
}
bool hasDesiredPosOrVel = false;
btScalar kp = 0.f;
btScalar kd = 0.f;
btScalar desiredVelocity = 0.f;
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_QDOT) != 0)
{
hasDesiredPosOrVel = true;
desiredVelocity = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQdot[velIndex];
kd = 0.1;
}
btScalar desiredPosition = 0.f;
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[posIndex] & SIM_DESIRED_STATE_HAS_Q) != 0)
{
hasDesiredPosOrVel = true;
desiredPosition = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQ[posIndex];
kp = 0.1;
}
if (hasDesiredPosOrVel)
{
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_KP) != 0)
{
kp = clientCmd.m_sendDesiredStateCommandArgument.m_Kp[velIndex];
}
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_KD) != 0)
{
kd = clientCmd.m_sendDesiredStateCommandArgument.m_Kd[velIndex];
}
motor->setVelocityTarget(desiredVelocity, kd);
//todo: instead of clamping, combine the motor and limit
//and combine handling of limit force and motor force.
//clamp position
if (mb->getLink(link).m_jointLowerLimit <= mb->getLink(link).m_jointUpperLimit)
{
btClamp(desiredPosition, mb->getLink(link).m_jointLowerLimit, mb->getLink(link).m_jointUpperLimit);
}
motor->setPositionTarget(desiredPosition, kp);
btScalar maxImp = 1000000.f * m_data->m_physicsDeltaTime;
if ((clientCmd.m_updateFlags & SIM_DESIRED_STATE_HAS_MAX_FORCE) != 0)
maxImp = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateForceTorque[velIndex] * m_data->m_physicsDeltaTime;
motor->setMaxAppliedImpulse(maxImp);
}
numMotors++;
}
}
if (mb->getLink(link).m_jointType == btMultibodyLink::eSpherical)
{
btMultiBodySphericalJointMotor* motor = (btMultiBodySphericalJointMotor*)mb->getLink(link).m_userPtr;
if (motor)
{
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_RHS_CLAMP) != 0)
{
motor->setRhsClamp(clientCmd.m_sendDesiredStateCommandArgument.m_rhsClamp[velIndex]);
}
bool hasDesiredPosOrVel = false;
btScalar kp = 0.f;
btScalar kd = 0.f;
btVector3 desiredVelocity(0, 0, 0);
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_QDOT) != 0)
{
hasDesiredPosOrVel = true;
desiredVelocity.setValue(
clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQdot[velIndex + 0],
clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQdot[velIndex + 1],
clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQdot[velIndex + 2]);
kd = 0.1;
}
btQuaternion desiredPosition(0, 0, 0, 1);
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[posIndex] & SIM_DESIRED_STATE_HAS_Q) != 0)
{
hasDesiredPosOrVel = true;
desiredPosition.setValue(
clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQ[posIndex + 0],
clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQ[posIndex + 1],
clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQ[posIndex + 2],
clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQ[posIndex + 3]);
kp = 0.1;
}
if (hasDesiredPosOrVel)
{
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_KP) != 0)
{
kp = clientCmd.m_sendDesiredStateCommandArgument.m_Kp[velIndex];
}
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_KD) != 0)
{
kd = clientCmd.m_sendDesiredStateCommandArgument.m_Kd[velIndex];
}
motor->setVelocityTarget(desiredVelocity, kd);
//todo: instead of clamping, combine the motor and limit
//and combine handling of limit force and motor force.
//clamp position
//if (mb->getLink(link).m_jointLowerLimit <= mb->getLink(link).m_jointUpperLimit)
//{
// btClamp(desiredPosition, mb->getLink(link).m_jointLowerLimit, mb->getLink(link).m_jointUpperLimit);
//}
motor->setPositionTarget(desiredPosition, kp);
btScalar maxImp = 1000000.f * m_data->m_physicsDeltaTime;
if ((clientCmd.m_updateFlags & SIM_DESIRED_STATE_HAS_MAX_FORCE) != 0)
maxImp = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateForceTorque[velIndex] * m_data->m_physicsDeltaTime;
motor->setMaxAppliedImpulse(maxImp);
}
numMotors++;
}
}
velIndex += mb->getLink(link).m_dofCount;
posIndex += mb->getLink(link).m_posVarCount;
}
}
break;
}
#ifdef STATIC_LINK_SPD_PLUGIN
case CONTROL_MODE_STABLE_PD:
{
int posVal = body->m_multiBody->getNumPosVars();
btAlignedObjectArray<double> zeroVel;
int dof = 7 + posVal;
zeroVel.resize(dof);
//clientCmd.m_sendDesiredStateCommandArgument.
//current positions and velocities
btAlignedObjectArray<double> jointPositionsQ;
btAlignedObjectArray<double> jointVelocitiesQdot;
btTransform baseTr = body->m_multiBody->getBaseWorldTransform();
#if 1
jointPositionsQ.push_back(baseTr.getOrigin()[0]);
jointPositionsQ.push_back(baseTr.getOrigin()[1]);
jointPositionsQ.push_back(baseTr.getOrigin()[2]);
jointPositionsQ.push_back(baseTr.getRotation()[0]);
jointPositionsQ.push_back(baseTr.getRotation()[1]);
jointPositionsQ.push_back(baseTr.getRotation()[2]);
jointPositionsQ.push_back(baseTr.getRotation()[3]);
jointVelocitiesQdot.push_back(body->m_multiBody->getBaseVel()[0]);
jointVelocitiesQdot.push_back(body->m_multiBody->getBaseVel()[1]);
jointVelocitiesQdot.push_back(body->m_multiBody->getBaseVel()[2]);
jointVelocitiesQdot.push_back(body->m_multiBody->getBaseOmega()[0]);
jointVelocitiesQdot.push_back(body->m_multiBody->getBaseOmega()[1]);
jointVelocitiesQdot.push_back(body->m_multiBody->getBaseOmega()[2]);
jointVelocitiesQdot.push_back(0);
#else
for (int i = 0; i < 7; i++)
{
jointPositionsQ.push_back(0);
jointVelocitiesQdot.push_back(0);
}
jointPositionsQ[6] = 1;
#endif
for (int i = 0; i < body->m_multiBody->getNumLinks(); i++)
{
switch (body->m_multiBody->getLink(i).m_jointType)
{
case btMultibodyLink::eSpherical:
{
btScalar* jointPos = body->m_multiBody->getJointPosMultiDof(i);
jointPositionsQ.push_back(jointPos[0]);
jointPositionsQ.push_back(jointPos[1]);
jointPositionsQ.push_back(jointPos[2]);
jointPositionsQ.push_back(jointPos[3]);
btScalar* jointVel = body->m_multiBody->getJointVelMultiDof(i);
jointVelocitiesQdot.push_back(jointVel[0]);
jointVelocitiesQdot.push_back(jointVel[1]);
jointVelocitiesQdot.push_back(jointVel[2]);
jointVelocitiesQdot.push_back(0);
break;
}
case btMultibodyLink::ePrismatic:
case btMultibodyLink::eRevolute:
{
btScalar* jointPos = body->m_multiBody->getJointPosMultiDof(i);
jointPositionsQ.push_back(jointPos[0]);
btScalar* jointVel = body->m_multiBody->getJointVelMultiDof(i);
jointVelocitiesQdot.push_back(jointVel[0]);
break;
}
case btMultibodyLink::eFixed:
{
//skip
break;
}
default:
{
b3Error("Unsupported joint type");
btAssert(0);
}
}
}
cRBDModel* rbdModel = 0;
{
BT_PROFILE("findOrCreateRBDModel");
rbdModel = m_data->findOrCreateRBDModel(body->m_multiBody, &jointPositionsQ[0], &jointVelocitiesQdot[0]);
}
if (rbdModel)
{
int num_dof = jointPositionsQ.size();
const Eigen::VectorXd& pose = rbdModel->GetPose();
const Eigen::VectorXd& vel = rbdModel->GetVel();
Eigen::Map<Eigen::VectorXd> mKp((double*)clientCmd.m_sendDesiredStateCommandArgument.m_Kp, num_dof);
Eigen::Map<Eigen::VectorXd> mKd((double*)clientCmd.m_sendDesiredStateCommandArgument.m_Kd, num_dof);
Eigen::Map<Eigen::VectorXd> maxForce((double*)clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateForceTorque, num_dof);
Eigen::DiagonalMatrix<double, Eigen::Dynamic> Kp_mat = mKp.asDiagonal();
Eigen::DiagonalMatrix<double, Eigen::Dynamic> Kd_mat = mKd.asDiagonal();
Eigen::MatrixXd M = rbdModel->GetMassMat();
//rbdModel->UpdateBiasForce();
const Eigen::VectorXd& C = rbdModel->GetBiasForce();
M.diagonal() += m_data->m_physicsDeltaTime * mKd;
Eigen::VectorXd pose_inc;
const Eigen::MatrixXd& joint_mat = rbdModel->GetJointMat();
{
BT_PROFILE("cKinTree::VelToPoseDiff");
cKinTree::VelToPoseDiff(joint_mat, rbdModel->GetPose(), rbdModel->GetVel(), pose_inc);
}
//tar_pose needs to be reshuffled?
Eigen::VectorXd tar_pose, tar_vel;
{
BT_PROFILE("convertPose");
PhysicsServerCommandProcessorInternalData::convertPose(body->m_multiBody,
(double*)clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQ,
(double*)clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQdot,
tar_pose, tar_vel);
}
pose_inc = pose + m_data->m_physicsDeltaTime * pose_inc;
{
BT_PROFILE("cKinTree::PostProcessPose");
cKinTree::PostProcessPose(joint_mat, pose_inc);
}
Eigen::VectorXd pose_err;
{
BT_PROFILE("cKinTree::CalcVel");
cKinTree::CalcVel(joint_mat, pose_inc, tar_pose, 1, pose_err);
}
for (int i = 0; i < 7; i++)
{
pose_err[i] = 0;
}
Eigen::VectorXd vel_err = tar_vel - vel;
Eigen::VectorXd acc;
{
BT_PROFILE("acc");
acc = Kp_mat * pose_err + Kd_mat * vel_err - C;
}
{
BT_PROFILE("M.ldlt().solve");
acc = M.ldlt().solve(acc);
}
Eigen::VectorXd out_tau = Eigen::VectorXd::Zero(num_dof);
out_tau += Kp_mat * pose_err + Kd_mat * (vel_err - m_data->m_physicsDeltaTime * acc);
//clamp the forces
out_tau = out_tau.cwiseMax(-maxForce);
out_tau = out_tau.cwiseMin(maxForce);
//apply the forces
int torqueIndex = 7;
for (int link = 0; link < mb->getNumLinks(); link++)
{
int dofCount = mb->getLink(link).m_dofCount;
int dofOffset = mb->getLink(link).m_dofOffset;
if (dofCount == 3)
{
for (int dof = 0; dof < 3; dof++)
{
double torque = out_tau[torqueIndex + dof];
mb->addJointTorqueMultiDof(link, dof, torque);
}
torqueIndex += 4;
}
if (dofCount == 1)
{
double torque = out_tau[torqueIndex];
mb->addJointTorqueMultiDof(link, 0, torque);
torqueIndex++;
}
}
}
break;
}
#endif
default:
{
b3Warning("m_controlMode not implemented yet");
break;
}
}
}
else
{
//support for non-btMultiBody, such as btRigidBody
if (body && body->m_rigidBody)
{
btRigidBody* rb = body->m_rigidBody;
btAssert(rb);
//switch (clientCmd.m_sendDesiredStateCommandArgument.m_controlMode)
{
//case CONTROL_MODE_TORQUE:
{
if (m_data->m_verboseOutput)
{
b3Printf("Using CONTROL_MODE_TORQUE");
}
// mb->clearForcesAndTorques();
///see addJointInfoFromConstraint
int velIndex = 6;
int posIndex = 7;
//if ((clientCmd.m_updateFlags&SIM_DESIRED_STATE_HAS_MAX_FORCE)!=0)
{
for (int link = 0; link < body->m_rigidBodyJoints.size(); link++)
{
btGeneric6DofSpring2Constraint* con = body->m_rigidBodyJoints[link];
btVector3 linearLowerLimit;
btVector3 linearUpperLimit;
btVector3 angularLowerLimit;
btVector3 angularUpperLimit;
//for (int dof=0;dof<mb->getLink(link).m_dofCount;dof++)
{
{
int torqueIndex = velIndex;
double torque = 100;
bool hasDesiredTorque = false;
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_MAX_FORCE) != 0)
{
torque = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateForceTorque[velIndex];
hasDesiredTorque = true;
}
bool hasDesiredPosOrVel = false;
btScalar qdotTarget = 0.f;
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_QDOT) != 0)
{
hasDesiredPosOrVel = true;
qdotTarget = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQdot[velIndex];
}
btScalar qTarget = 0.f;
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[posIndex] & SIM_DESIRED_STATE_HAS_Q) != 0)
{
hasDesiredPosOrVel = true;
qTarget = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQ[posIndex];
}
con->getLinearLowerLimit(linearLowerLimit);
con->getLinearUpperLimit(linearUpperLimit);
con->getAngularLowerLimit(angularLowerLimit);
con->getAngularUpperLimit(angularUpperLimit);
if (linearLowerLimit.isZero() && linearUpperLimit.isZero() && angularLowerLimit.isZero() && angularUpperLimit.isZero())
{
//fixed, don't do anything
}
else
{
con->calculateTransforms();
if (linearLowerLimit.isZero() && linearUpperLimit.isZero())
{
//eRevoluteType;
btVector3 limitRange = angularLowerLimit.absolute() + angularUpperLimit.absolute();
int limitAxis = limitRange.maxAxis();
const btTransform& transA = con->getCalculatedTransformA();
const btTransform& transB = con->getCalculatedTransformB();
btVector3 axisA = transA.getBasis().getColumn(limitAxis);
btVector3 axisB = transB.getBasis().getColumn(limitAxis);
switch (clientCmd.m_sendDesiredStateCommandArgument.m_controlMode)
{
case CONTROL_MODE_TORQUE:
{
if (hasDesiredTorque)
{
con->getRigidBodyA().applyTorque(torque * axisA);
con->getRigidBodyB().applyTorque(-torque * axisB);
}
break;
}
case CONTROL_MODE_VELOCITY:
{
if (hasDesiredPosOrVel)
{
con->enableMotor(3 + limitAxis, true);
con->setTargetVelocity(3 + limitAxis, qdotTarget);
con->setMaxMotorForce(3 + limitAxis, torque);
}
break;
}
case CONTROL_MODE_POSITION_VELOCITY_PD:
{
if (hasDesiredPosOrVel)
{
con->setServo(3 + limitAxis, true);
con->setServoTarget(3 + limitAxis, -qTarget);
//next one is the maximum velocity to reach target position.
//the maximum velocity is limited by maxMotorForce
con->setTargetVelocity(3 + limitAxis, 100);
con->setMaxMotorForce(3 + limitAxis, torque);
con->enableMotor(3 + limitAxis, true);
}
break;
}
default:
{
}
};
}
else
{
//ePrismaticType; @todo
btVector3 limitRange = linearLowerLimit.absolute() + linearUpperLimit.absolute();
int limitAxis = limitRange.maxAxis();
const btTransform& transA = con->getCalculatedTransformA();
const btTransform& transB = con->getCalculatedTransformB();
btVector3 axisA = transA.getBasis().getColumn(limitAxis);
btVector3 axisB = transB.getBasis().getColumn(limitAxis);
switch (clientCmd.m_sendDesiredStateCommandArgument.m_controlMode)
{
case CONTROL_MODE_TORQUE:
{
con->getRigidBodyA().applyForce(-torque * axisA, btVector3(0, 0, 0));
con->getRigidBodyB().applyForce(torque * axisB, btVector3(0, 0, 0));
break;
}
case CONTROL_MODE_VELOCITY:
{
con->enableMotor(limitAxis, true);
con->setTargetVelocity(limitAxis, -qdotTarget);
con->setMaxMotorForce(limitAxis, torque);
break;
}
case CONTROL_MODE_POSITION_VELOCITY_PD:
{
con->setServo(limitAxis, true);
con->setServoTarget(limitAxis, qTarget);
//next one is the maximum velocity to reach target position.
//the maximum velocity is limited by maxMotorForce
con->setTargetVelocity(limitAxis, 100);
con->setMaxMotorForce(limitAxis, torque);
con->enableMotor(limitAxis, true);
break;
}
default:
{
}
};
}
}
} //fi
///see addJointInfoFromConstraint
velIndex++; //info.m_uIndex
posIndex++; //info.m_qIndex
}
}
} //fi
//break;
}
}
} //if (body && body->m_rigidBody)
}
serverStatusOut.m_type = CMD_DESIRED_STATE_RECEIVED_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestActualStateCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
serverStatusOut.m_type = CMD_ACTUAL_STATE_UPDATE_FAILED;
BT_PROFILE("CMD_REQUEST_ACTUAL_STATE");
if (m_data->m_verboseOutput)
{
b3Printf("Sending the actual state (Q,U)");
}
int bodyUniqueId = clientCmd.m_requestActualStateInformationCommandArgument.m_bodyUniqueId;
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
//we store the state details in the shared memory block, to reduce status size
SendActualStateSharedMemoryStorage* stateDetails = (SendActualStateSharedMemoryStorage*)bufferServerToClient;
//make sure the storage fits, otherwise
btAssert(sizeof(SendActualStateSharedMemoryStorage) < bufferSizeInBytes);
if (sizeof(SendActualStateSharedMemoryStorage) > bufferSizeInBytes)
{
//this forces an error report
body = 0;
}
if (body && body->m_multiBody)
{
btMultiBody* mb = body->m_multiBody;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverStatusOut.m_type = CMD_ACTUAL_STATE_UPDATE_COMPLETED;
serverCmd.m_sendActualStateArgs.m_bodyUniqueId = bodyUniqueId;
serverCmd.m_sendActualStateArgs.m_numLinks = body->m_multiBody->getNumLinks();
serverCmd.m_numDataStreamBytes = sizeof(SendActualStateSharedMemoryStorage);
serverCmd.m_sendActualStateArgs.m_stateDetails = 0;
int totalDegreeOfFreedomQ = 0;
int totalDegreeOfFreedomU = 0;
if (mb->getNumLinks() >= MAX_DEGREE_OF_FREEDOM)
{
serverStatusOut.m_type = CMD_ACTUAL_STATE_UPDATE_FAILED;
hasStatus = true;
return hasStatus;
}
//always add the base, even for static (non-moving objects)
//so that we can easily move the 'fixed' base when needed
//do we don't use this conditional "if (!mb->hasFixedBase())"
{
btTransform tr;
tr.setOrigin(mb->getBasePos());
tr.setRotation(mb->getWorldToBaseRot().inverse());
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[0] =
body->m_rootLocalInertialFrame.getOrigin()[0];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[1] =
body->m_rootLocalInertialFrame.getOrigin()[1];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[2] =
body->m_rootLocalInertialFrame.getOrigin()[2];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[3] =
body->m_rootLocalInertialFrame.getRotation()[0];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[4] =
body->m_rootLocalInertialFrame.getRotation()[1];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[5] =
body->m_rootLocalInertialFrame.getRotation()[2];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[6] =
body->m_rootLocalInertialFrame.getRotation()[3];
//base position in world space, cartesian
stateDetails->m_actualStateQ[0] = tr.getOrigin()[0];
stateDetails->m_actualStateQ[1] = tr.getOrigin()[1];
stateDetails->m_actualStateQ[2] = tr.getOrigin()[2];
//base orientation, quaternion x,y,z,w, in world space, cartesian
stateDetails->m_actualStateQ[3] = tr.getRotation()[0];
stateDetails->m_actualStateQ[4] = tr.getRotation()[1];
stateDetails->m_actualStateQ[5] = tr.getRotation()[2];
stateDetails->m_actualStateQ[6] = tr.getRotation()[3];
totalDegreeOfFreedomQ += 7; //pos + quaternion
//base linear velocity (in world space, cartesian)
stateDetails->m_actualStateQdot[0] = mb->getBaseVel()[0];
stateDetails->m_actualStateQdot[1] = mb->getBaseVel()[1];
stateDetails->m_actualStateQdot[2] = mb->getBaseVel()[2];
//base angular velocity (in world space, cartesian)
stateDetails->m_actualStateQdot[3] = mb->getBaseOmega()[0];
stateDetails->m_actualStateQdot[4] = mb->getBaseOmega()[1];
stateDetails->m_actualStateQdot[5] = mb->getBaseOmega()[2];
totalDegreeOfFreedomU += 6; //3 linear and 3 angular DOF
}
btAlignedObjectArray<btVector3> omega;
btAlignedObjectArray<btVector3> linVel;
bool computeForwardKinematics = ((clientCmd.m_updateFlags & ACTUAL_STATE_COMPUTE_FORWARD_KINEMATICS) != 0);
if (computeForwardKinematics)
{
B3_PROFILE("compForwardKinematics");
btAlignedObjectArray<btQuaternion> world_to_local;
btAlignedObjectArray<btVector3> local_origin;
world_to_local.resize(mb->getNumLinks() + 1);
local_origin.resize(mb->getNumLinks() + 1);
mb->forwardKinematics(world_to_local, local_origin);
}
bool computeLinkVelocities = ((clientCmd.m_updateFlags & ACTUAL_STATE_COMPUTE_LINKVELOCITY) != 0);
if (computeLinkVelocities)
{
omega.resize(mb->getNumLinks() + 1);
linVel.resize(mb->getNumLinks() + 1);
{
B3_PROFILE("compTreeLinkVelocities");
mb->compTreeLinkVelocities(&omega[0], &linVel[0]);
}
}
for (int l = 0; l < mb->getNumLinks(); l++)
{
for (int d = 0; d < mb->getLink(l).m_posVarCount; d++)
{
stateDetails->m_actualStateQ[totalDegreeOfFreedomQ++] = mb->getJointPosMultiDof(l)[d];
}
for (int d = 0; d < mb->getLink(l).m_dofCount; d++)
{
stateDetails->m_jointMotorForce[totalDegreeOfFreedomU] = 0;
if (mb->getLink(l).m_jointType == btMultibodyLink::eSpherical)
{
btMultiBodySphericalJointMotor* motor = (btMultiBodySphericalJointMotor*)mb->getLink(l).m_userPtr;
if (motor)
{
btScalar impulse = motor->getAppliedImpulse(d);
btScalar force = impulse / m_data->m_physicsDeltaTime;
stateDetails->m_jointMotorForceMultiDof[totalDegreeOfFreedomU] = force;
}
}
else
{
if (supportsJointMotor(mb, l))
{
btMultiBodyJointMotor* motor = (btMultiBodyJointMotor*)body->m_multiBody->getLink(l).m_userPtr;
if (motor && m_data->m_physicsDeltaTime > btScalar(0))
{
btScalar force = motor->getAppliedImpulse(0) / m_data->m_physicsDeltaTime;
stateDetails->m_jointMotorForceMultiDof[totalDegreeOfFreedomU] = force;
}
}
}
stateDetails->m_actualStateQdot[totalDegreeOfFreedomU++] = mb->getJointVelMultiDof(l)[d];
}
if (0 == mb->getLink(l).m_jointFeedback)
{
for (int d = 0; d < 6; d++)
{
stateDetails->m_jointReactionForces[l * 6 + d] = 0;
}
}
else
{
btVector3 sensedForce = mb->getLink(l).m_jointFeedback->m_reactionForces.getLinear();
btVector3 sensedTorque = mb->getLink(l).m_jointFeedback->m_reactionForces.getAngular();
stateDetails->m_jointReactionForces[l * 6 + 0] = sensedForce[0];
stateDetails->m_jointReactionForces[l * 6 + 1] = sensedForce[1];
stateDetails->m_jointReactionForces[l * 6 + 2] = sensedForce[2];
stateDetails->m_jointReactionForces[l * 6 + 3] = sensedTorque[0];
stateDetails->m_jointReactionForces[l * 6 + 4] = sensedTorque[1];
stateDetails->m_jointReactionForces[l * 6 + 5] = sensedTorque[2];
}
stateDetails->m_jointMotorForce[l] = 0;
if (supportsJointMotor(mb, l))
{
btMultiBodyJointMotor* motor = (btMultiBodyJointMotor*)body->m_multiBody->getLink(l).m_userPtr;
if (motor && m_data->m_physicsDeltaTime > btScalar(0))
{
btScalar force = motor->getAppliedImpulse(0) / m_data->m_physicsDeltaTime;
stateDetails->m_jointMotorForce[l] =
force;
//if (force>0)
//{
// b3Printf("force = %f\n", force);
//}
}
}
btVector3 linkLocalInertialOrigin = body->m_linkLocalInertialFrames[l].getOrigin();
btQuaternion linkLocalInertialRotation = body->m_linkLocalInertialFrames[l].getRotation();
btVector3 linkCOMOrigin = mb->getLink(l).m_cachedWorldTransform.getOrigin();
btQuaternion linkCOMRotation = mb->getLink(l).m_cachedWorldTransform.getRotation();
stateDetails->m_linkState[l * 7 + 0] = linkCOMOrigin.getX();
stateDetails->m_linkState[l * 7 + 1] = linkCOMOrigin.getY();
stateDetails->m_linkState[l * 7 + 2] = linkCOMOrigin.getZ();
stateDetails->m_linkState[l * 7 + 3] = linkCOMRotation.x();
stateDetails->m_linkState[l * 7 + 4] = linkCOMRotation.y();
stateDetails->m_linkState[l * 7 + 5] = linkCOMRotation.z();
stateDetails->m_linkState[l * 7 + 6] = linkCOMRotation.w();
btVector3 worldLinVel(0, 0, 0);
btVector3 worldAngVel(0, 0, 0);
if (computeLinkVelocities)
{
const btMatrix3x3& linkRotMat = mb->getLink(l).m_cachedWorldTransform.getBasis();
worldLinVel = linkRotMat * linVel[l + 1];
worldAngVel = linkRotMat * omega[l + 1];
}
stateDetails->m_linkWorldVelocities[l * 6 + 0] = worldLinVel[0];
stateDetails->m_linkWorldVelocities[l * 6 + 1] = worldLinVel[1];
stateDetails->m_linkWorldVelocities[l * 6 + 2] = worldLinVel[2];
stateDetails->m_linkWorldVelocities[l * 6 + 3] = worldAngVel[0];
stateDetails->m_linkWorldVelocities[l * 6 + 4] = worldAngVel[1];
stateDetails->m_linkWorldVelocities[l * 6 + 5] = worldAngVel[2];
stateDetails->m_linkLocalInertialFrames[l * 7 + 0] = linkLocalInertialOrigin.getX();
stateDetails->m_linkLocalInertialFrames[l * 7 + 1] = linkLocalInertialOrigin.getY();
stateDetails->m_linkLocalInertialFrames[l * 7 + 2] = linkLocalInertialOrigin.getZ();
stateDetails->m_linkLocalInertialFrames[l * 7 + 3] = linkLocalInertialRotation.x();
stateDetails->m_linkLocalInertialFrames[l * 7 + 4] = linkLocalInertialRotation.y();
stateDetails->m_linkLocalInertialFrames[l * 7 + 5] = linkLocalInertialRotation.z();
stateDetails->m_linkLocalInertialFrames[l * 7 + 6] = linkLocalInertialRotation.w();
}
serverCmd.m_sendActualStateArgs.m_numDegreeOfFreedomQ = totalDegreeOfFreedomQ;
serverCmd.m_sendActualStateArgs.m_numDegreeOfFreedomU = totalDegreeOfFreedomU;
hasStatus = true;
}
else if (body && body->m_rigidBody)
{
btRigidBody* rb = body->m_rigidBody;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_ACTUAL_STATE_UPDATE_COMPLETED;
serverCmd.m_sendActualStateArgs.m_bodyUniqueId = bodyUniqueId;
serverCmd.m_sendActualStateArgs.m_numLinks = 0;
serverCmd.m_numDataStreamBytes = sizeof(SendActualStateSharedMemoryStorage);
serverCmd.m_sendActualStateArgs.m_stateDetails = 0;
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[0] =
body->m_rootLocalInertialFrame.getOrigin()[0];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[1] =
body->m_rootLocalInertialFrame.getOrigin()[1];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[2] =
body->m_rootLocalInertialFrame.getOrigin()[2];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[3] =
body->m_rootLocalInertialFrame.getRotation()[0];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[4] =
body->m_rootLocalInertialFrame.getRotation()[1];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[5] =
body->m_rootLocalInertialFrame.getRotation()[2];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[6] =
body->m_rootLocalInertialFrame.getRotation()[3];
btTransform tr = rb->getWorldTransform();
//base position in world space, cartesian
stateDetails->m_actualStateQ[0] = tr.getOrigin()[0];
stateDetails->m_actualStateQ[1] = tr.getOrigin()[1];
stateDetails->m_actualStateQ[2] = tr.getOrigin()[2];
//base orientation, quaternion x,y,z,w, in world space, cartesian
stateDetails->m_actualStateQ[3] = tr.getRotation()[0];
stateDetails->m_actualStateQ[4] = tr.getRotation()[1];
stateDetails->m_actualStateQ[5] = tr.getRotation()[2];
stateDetails->m_actualStateQ[6] = tr.getRotation()[3];
int totalDegreeOfFreedomQ = 7; //pos + quaternion
//base linear velocity (in world space, cartesian)
stateDetails->m_actualStateQdot[0] = rb->getLinearVelocity()[0];
stateDetails->m_actualStateQdot[1] = rb->getLinearVelocity()[1];
stateDetails->m_actualStateQdot[2] = rb->getLinearVelocity()[2];
//base angular velocity (in world space, cartesian)
stateDetails->m_actualStateQdot[3] = rb->getAngularVelocity()[0];
stateDetails->m_actualStateQdot[4] = rb->getAngularVelocity()[1];
stateDetails->m_actualStateQdot[5] = rb->getAngularVelocity()[2];
int totalDegreeOfFreedomU = 6; //3 linear and 3 angular DOF
serverCmd.m_sendActualStateArgs.m_numDegreeOfFreedomQ = totalDegreeOfFreedomQ;
serverCmd.m_sendActualStateArgs.m_numDegreeOfFreedomU = totalDegreeOfFreedomU;
hasStatus = true;
}
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
else if (body && body->m_softBody)
{
btSoftBody* sb = body->m_softBody;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_ACTUAL_STATE_UPDATE_COMPLETED;
serverCmd.m_sendActualStateArgs.m_bodyUniqueId = bodyUniqueId;
serverCmd.m_sendActualStateArgs.m_numLinks = 0;
serverCmd.m_numDataStreamBytes = sizeof(SendActualStateSharedMemoryStorage);
serverCmd.m_sendActualStateArgs.m_stateDetails = 0;
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[0] =
body->m_rootLocalInertialFrame.getOrigin()[0];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[1] =
body->m_rootLocalInertialFrame.getOrigin()[1];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[2] =
body->m_rootLocalInertialFrame.getOrigin()[2];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[3] =
body->m_rootLocalInertialFrame.getRotation()[0];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[4] =
body->m_rootLocalInertialFrame.getRotation()[1];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[5] =
body->m_rootLocalInertialFrame.getRotation()[2];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[6] =
body->m_rootLocalInertialFrame.getRotation()[3];
btVector3 center_of_mass(sb->getCenterOfMass());
btTransform tr = sb->getWorldTransform();
//base position in world space, cartesian
stateDetails->m_actualStateQ[0] = center_of_mass[0];
stateDetails->m_actualStateQ[1] = center_of_mass[1];
stateDetails->m_actualStateQ[2] = center_of_mass[2];
//base orientation, quaternion x,y,z,w, in world space, cartesian
stateDetails->m_actualStateQ[3] = tr.getRotation()[0];
stateDetails->m_actualStateQ[4] = tr.getRotation()[1];
stateDetails->m_actualStateQ[5] = tr.getRotation()[2];
stateDetails->m_actualStateQ[6] = tr.getRotation()[3];
int totalDegreeOfFreedomQ = 7; //pos + quaternion
int totalDegreeOfFreedomU = 6; //3 linear and 3 angular DOF
serverCmd.m_sendActualStateArgs.m_numDegreeOfFreedomQ = totalDegreeOfFreedomQ;
serverCmd.m_sendActualStateArgs.m_numDegreeOfFreedomU = totalDegreeOfFreedomU;
hasStatus = true;
}
#endif
else
{
//b3Warning("Request state but no multibody or rigid body available");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_ACTUAL_STATE_UPDATE_FAILED;
hasStatus = true;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestContactpointInformationCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_CONTACT_POINT_INFORMATION");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_sendContactPointArgs.m_numContactPointsCopied = 0;
//make a snapshot of the contact manifolds into individual contact points
if (clientCmd.m_requestContactPointArguments.m_startingContactPointIndex == 0)
{
m_data->m_cachedContactPoints.resize(0);
int mode = CONTACT_QUERY_MODE_REPORT_EXISTING_CONTACT_POINTS;
if (clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_QUERY_MODE)
{
mode = clientCmd.m_requestContactPointArguments.m_mode;
}
switch (mode)
{
case CONTACT_QUERY_MODE_REPORT_EXISTING_CONTACT_POINTS:
{
int numContactManifolds = m_data->m_dynamicsWorld->getDispatcher()->getNumManifolds();
m_data->m_cachedContactPoints.reserve(numContactManifolds * 4);
for (int i = 0; i < numContactManifolds; i++)
{
const btPersistentManifold* manifold = m_data->m_dynamicsWorld->getDispatcher()->getInternalManifoldPointer()[i];
int linkIndexA = -1;
int linkIndexB = -1;
int objectIndexB = -1;
const btRigidBody* bodyB = btRigidBody::upcast(manifold->getBody1());
if (bodyB)
{
objectIndexB = bodyB->getUserIndex2();
}
const btMultiBodyLinkCollider* mblB = btMultiBodyLinkCollider::upcast(manifold->getBody1());
if (mblB && mblB->m_multiBody)
{
linkIndexB = mblB->m_link;
objectIndexB = mblB->m_multiBody->getUserIndex2();
}
int objectIndexA = -1;
const btRigidBody* bodyA = btRigidBody::upcast(manifold->getBody0());
if (bodyA)
{
objectIndexA = bodyA->getUserIndex2();
}
const btMultiBodyLinkCollider* mblA = btMultiBodyLinkCollider::upcast(manifold->getBody0());
if (mblA && mblA->m_multiBody)
{
linkIndexA = mblA->m_link;
objectIndexA = mblA->m_multiBody->getUserIndex2();
}
btAssert(bodyA || mblA);
//apply the filter, if the user provides it
bool swap = false;
if (clientCmd.m_requestContactPointArguments.m_objectAIndexFilter >= 0)
{
if (clientCmd.m_requestContactPointArguments.m_objectAIndexFilter == objectIndexA)
{
swap = false;
}
else if (clientCmd.m_requestContactPointArguments.m_objectAIndexFilter == objectIndexB)
{
swap = true;
}
else
{
continue;
}
}
if (swap)
{
std::swap(objectIndexA, objectIndexB);
std::swap(linkIndexA, linkIndexB);
std::swap(bodyA, bodyB);
}
//apply the second object filter, if the user provides it
if (clientCmd.m_requestContactPointArguments.m_objectBIndexFilter >= 0)
{
if (clientCmd.m_requestContactPointArguments.m_objectBIndexFilter != objectIndexB)
{
continue;
}
}
if (
(clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_LINK_INDEX_A_FILTER) &&
clientCmd.m_requestContactPointArguments.m_linkIndexAIndexFilter != linkIndexA)
{
continue;
}
if (
(clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_LINK_INDEX_B_FILTER) &&
clientCmd.m_requestContactPointArguments.m_linkIndexBIndexFilter != linkIndexB)
{
continue;
}
for (int p = 0; p < manifold->getNumContacts(); p++)
{
b3ContactPointData pt;
pt.m_bodyUniqueIdA = objectIndexA;
pt.m_bodyUniqueIdB = objectIndexB;
const btManifoldPoint& srcPt = manifold->getContactPoint(p);
pt.m_contactDistance = srcPt.getDistance();
pt.m_contactFlags = 0;
pt.m_linkIndexA = linkIndexA;
pt.m_linkIndexB = linkIndexB;
for (int j = 0; j < 3; j++)
{
pt.m_contactNormalOnBInWS[j] = srcPt.m_normalWorldOnB[j];
pt.m_positionOnAInWS[j] = srcPt.getPositionWorldOnA()[j];
pt.m_positionOnBInWS[j] = srcPt.getPositionWorldOnB()[j];
}
pt.m_normalForce = srcPt.getAppliedImpulse() / m_data->m_physicsDeltaTime;
pt.m_linearFrictionForce1 = srcPt.m_appliedImpulseLateral1 / m_data->m_physicsDeltaTime;
pt.m_linearFrictionForce2 = srcPt.m_appliedImpulseLateral2 / m_data->m_physicsDeltaTime;
for (int j = 0; j < 3; j++)
{
pt.m_linearFrictionDirection1[j] = srcPt.m_lateralFrictionDir1[j];
pt.m_linearFrictionDirection2[j] = srcPt.m_lateralFrictionDir2[j];
}
m_data->m_cachedContactPoints.push_back(pt);
}
}
break;
}
case CONTACT_QUERY_MODE_COMPUTE_CLOSEST_POINTS:
{
//todo(erwincoumans) compute closest points between all, and vs all, pair
btScalar closestDistanceThreshold = 0.f;
if (clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_CLOSEST_DISTANCE_THRESHOLD)
{
closestDistanceThreshold = clientCmd.m_requestContactPointArguments.m_closestDistanceThreshold;
}
int bodyUniqueIdA = clientCmd.m_requestContactPointArguments.m_objectAIndexFilter;
int bodyUniqueIdB = clientCmd.m_requestContactPointArguments.m_objectBIndexFilter;
bool hasLinkIndexAFilter = (0 != (clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_LINK_INDEX_A_FILTER));
bool hasLinkIndexBFilter = (0 != (clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_LINK_INDEX_B_FILTER));
int linkIndexA = clientCmd.m_requestContactPointArguments.m_linkIndexAIndexFilter;
int linkIndexB = clientCmd.m_requestContactPointArguments.m_linkIndexBIndexFilter;
btAlignedObjectArray<btCollisionObject*> setA;
btAlignedObjectArray<btCollisionObject*> setB;
btAlignedObjectArray<int> setALinkIndex;
btAlignedObjectArray<int> setBLinkIndex;
btCollisionObject colObA;
btCollisionObject colObB;
int collisionShapeA = (clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_COLLISION_SHAPE_A) ? clientCmd.m_requestContactPointArguments.m_collisionShapeA : -1;
int collisionShapeB = (clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_COLLISION_SHAPE_B) ? clientCmd.m_requestContactPointArguments.m_collisionShapeB : -1;
if (collisionShapeA >= 0)
{
btVector3 posA(0, 0, 0);
if (clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_COLLISION_SHAPE_POSITION_A)
{
posA.setValue(clientCmd.m_requestContactPointArguments.m_collisionShapePositionA[0],
clientCmd.m_requestContactPointArguments.m_collisionShapePositionA[1],
clientCmd.m_requestContactPointArguments.m_collisionShapePositionA[2]);
}
btQuaternion ornA(0, 0, 0, 1);
if (clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_COLLISION_SHAPE_ORIENTATION_A)
{
ornA.setValue(clientCmd.m_requestContactPointArguments.m_collisionShapeOrientationA[0],
clientCmd.m_requestContactPointArguments.m_collisionShapeOrientationA[1],
clientCmd.m_requestContactPointArguments.m_collisionShapeOrientationA[2],
clientCmd.m_requestContactPointArguments.m_collisionShapeOrientationA[3]);
}
InternalCollisionShapeHandle* handle = m_data->m_userCollisionShapeHandles.getHandle(collisionShapeA);
if (handle && handle->m_collisionShape)
{
colObA.setCollisionShape(handle->m_collisionShape);
btTransform tr;
tr.setIdentity();
tr.setOrigin(posA);
tr.setRotation(ornA);
colObA.setWorldTransform(tr);
setA.push_back(&colObA);
setALinkIndex.push_back(-2);
}
else
{
b3Warning("collisionShapeA provided is not valid.");
}
}
if (collisionShapeB >= 0)
{
btVector3 posB(0, 0, 0);
if (clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_COLLISION_SHAPE_POSITION_B)
{
posB.setValue(clientCmd.m_requestContactPointArguments.m_collisionShapePositionB[0],
clientCmd.m_requestContactPointArguments.m_collisionShapePositionB[1],
clientCmd.m_requestContactPointArguments.m_collisionShapePositionB[2]);
}
btQuaternion ornB(0, 0, 0, 1);
if (clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_COLLISION_SHAPE_ORIENTATION_B)
{
ornB.setValue(clientCmd.m_requestContactPointArguments.m_collisionShapeOrientationB[0],
clientCmd.m_requestContactPointArguments.m_collisionShapeOrientationB[1],
clientCmd.m_requestContactPointArguments.m_collisionShapeOrientationB[2],
clientCmd.m_requestContactPointArguments.m_collisionShapeOrientationB[3]);
}
InternalCollisionShapeHandle* handle = m_data->m_userCollisionShapeHandles.getHandle(collisionShapeB);
if (handle && handle->m_collisionShape)
{
colObB.setCollisionShape(handle->m_collisionShape);
btTransform tr;
tr.setIdentity();
tr.setOrigin(posB);
tr.setRotation(ornB);
colObB.setWorldTransform(tr);
setB.push_back(&colObB);
setBLinkIndex.push_back(-2);
}
else
{
b3Warning("collisionShapeB provided is not valid.");
}
}
if (bodyUniqueIdA >= 0)
{
InternalBodyData* bodyA = m_data->m_bodyHandles.getHandle(bodyUniqueIdA);
if (bodyA)
{
if (bodyA->m_multiBody)
{
if (bodyA->m_multiBody->getBaseCollider())
{
if (!hasLinkIndexAFilter || (linkIndexA == -1))
{
setA.push_back(bodyA->m_multiBody->getBaseCollider());
setALinkIndex.push_back(-1);
}
}
for (int i = 0; i < bodyA->m_multiBody->getNumLinks(); i++)
{
if (bodyA->m_multiBody->getLink(i).m_collider)
{
if (!hasLinkIndexAFilter || (linkIndexA == i))
{
setA.push_back(bodyA->m_multiBody->getLink(i).m_collider);
setALinkIndex.push_back(i);
}
}
}
}
if (bodyA->m_rigidBody)
{
setA.push_back(bodyA->m_rigidBody);
setALinkIndex.push_back(-1);
}
}
}
if (bodyUniqueIdB >= 0)
{
InternalBodyData* bodyB = m_data->m_bodyHandles.getHandle(bodyUniqueIdB);
if (bodyB)
{
if (bodyB->m_multiBody)
{
if (bodyB->m_multiBody->getBaseCollider())
{
if (!hasLinkIndexBFilter || (linkIndexB == -1))
{
setB.push_back(bodyB->m_multiBody->getBaseCollider());
setBLinkIndex.push_back(-1);
}
}
for (int i = 0; i < bodyB->m_multiBody->getNumLinks(); i++)
{
if (bodyB->m_multiBody->getLink(i).m_collider)
{
if (!hasLinkIndexBFilter || (linkIndexB == i))
{
setB.push_back(bodyB->m_multiBody->getLink(i).m_collider);
setBLinkIndex.push_back(i);
}
}
}
}
if (bodyB->m_rigidBody)
{
setB.push_back(bodyB->m_rigidBody);
setBLinkIndex.push_back(-1);
}
}
}
{
///ContactResultCallback is used to report contact points
struct MyContactResultCallback : public btCollisionWorld::ContactResultCallback
{
int m_bodyUniqueIdA;
int m_bodyUniqueIdB;
int m_linkIndexA;
int m_linkIndexB;
btScalar m_deltaTime;
btAlignedObjectArray<b3ContactPointData>& m_cachedContactPoints;
MyContactResultCallback(btAlignedObjectArray<b3ContactPointData>& pointCache)
: m_cachedContactPoints(pointCache)
{
}
virtual ~MyContactResultCallback()
{
}
virtual bool needsCollision(btBroadphaseProxy* proxy0) const
{
//bool collides = (proxy0->m_collisionFilterGroup & m_collisionFilterMask) != 0;
//collides = collides && (m_collisionFilterGroup & proxy0->m_collisionFilterMask);
//return collides;
return true;
}
virtual btScalar addSingleResult(btManifoldPoint& cp, const btCollisionObjectWrapper* colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper* colObj1Wrap, int partId1, int index1)
{
if (cp.m_distance1 <= m_closestDistanceThreshold)
{
b3ContactPointData pt;
pt.m_bodyUniqueIdA = m_bodyUniqueIdA;
pt.m_bodyUniqueIdB = m_bodyUniqueIdB;
const btManifoldPoint& srcPt = cp;
pt.m_contactDistance = srcPt.getDistance();
pt.m_contactFlags = 0;
pt.m_linkIndexA = m_linkIndexA;
pt.m_linkIndexB = m_linkIndexB;
for (int j = 0; j < 3; j++)
{
pt.m_contactNormalOnBInWS[j] = srcPt.m_normalWorldOnB[j];
pt.m_positionOnAInWS[j] = srcPt.getPositionWorldOnA()[j];
pt.m_positionOnBInWS[j] = srcPt.getPositionWorldOnB()[j];
}
pt.m_normalForce = srcPt.getAppliedImpulse() / m_deltaTime;
pt.m_linearFrictionForce1 = srcPt.m_appliedImpulseLateral1 / m_deltaTime;
pt.m_linearFrictionForce2 = srcPt.m_appliedImpulseLateral2 / m_deltaTime;
for (int j = 0; j < 3; j++)
{
pt.m_linearFrictionDirection1[j] = srcPt.m_lateralFrictionDir1[j];
pt.m_linearFrictionDirection2[j] = srcPt.m_lateralFrictionDir2[j];
}
m_cachedContactPoints.push_back(pt);
}
return 1;
}
};
MyContactResultCallback cb(m_data->m_cachedContactPoints);
cb.m_bodyUniqueIdA = bodyUniqueIdA;
cb.m_bodyUniqueIdB = bodyUniqueIdB;
cb.m_deltaTime = m_data->m_physicsDeltaTime;
for (int i = 0; i < setA.size(); i++)
{
cb.m_linkIndexA = setALinkIndex[i];
for (int j = 0; j < setB.size(); j++)
{
cb.m_linkIndexB = setBLinkIndex[j];
cb.m_closestDistanceThreshold = closestDistanceThreshold;
this->m_data->m_dynamicsWorld->contactPairTest(setA[i], setB[j], cb);
}
}
}
break;
}
default:
{
b3Warning("Unknown contact query mode: %d", mode);
}
}
}
int numContactPoints = m_data->m_cachedContactPoints.size();
//b3ContactPoint
//struct b3ContactPointDynamics
int totalBytesPerContact = sizeof(b3ContactPointData);
int contactPointStorage = bufferSizeInBytes / totalBytesPerContact - 1;
b3ContactPointData* contactData = (b3ContactPointData*)bufferServerToClient;
int startContactPointIndex = clientCmd.m_requestContactPointArguments.m_startingContactPointIndex;
int numContactPointBatch = btMin(numContactPoints, contactPointStorage);
int endContactPointIndex = startContactPointIndex + numContactPointBatch;
for (int i = startContactPointIndex; i < endContactPointIndex; i++)
{
const b3ContactPointData& srcPt = m_data->m_cachedContactPoints[i];
b3ContactPointData& destPt = contactData[serverCmd.m_sendContactPointArgs.m_numContactPointsCopied];
destPt = srcPt;
serverCmd.m_sendContactPointArgs.m_numContactPointsCopied++;
}
serverCmd.m_sendContactPointArgs.m_startingContactPointIndex = clientCmd.m_requestContactPointArguments.m_startingContactPointIndex;
serverCmd.m_sendContactPointArgs.m_numRemainingContactPoints = numContactPoints - clientCmd.m_requestContactPointArguments.m_startingContactPointIndex - serverCmd.m_sendContactPointArgs.m_numContactPointsCopied;
serverCmd.m_numDataStreamBytes = totalBytesPerContact * serverCmd.m_sendContactPointArgs.m_numContactPointsCopied;
serverCmd.m_type = CMD_CONTACT_POINT_INFORMATION_COMPLETED; //CMD_CONTACT_POINT_INFORMATION_FAILED,
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestBodyInfoCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_BODY_INFO");
const SdfRequestInfoArgs& sdfInfoArgs = clientCmd.m_sdfRequestInfoArgs;
//stream info into memory
int streamSizeInBytes = createBodyInfoStream(sdfInfoArgs.m_bodyUniqueId, bufferServerToClient, bufferSizeInBytes);
serverStatusOut.m_type = CMD_BODY_INFO_COMPLETED;
serverStatusOut.m_dataStreamArguments.m_bodyUniqueId = sdfInfoArgs.m_bodyUniqueId;
serverStatusOut.m_dataStreamArguments.m_bodyName[0] = 0;
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(sdfInfoArgs.m_bodyUniqueId);
if (bodyHandle)
{
strcpy(serverStatusOut.m_dataStreamArguments.m_bodyName, bodyHandle->m_bodyName.c_str());
}
serverStatusOut.m_numDataStreamBytes = streamSizeInBytes;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processLoadSDFCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_LOAD_SDF");
const SdfArgs& sdfArgs = clientCmd.m_sdfArguments;
if (m_data->m_verboseOutput)
{
b3Printf("Processed CMD_LOAD_SDF:%s", sdfArgs.m_sdfFileName);
}
bool useMultiBody = (clientCmd.m_updateFlags & URDF_ARGS_USE_MULTIBODY) ? (sdfArgs.m_useMultiBody != 0) : true;
int flags = CUF_USE_SDF; //CUF_USE_URDF_INERTIA
btScalar globalScaling = 1.f;
if (clientCmd.m_updateFlags & URDF_ARGS_USE_GLOBAL_SCALING)
{
globalScaling = sdfArgs.m_globalScaling;
}
bool completedOk = loadSdf(sdfArgs.m_sdfFileName, bufferServerToClient, bufferSizeInBytes, useMultiBody, flags, globalScaling);
if (completedOk)
{
m_data->m_guiHelper->autogenerateGraphicsObjects(this->m_data->m_dynamicsWorld);
//serverStatusOut.m_type = CMD_SDF_LOADING_FAILED;
serverStatusOut.m_sdfLoadedArgs.m_numBodies = m_data->m_sdfRecentLoadedBodies.size();
serverStatusOut.m_sdfLoadedArgs.m_numUserConstraints = 0;
int maxBodies = btMin(MAX_SDF_BODIES, serverStatusOut.m_sdfLoadedArgs.m_numBodies);
for (int i = 0; i < maxBodies; i++)
{
serverStatusOut.m_sdfLoadedArgs.m_bodyUniqueIds[i] = m_data->m_sdfRecentLoadedBodies[i];
}
serverStatusOut.m_type = CMD_SDF_LOADING_COMPLETED;
}
else
{
serverStatusOut.m_type = CMD_SDF_LOADING_FAILED;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCreateMultiBodyCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
if (clientCmd.m_createMultiBodyArgs.m_numBatchObjects > 0)
{
//batch of objects, to speed up creation time
bool result = false;
SharedMemoryCommand clientCmd2 = clientCmd;
int baseLinkIndex = clientCmd.m_createMultiBodyArgs.m_baseLinkIndex;
double* basePositionAndOrientations = (double*)bufferServerToClient;
for (int i = 0; i < clientCmd2.m_createMultiBodyArgs.m_numBatchObjects; i++)
{
clientCmd2.m_createMultiBodyArgs.m_linkPositions[baseLinkIndex * 3 + 0] = basePositionAndOrientations[0 + i * 3];
clientCmd2.m_createMultiBodyArgs.m_linkPositions[baseLinkIndex * 3 + 1] = basePositionAndOrientations[1 + i * 3];
clientCmd2.m_createMultiBodyArgs.m_linkPositions[baseLinkIndex * 3 + 2] = basePositionAndOrientations[2 + i * 3];
if (i == (clientCmd2.m_createMultiBodyArgs.m_numBatchObjects - 1))
{
result = processCreateMultiBodyCommandSingle(clientCmd2, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
}
else
{
result = processCreateMultiBodyCommandSingle(clientCmd2, serverStatusOut, 0, 0);
}
}
m_data->m_guiHelper->autogenerateGraphicsObjects(this->m_data->m_dynamicsWorld);
return result;
}
return processCreateMultiBodyCommandSingle(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
}
bool PhysicsServerCommandProcessor::processCreateMultiBodyCommandSingle(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
BT_PROFILE("processCreateMultiBodyCommand2");
bool hasStatus = true;
serverStatusOut.m_type = CMD_CREATE_MULTI_BODY_FAILED;
if (clientCmd.m_createMultiBodyArgs.m_baseLinkIndex >= 0)
{
m_data->m_sdfRecentLoadedBodies.clear();
int flags = 0;
if (clientCmd.m_updateFlags & MULT_BODY_HAS_FLAGS)
{
flags = clientCmd.m_createMultiBodyArgs.m_flags;
}
ProgrammaticUrdfInterface u2b(clientCmd.m_createMultiBodyArgs, m_data, flags);
bool useMultiBody = true;
if (clientCmd.m_updateFlags & MULT_BODY_USE_MAXIMAL_COORDINATES)
{
useMultiBody = false;
}
bool ok = 0;
{
BT_PROFILE("processImportedObjects");
ok = processImportedObjects("memory", bufferServerToClient, bufferSizeInBytes, useMultiBody, flags, u2b);
}
if (ok)
{
BT_PROFILE("post process");
int bodyUniqueId = -1;
if (m_data->m_sdfRecentLoadedBodies.size() == 1)
{
bodyUniqueId = m_data->m_sdfRecentLoadedBodies[0];
}
m_data->m_sdfRecentLoadedBodies.clear();
if (bodyUniqueId >= 0)
{
serverStatusOut.m_type = CMD_CREATE_MULTI_BODY_COMPLETED;
if (bufferSizeInBytes > 0 && serverStatusOut.m_numDataStreamBytes == 0)
{
{
BT_PROFILE("autogenerateGraphicsObjects");
m_data->m_guiHelper->autogenerateGraphicsObjects(this->m_data->m_dynamicsWorld);
}
BT_PROFILE("createBodyInfoStream");
int streamSizeInBytes = createBodyInfoStream(bodyUniqueId, bufferServerToClient, bufferSizeInBytes);
serverStatusOut.m_numDataStreamBytes = streamSizeInBytes;
serverStatusOut.m_dataStreamArguments.m_bodyUniqueId = bodyUniqueId;
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
strcpy(serverStatusOut.m_dataStreamArguments.m_bodyName, body->m_bodyName.c_str());
}
}
}
//ConvertURDF2Bullet(u2b,creation, rootTrans,m_data->m_dynamicsWorld,useMultiBody,u2b.getPathPrefix(),flags);
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processLoadURDFCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
serverStatusOut.m_type = CMD_URDF_LOADING_FAILED;
BT_PROFILE("CMD_LOAD_URDF");
const UrdfArgs& urdfArgs = clientCmd.m_urdfArguments;
if (m_data->m_verboseOutput)
{
b3Printf("Processed CMD_LOAD_URDF:%s", urdfArgs.m_urdfFileName);
}
btAssert((clientCmd.m_updateFlags & URDF_ARGS_FILE_NAME) != 0);
btAssert(urdfArgs.m_urdfFileName);
btVector3 initialPos(0, 0, 0);
btQuaternion initialOrn(0, 0, 0, 1);
if (clientCmd.m_updateFlags & URDF_ARGS_INITIAL_POSITION)
{
initialPos[0] = urdfArgs.m_initialPosition[0];
initialPos[1] = urdfArgs.m_initialPosition[1];
initialPos[2] = urdfArgs.m_initialPosition[2];
}
int urdfFlags = 0;
if (clientCmd.m_updateFlags & URDF_ARGS_HAS_CUSTOM_URDF_FLAGS)
{
urdfFlags = urdfArgs.m_urdfFlags;
}
if (clientCmd.m_updateFlags & URDF_ARGS_INITIAL_ORIENTATION)
{
initialOrn[0] = urdfArgs.m_initialOrientation[0];
initialOrn[1] = urdfArgs.m_initialOrientation[1];
initialOrn[2] = urdfArgs.m_initialOrientation[2];
initialOrn[3] = urdfArgs.m_initialOrientation[3];
}
bool useMultiBody = (clientCmd.m_updateFlags & URDF_ARGS_USE_MULTIBODY) ? (urdfArgs.m_useMultiBody != 0) : true;
bool useFixedBase = (clientCmd.m_updateFlags & URDF_ARGS_USE_FIXED_BASE) ? (urdfArgs.m_useFixedBase != 0) : false;
int bodyUniqueId;
btScalar globalScaling = 1.f;
if (clientCmd.m_updateFlags & URDF_ARGS_USE_GLOBAL_SCALING)
{
globalScaling = urdfArgs.m_globalScaling;
}
//load the actual URDF and send a report: completed or failed
bool completedOk = loadUrdf(urdfArgs.m_urdfFileName,
initialPos, initialOrn,
useMultiBody, useFixedBase, &bodyUniqueId, bufferServerToClient, bufferSizeInBytes, urdfFlags, globalScaling);
if (completedOk && bodyUniqueId >= 0)
{
m_data->m_guiHelper->autogenerateGraphicsObjects(this->m_data->m_dynamicsWorld);
serverStatusOut.m_type = CMD_URDF_LOADING_COMPLETED;
int streamSizeInBytes = createBodyInfoStream(bodyUniqueId, bufferServerToClient, bufferSizeInBytes);
serverStatusOut.m_numDataStreamBytes = streamSizeInBytes;
#ifdef ENABLE_LINK_MAPPER
if (m_data->m_urdfLinkNameMapper.size())
{
serverStatusOut.m_numDataStreamBytes = m_data->m_urdfLinkNameMapper.at(m_data->m_urdfLinkNameMapper.size() - 1)->m_memSerializer->getCurrentBufferSize();
}
#endif
serverStatusOut.m_dataStreamArguments.m_bodyUniqueId = bodyUniqueId;
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
strcpy(serverStatusOut.m_dataStreamArguments.m_bodyName, body->m_bodyName.c_str());
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processLoadSoftBodyCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
serverStatusOut.m_type = CMD_LOAD_SOFT_BODY_FAILED;
bool hasStatus = true;
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
double scale = 1;
double mass = 1;
double collisionMargin = 0.02;
const LoadSoftBodyArgs& loadSoftBodyArgs = clientCmd.m_loadSoftBodyArguments;
if (m_data->m_verboseOutput)
{
b3Printf("Processed CMD_LOAD_SOFT_BODY:%s", loadSoftBodyArgs.m_fileName);
}
btAssert((clientCmd.m_updateFlags & LOAD_SOFT_BODY_FILE_NAME) != 0);
btAssert(loadSoftBodyArgs.m_fileName);
btVector3 initialPos(0, 0, 0);
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_INITIAL_POSITION)
{
initialPos[0] = loadSoftBodyArgs.m_initialPosition[0];
initialPos[1] = loadSoftBodyArgs.m_initialPosition[1];
initialPos[2] = loadSoftBodyArgs.m_initialPosition[2];
}
btQuaternion initialOrn(0, 0, 0, 1);
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_INITIAL_ORIENTATION)
{
initialOrn[0] = loadSoftBodyArgs.m_initialOrientation[0];
initialOrn[1] = loadSoftBodyArgs.m_initialOrientation[1];
initialOrn[2] = loadSoftBodyArgs.m_initialOrientation[2];
initialOrn[3] = loadSoftBodyArgs.m_initialOrientation[3];
}
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_UPDATE_SCALE)
{
scale = clientCmd.m_loadSoftBodyArguments.m_scale;
}
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_UPDATE_MASS)
{
mass = clientCmd.m_loadSoftBodyArguments.m_mass;
}
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_UPDATE_COLLISION_MARGIN)
{
collisionMargin = clientCmd.m_loadSoftBodyArguments.m_collisionMargin;
}
btScalar spring_bending_stiffness = 0;
{
btSoftBody* psb = NULL;
CommonFileIOInterface* fileIO(m_data->m_pluginManager.getFileIOInterface());
char relativeFileName[1024];
char pathPrefix[1024];
pathPrefix[0] = 0;
if (fileIO->findResourcePath(loadSoftBodyArgs.m_fileName, relativeFileName, 1024))
{
b3FileUtils::extractPath(relativeFileName, pathPrefix, 1024);
}
const std::string& error_message_prefix = "";
std::string out_found_filename, out_found_sim_filename;
int out_type(0), out_sim_type(0);
bool foundFile = UrdfFindMeshFile(fileIO, pathPrefix, relativeFileName, error_message_prefix, &out_found_filename, &out_type);
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_SIM_MESH)
{
bool foundSimMesh = UrdfFindMeshFile(fileIO, pathPrefix, loadSoftBodyArgs.m_simFileName, error_message_prefix, &out_found_sim_filename, &out_sim_type);
}
else
{
out_sim_type = out_type;
out_found_sim_filename = out_found_filename;
}
if (out_sim_type == UrdfGeometry::FILE_OBJ)
{
std::vector<tinyobj::shape_t> shapes;
tinyobj::attrib_t attribute;
std::string err = tinyobj::LoadObj(attribute, shapes, out_found_sim_filename.c_str(), "", fileIO);
if (!shapes.empty())
{
const tinyobj::shape_t& shape = shapes[0];
btAlignedObjectArray<btScalar> vertices;
btAlignedObjectArray<int> indices;
for (int i = 0; i < attribute.vertices.size(); i++)
{
vertices.push_back(attribute.vertices[i]);
}
for (int i = 0; i < shape.mesh.indices.size(); i++)
{
indices.push_back(shape.mesh.indices[i].vertex_index);
}
int numTris = shape.mesh.indices.size() / 3;
if (numTris > 0)
{
{
btSoftMultiBodyDynamicsWorld* softWorld = getSoftWorld();
if (softWorld)
{
psb = btSoftBodyHelpers::CreateFromTriMesh(softWorld->getWorldInfo(), &vertices[0], &indices[0], numTris);
}
}
{
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
psb = btSoftBodyHelpers::CreateFromTriMesh(deformWorld->getWorldInfo(), &vertices[0], &indices[0], numTris);
}
}
}
}
#ifndef SKIP_DEFORMABLE_BODY
btScalar spring_elastic_stiffness, spring_damping_stiffness;
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_ADD_MASS_SPRING_FORCE)
{
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
spring_elastic_stiffness = clientCmd.m_loadSoftBodyArguments.m_springElasticStiffness;
spring_damping_stiffness = clientCmd.m_loadSoftBodyArguments.m_springDampingStiffness;
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_ADD_BENDING_SPRINGS)
{
spring_bending_stiffness = clientCmd.m_loadSoftBodyArguments.m_springBendingStiffness;
}
btDeformableLagrangianForce* springForce = new btDeformableMassSpringForce(spring_elastic_stiffness, spring_damping_stiffness, true, spring_bending_stiffness);
deformWorld->addForce(psb, springForce);
m_data->m_lf.push_back(springForce);
}
}
#endif
}
else if (out_sim_type == UrdfGeometry::FILE_VTK)
{
#ifndef SKIP_DEFORMABLE_BODY
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
psb = btSoftBodyHelpers::CreateFromVtkFile(deformWorld->getWorldInfo(), out_found_sim_filename.c_str());
btScalar corotated_mu, corotated_lambda;
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_ADD_COROTATED_FORCE)
{
corotated_mu = clientCmd.m_loadSoftBodyArguments.m_corotatedMu;
corotated_lambda = clientCmd.m_loadSoftBodyArguments.m_corotatedLambda;
btDeformableLagrangianForce* corotatedForce = new btDeformableCorotatedForce(corotated_mu, corotated_lambda);
deformWorld->addForce(psb, corotatedForce);
m_data->m_lf.push_back(corotatedForce);
}
btScalar neohookean_mu, neohookean_lambda, neohookean_damping;
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_ADD_NEOHOOKEAN_FORCE)
{
neohookean_mu = clientCmd.m_loadSoftBodyArguments.m_NeoHookeanMu;
neohookean_lambda = clientCmd.m_loadSoftBodyArguments.m_NeoHookeanLambda;
neohookean_damping = clientCmd.m_loadSoftBodyArguments.m_NeoHookeanDamping;
btDeformableLagrangianForce* neohookeanForce = new btDeformableNeoHookeanForce(neohookean_mu, neohookean_lambda, neohookean_damping);
deformWorld->addForce(psb, neohookeanForce);
m_data->m_lf.push_back(neohookeanForce);
}
btScalar spring_elastic_stiffness, spring_damping_stiffness;
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_ADD_MASS_SPRING_FORCE)
{
spring_elastic_stiffness = clientCmd.m_loadSoftBodyArguments.m_springElasticStiffness;
spring_damping_stiffness = clientCmd.m_loadSoftBodyArguments.m_springDampingStiffness;
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_ADD_BENDING_SPRINGS)
{
spring_bending_stiffness = clientCmd.m_loadSoftBodyArguments.m_springBendingStiffness;
}
btDeformableLagrangianForce* springForce = new btDeformableMassSpringForce(spring_elastic_stiffness, spring_damping_stiffness, true, spring_bending_stiffness);
deformWorld->addForce(psb, springForce);
m_data->m_lf.push_back(springForce);
}
}
#endif
}
if (psb != NULL)
{
#ifndef SKIP_DEFORMABLE_BODY
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
// load render mesh
if (out_found_sim_filename != out_found_filename)
{
// load render mesh
{
tinyobj::attrib_t attribute;
std::vector<tinyobj::shape_t> shapes;
std::string err = tinyobj::LoadObj(attribute, shapes, out_found_filename.c_str(), pathPrefix, m_data->m_pluginManager.getFileIOInterface());
for (int s = 0; s < (int)shapes.size(); s++)
{
tinyobj::shape_t& shape = shapes[s];
int faceCount = shape.mesh.indices.size();
int vertexCount = attribute.vertices.size()/3;
for (int v=0;v<vertexCount;v++)
{
btSoftBody::Node n;
n.m_x = btVector3(attribute.vertices[3*v],attribute.vertices[3*v+1],attribute.vertices[3*v+2]);
psb->m_renderNodes.push_back(n);
}
for (int f = 0; f < faceCount; f += 3)
{
if (f < 0 && f >= int(shape.mesh.indices.size()))
{
continue;
}
tinyobj::index_t v_0 = shape.mesh.indices[f];
tinyobj::index_t v_1 = shape.mesh.indices[f + 1];
tinyobj::index_t v_2 = shape.mesh.indices[f + 2];
btSoftBody::Face ff;
ff.m_n[0] = &psb->m_renderNodes[v_0.vertex_index];
ff.m_n[1] = &psb->m_renderNodes[v_1.vertex_index];
ff.m_n[2] = &psb->m_renderNodes[v_2.vertex_index];
psb->m_renderFaces.push_back(ff);
}
}
}
btSoftBodyHelpers::interpolateBarycentricWeights(psb);
}
else
{
psb->m_renderNodes.resize(0);
}
btVector3 gravity = m_data->m_dynamicsWorld->getGravity();
btDeformableLagrangianForce* gravityForce = new btDeformableGravityForce(gravity);
deformWorld->addForce(psb, gravityForce);
m_data->m_lf.push_back(gravityForce);
btScalar collision_hardness = 1;
psb->m_cfg.kKHR = collision_hardness;
psb->m_cfg.kCHR = collision_hardness;
btScalar friction_coeff = 0;
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_SET_FRICTION_COEFFICIENT)
{
friction_coeff = loadSoftBodyArgs.m_frictionCoeff;
}
psb->m_cfg.kDF = friction_coeff;
bool use_bending_spring = false;
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_ADD_BENDING_SPRINGS)
{
use_bending_spring = loadSoftBodyArgs.m_useBendingSprings;
if (use_bending_spring)
{
psb->generateBendingConstraints(2);
}
}
btSoftBody::Material* pm = psb->appendMaterial();
pm->m_flags -= btSoftBody::fMaterial::DebugDraw;
// turn on the collision flag for deformable
// collision between deformable and rigid
psb->m_cfg.collisions = btSoftBody::fCollision::SDF_RD;
// collion between deformable and deformable and self-collision
psb->m_cfg.collisions |= btSoftBody::fCollision::VF_DD;
psb->setCollisionFlags(0);
psb->setTotalMass(mass);
bool use_self_collision = false;
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_USE_SELF_COLLISION)
{
use_self_collision = loadSoftBodyArgs.m_useSelfCollision;
}
psb->setSelfCollision(use_self_collision);
}
#endif//SKIP_DEFORMABLE_BODY
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
btSoftMultiBodyDynamicsWorld* softWorld = getSoftWorld();
if (softWorld)
{
btSoftBody::Material* pm = psb->appendMaterial();
pm->m_kLST = 0.5;
pm->m_flags -= btSoftBody::fMaterial::DebugDraw;
psb->generateBendingConstraints(2, pm);
psb->m_cfg.piterations = 20;
psb->m_cfg.kDF = 0.5;
//turn on softbody vs softbody collision
psb->m_cfg.collisions |= btSoftBody::fCollision::VF_SS;
psb->randomizeConstraints();
psb->setTotalMass(mass, true);
}
#endif //SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
psb->scale(btVector3(scale, scale, scale));
psb->rotate(initialOrn);
psb->translate(initialPos);
psb->getCollisionShape()->setMargin(collisionMargin);
psb->getCollisionShape()->setUserPointer(psb);
#ifndef SKIP_DEFORMABLE_BODY
if (deformWorld)
{
deformWorld->addSoftBody(psb);
} else
#endif//SKIP_DEFORMABLE_BODY
{
btSoftMultiBodyDynamicsWorld* softWorld = getSoftWorld();
if (softWorld)
{
softWorld->addSoftBody(psb);
}
}
m_data->m_guiHelper->createCollisionShapeGraphicsObject(psb->getCollisionShape());
m_data->m_guiHelper->autogenerateGraphicsObjects(this->m_data->m_dynamicsWorld);
int bodyUniqueId = m_data->m_bodyHandles.allocHandle();
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(bodyUniqueId);
bodyHandle->m_softBody = psb;
b3VisualShapeData visualShape;
visualShape.m_objectUniqueId = bodyUniqueId;
visualShape.m_linkIndex = -1;
visualShape.m_visualGeometryType = URDF_GEOM_MESH;
//dimensions just contains the scale
visualShape.m_dimensions[0] = scale;
visualShape.m_dimensions[1] = scale;
visualShape.m_dimensions[2] = scale;
//filename
strncpy(visualShape.m_meshAssetFileName, relativeFileName, VISUAL_SHAPE_MAX_PATH_LEN);
visualShape.m_meshAssetFileName[VISUAL_SHAPE_MAX_PATH_LEN - 1] = 0;
//position and orientation
visualShape.m_localVisualFrame[0] = initialPos[0];
visualShape.m_localVisualFrame[1] = initialPos[1];
visualShape.m_localVisualFrame[2] = initialPos[2];
visualShape.m_localVisualFrame[3] = initialOrn[0];
visualShape.m_localVisualFrame[4] = initialOrn[1];
visualShape.m_localVisualFrame[5] = initialOrn[2];
visualShape.m_localVisualFrame[6] = initialOrn[3];
//color and ids to be set by the renderer
visualShape.m_rgbaColor[0] = 0;
visualShape.m_rgbaColor[1] = 0;
visualShape.m_rgbaColor[2] = 0;
visualShape.m_rgbaColor[3] = 1;
visualShape.m_tinyRendererTextureId = -1;
visualShape.m_textureUniqueId =-1;
visualShape.m_openglTextureId = -1;
m_data->m_pluginManager.getRenderInterface()->addVisualShape(&visualShape, fileIO);
serverStatusOut.m_loadSoftBodyResultArguments.m_objectUniqueId = bodyUniqueId;
serverStatusOut.m_type = CMD_LOAD_SOFT_BODY_COMPLETED;
int pos = strlen(relativeFileName)-1;
while(pos>=0 && relativeFileName[pos]!='/') { pos--;}
btAssert(strlen(relativeFileName)-pos-5>0);
std::string object_name (std::string(relativeFileName).substr(pos+1, strlen(relativeFileName)- 5 - pos));
bodyHandle->m_bodyName = object_name;
int streamSizeInBytes = createBodyInfoStream(bodyUniqueId, bufferServerToClient, bufferSizeInBytes);
serverStatusOut.m_numDataStreamBytes = streamSizeInBytes;
#ifdef ENABLE_LINK_MAPPER
if (m_data->m_urdfLinkNameMapper.size())
{
serverStatusOut.m_numDataStreamBytes = m_data->m_urdfLinkNameMapper.at(m_data->m_urdfLinkNameMapper.size() - 1)->m_memSerializer->getCurrentBufferSize();
}
#endif
serverStatusOut.m_dataStreamArguments.m_bodyUniqueId = bodyUniqueId;
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
strcpy(serverStatusOut.m_dataStreamArguments.m_bodyName, body->m_bodyName.c_str());
b3Notification notification;
notification.m_notificationType = BODY_ADDED;
notification.m_bodyArgs.m_bodyUniqueId = bodyUniqueId;
m_data->m_pluginManager.addNotification(notification);
}
}
#endif
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCreateSensorCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_CREATE_SENSOR");
if (m_data->m_verboseOutput)
{
b3Printf("Processed CMD_CREATE_SENSOR");
}
int bodyUniqueId = clientCmd.m_createSensorArguments.m_bodyUniqueId;
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (body && body->m_multiBody)
{
btMultiBody* mb = body->m_multiBody;
btAssert(mb);
for (int i = 0; i < clientCmd.m_createSensorArguments.m_numJointSensorChanges; i++)
{
int jointIndex = clientCmd.m_createSensorArguments.m_jointIndex[i];
if (clientCmd.m_createSensorArguments.m_enableJointForceSensor[i])
{
if (mb->getLink(jointIndex).m_jointFeedback)
{
b3Warning("CMD_CREATE_SENSOR: sensor for joint [%d] already enabled", jointIndex);
}
else
{
btMultiBodyJointFeedback* fb = new btMultiBodyJointFeedback();
fb->m_reactionForces.setZero();
mb->getLink(jointIndex).m_jointFeedback = fb;
m_data->m_multiBodyJointFeedbacks.push_back(fb);
};
}
else
{
if (mb->getLink(jointIndex).m_jointFeedback)
{
m_data->m_multiBodyJointFeedbacks.remove(mb->getLink(jointIndex).m_jointFeedback);
delete mb->getLink(jointIndex).m_jointFeedback;
mb->getLink(jointIndex).m_jointFeedback = 0;
}
else
{
b3Warning("CMD_CREATE_SENSOR: cannot perform sensor removal request, no sensor on joint [%d]", jointIndex);
};
}
}
}
else
{
b3Warning("No btMultiBody in the world. btRigidBody/btTypedConstraint sensor not hooked up yet");
}
#if 0
//todo(erwincoumans) here is some sample code to hook up a force/torque sensor for btTypedConstraint/btRigidBody
/*
for (int i=0;i<m_data->m_dynamicsWorld->getNumConstraints();i++)
{
btTypedConstraint* c = m_data->m_dynamicsWorld->getConstraint(i);
btJointFeedback* fb = new btJointFeedback();
m_data->m_jointFeedbacks.push_back(fb);
c->setJointFeedback(fb);
}
*/
#endif
serverStatusOut.m_type = CMD_CLIENT_COMMAND_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processProfileTimingCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
{
if (clientCmd.m_profile.m_type == 0)
{
char** eventNamePtr = m_data->m_profileEvents[clientCmd.m_profile.m_name];
char* eventName = 0;
if (eventNamePtr)
{
eventName = *eventNamePtr;
}
else
{
int len = strlen(clientCmd.m_profile.m_name);
eventName = new char[len + 1];
strcpy(eventName, clientCmd.m_profile.m_name);
eventName[len] = 0;
m_data->m_profileEvents.insert(eventName, eventName);
}
b3EnterProfileZone(eventName);
}
if (clientCmd.m_profile.m_type == 1)
{
b3LeaveProfileZone();
}
}
serverStatusOut.m_type = CMD_CLIENT_COMMAND_COMPLETED;
hasStatus = true;
return hasStatus;
}
void setDefaultRootWorldAABB(SharedMemoryStatus& serverCmd)
{
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[0] = 0;
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[1] = 0;
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[2] = 0;
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[0] = -1;
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[1] = -1;
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[2] = -1;
}
bool PhysicsServerCommandProcessor::processRequestCollisionInfoCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverStatusOut.m_type = CMD_REQUEST_COLLISION_INFO_FAILED;
hasStatus = true;
int bodyUniqueId = clientCmd.m_requestCollisionInfoArgs.m_bodyUniqueId;
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (body && body->m_multiBody)
{
btMultiBody* mb = body->m_multiBody;
serverStatusOut.m_type = CMD_REQUEST_COLLISION_INFO_COMPLETED;
serverCmd.m_sendCollisionInfoArgs.m_numLinks = body->m_multiBody->getNumLinks();
setDefaultRootWorldAABB(serverCmd);
if (body->m_multiBody->getBaseCollider())
{
btTransform tr;
tr.setOrigin(mb->getBasePos());
tr.setRotation(mb->getWorldToBaseRot().inverse());
btVector3 aabbMin, aabbMax;
body->m_multiBody->getBaseCollider()->getCollisionShape()->getAabb(tr, aabbMin, aabbMax);
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[0] = aabbMin[0];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[1] = aabbMin[1];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[2] = aabbMin[2];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[0] = aabbMax[0];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[1] = aabbMax[1];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[2] = aabbMax[2];
}
for (int l = 0; l < mb->getNumLinks(); l++)
{
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMin[3 * l + 0] = 0;
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMin[3 * l + 1] = 0;
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMin[3 * l + 2] = 0;
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMax[3 * l + 0] = -1;
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMax[3 * l + 1] = -1;
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMax[3 * l + 2] = -1;
if (body->m_multiBody->getLink(l).m_collider)
{
btVector3 aabbMin, aabbMax;
body->m_multiBody->getLinkCollider(l)->getCollisionShape()->getAabb(mb->getLink(l).m_cachedWorldTransform, aabbMin, aabbMax);
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMin[3 * l + 0] = aabbMin[0];
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMin[3 * l + 1] = aabbMin[1];
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMin[3 * l + 2] = aabbMin[2];
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMax[3 * l + 0] = aabbMax[0];
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMax[3 * l + 1] = aabbMax[1];
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMax[3 * l + 2] = aabbMax[2];
}
}
}
else if (body && body->m_rigidBody)
{
btRigidBody* rb = body->m_rigidBody;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverStatusOut.m_type = CMD_REQUEST_COLLISION_INFO_COMPLETED;
serverCmd.m_sendCollisionInfoArgs.m_numLinks = 0;
setDefaultRootWorldAABB(serverCmd);
if (rb->getCollisionShape())
{
btTransform tr = rb->getWorldTransform();
btVector3 aabbMin, aabbMax;
rb->getCollisionShape()->getAabb(tr, aabbMin, aabbMax);
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[0] = aabbMin[0];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[1] = aabbMin[1];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[2] = aabbMin[2];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[0] = aabbMax[0];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[1] = aabbMax[1];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[2] = aabbMax[2];
}
}
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
else if (body && body->m_softBody)
{
btSoftBody* sb = body->m_softBody;
serverCmd.m_sendCollisionInfoArgs.m_numLinks = 0;
btVector3 aabbMin, aabbMax;
sb->getAabb(aabbMin, aabbMax);
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[0] = aabbMin[0];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[1] = aabbMin[1];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[2] = aabbMin[2];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[0] = aabbMax[0];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[1] = aabbMax[1];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[2] = aabbMax[2];
SharedMemoryStatus& serverCmd = serverStatusOut;
serverStatusOut.m_type = CMD_REQUEST_COLLISION_INFO_COMPLETED;
}
#endif
return hasStatus;
}
bool PhysicsServerCommandProcessor::processForwardDynamicsCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_STEP_FORWARD_SIMULATION");
if (m_data->m_verboseOutput)
{
b3Printf("Step simulation request");
b3Printf("CMD_STEP_FORWARD_SIMULATION clientCmd = %d\n", clientCmd.m_sequenceNumber);
}
///todo(erwincoumans) move this damping inside Bullet
for (int i = 0; i < m_data->m_dynamicsWorld->getNumMultibodies(); i++)
{
btMultiBody* mb = m_data->m_dynamicsWorld->getMultiBody(i);
for (int l = 0; l < mb->getNumLinks(); l++)
{
for (int d = 0; d < mb->getLink(l).m_dofCount; d++)
{
double damping_coefficient = mb->getLink(l).m_jointDamping;
double damping = -damping_coefficient * mb->getJointVelMultiDof(l)[d];
mb->addJointTorqueMultiDof(l, d, damping);
}
}
}
btScalar deltaTimeScaled = m_data->m_physicsDeltaTime * simTimeScalingFactor;
int numSteps = 0;
if (m_data->m_numSimulationSubSteps > 0)
{
numSteps = m_data->m_dynamicsWorld->stepSimulation(deltaTimeScaled, m_data->m_numSimulationSubSteps, m_data->m_physicsDeltaTime / m_data->m_numSimulationSubSteps);
m_data->m_simulationTimestamp += deltaTimeScaled;
}
else
{
numSteps = m_data->m_dynamicsWorld->stepSimulation(deltaTimeScaled, 0);
m_data->m_simulationTimestamp += deltaTimeScaled;
}
if (numSteps > 0)
{
addBodyChangedNotifications();
}
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_forwardDynamicsAnalyticsArgs.m_numSteps = numSteps;
btAlignedObjectArray<btSolverAnalyticsData> islandAnalyticsData;
m_data->m_dynamicsWorld->getAnalyticsData(islandAnalyticsData);
serverCmd.m_forwardDynamicsAnalyticsArgs.m_numIslands = islandAnalyticsData.size();
int numIslands = btMin(islandAnalyticsData.size(), MAX_ISLANDS_ANALYTICS);
for (int i = 0; i < numIslands; i++)
{
serverCmd.m_forwardDynamicsAnalyticsArgs.m_numSolverCalls = islandAnalyticsData[i].m_numSolverCalls;
serverCmd.m_forwardDynamicsAnalyticsArgs.m_islandData[i].m_islandId = islandAnalyticsData[i].m_islandId;
serverCmd.m_forwardDynamicsAnalyticsArgs.m_islandData[i].m_numBodies = islandAnalyticsData[i].m_numBodies;
serverCmd.m_forwardDynamicsAnalyticsArgs.m_islandData[i].m_numIterationsUsed = islandAnalyticsData[i].m_numIterationsUsed;
serverCmd.m_forwardDynamicsAnalyticsArgs.m_islandData[i].m_remainingLeastSquaresResidual = islandAnalyticsData[i].m_remainingLeastSquaresResidual;
serverCmd.m_forwardDynamicsAnalyticsArgs.m_islandData[i].m_numContactManifolds = islandAnalyticsData[i].m_numContactManifolds;
}
serverCmd.m_type = CMD_STEP_FORWARD_SIMULATION_COMPLETED;
m_data->m_remoteSyncTransformTime += deltaTimeScaled;
if (m_data->m_remoteSyncTransformTime >= m_data->m_remoteSyncTransformInterval)
{
m_data->m_remoteSyncTransformTime = 0;
syncPhysicsToGraphics2();
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestInternalDataCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_INTERNAL_DATA");
//todo: also check version etc?
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_REQUEST_INTERNAL_DATA_FAILED;
int sz = btDefaultSerializer::getMemoryDnaSizeInBytes();
const char* memDna = btDefaultSerializer::getMemoryDna();
if (sz < bufferSizeInBytes)
{
for (int i = 0; i < sz; i++)
{
bufferServerToClient[i] = memDna[i];
}
serverCmd.m_type = CMD_REQUEST_INTERNAL_DATA_COMPLETED;
serverCmd.m_numDataStreamBytes = sz;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processChangeDynamicsInfoCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_CHANGE_DYNAMICS_INFO");
int bodyUniqueId = clientCmd.m_changeDynamicsInfoArgs.m_bodyUniqueId;
int linkIndex = clientCmd.m_changeDynamicsInfoArgs.m_linkIndex;
double mass = clientCmd.m_changeDynamicsInfoArgs.m_mass;
double lateralFriction = clientCmd.m_changeDynamicsInfoArgs.m_lateralFriction;
double spinningFriction = clientCmd.m_changeDynamicsInfoArgs.m_spinningFriction;
double rollingFriction = clientCmd.m_changeDynamicsInfoArgs.m_rollingFriction;
double restitution = clientCmd.m_changeDynamicsInfoArgs.m_restitution;
btVector3 newLocalInertiaDiagonal(clientCmd.m_changeDynamicsInfoArgs.m_localInertiaDiagonal[0],
clientCmd.m_changeDynamicsInfoArgs.m_localInertiaDiagonal[1],
clientCmd.m_changeDynamicsInfoArgs.m_localInertiaDiagonal[2]);
btVector3 anisotropicFriction(clientCmd.m_changeDynamicsInfoArgs.m_anisotropicFriction[0],
clientCmd.m_changeDynamicsInfoArgs.m_anisotropicFriction[1],
clientCmd.m_changeDynamicsInfoArgs.m_anisotropicFriction[2]);
btAssert(bodyUniqueId >= 0);
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (body && body->m_multiBody)
{
btMultiBody* mb = body->m_multiBody;
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_ACTIVATION_STATE)
{
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateWakeUp)
{
mb->wakeUp();
}
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateSleep)
{
mb->goToSleep();
}
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateEnableSleeping)
{
mb->setCanSleep(true);
}
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateDisableSleeping)
{
mb->setCanSleep(false);
}
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateEnableWakeup)
{
mb->setCanWakeup(true);
}
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateDisableWakeup)
{
mb->setCanWakeup(false);
}
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_LINEAR_DAMPING)
{
mb->setLinearDamping(clientCmd.m_changeDynamicsInfoArgs.m_linearDamping);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_ANGULAR_DAMPING)
{
mb->setAngularDamping(clientCmd.m_changeDynamicsInfoArgs.m_angularDamping);
}
if (linkIndex == -1)
{
if (mb->getBaseCollider())
{
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_RESTITUTION)
{
mb->getBaseCollider()->setRestitution(restitution);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_CONTACT_STIFFNESS_AND_DAMPING)
{
mb->getBaseCollider()->setContactStiffnessAndDamping(clientCmd.m_changeDynamicsInfoArgs.m_contactStiffness, clientCmd.m_changeDynamicsInfoArgs.m_contactDamping);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_LATERAL_FRICTION)
{
mb->getBaseCollider()->setFriction(lateralFriction);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_SPINNING_FRICTION)
{
mb->getBaseCollider()->setSpinningFriction(spinningFriction);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_ROLLING_FRICTION)
{
mb->getBaseCollider()->setRollingFriction(rollingFriction);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_FRICTION_ANCHOR)
{
if (clientCmd.m_changeDynamicsInfoArgs.m_frictionAnchor)
{
mb->getBaseCollider()->setCollisionFlags(mb->getBaseCollider()->getCollisionFlags() | btCollisionObject::CF_HAS_FRICTION_ANCHOR);
}
else
{
mb->getBaseCollider()->setCollisionFlags(mb->getBaseCollider()->getCollisionFlags() & ~btCollisionObject::CF_HAS_FRICTION_ANCHOR);
}
}
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_MASS)
{
mb->setBaseMass(mass);
if (mb->getBaseCollider() && mb->getBaseCollider()->getCollisionShape())
{
btVector3 localInertia;
mb->getBaseCollider()->getCollisionShape()->calculateLocalInertia(mass, localInertia);
mb->setBaseInertia(localInertia);
}
//handle switch from static/fixedBase to dynamic and vise-versa
if (mass > 0)
{
bool isDynamic = true;
if (mb->hasFixedBase())
{
int collisionFilterGroup = isDynamic ? int(btBroadphaseProxy::DefaultFilter) : int(btBroadphaseProxy::StaticFilter);
int collisionFilterMask = isDynamic ? int(btBroadphaseProxy::AllFilter) : int(btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter);
m_data->m_dynamicsWorld->removeCollisionObject(mb->getBaseCollider());
int oldFlags = mb->getBaseCollider()->getCollisionFlags();
mb->getBaseCollider()->setCollisionFlags(oldFlags & ~btCollisionObject::CF_STATIC_OBJECT);
mb->setFixedBase(false);
m_data->m_dynamicsWorld->addCollisionObject(mb->getBaseCollider(), collisionFilterGroup, collisionFilterMask);
}
}
else
{
if (!mb->hasFixedBase())
{
bool isDynamic = false;
int collisionFilterGroup = isDynamic ? int(btBroadphaseProxy::DefaultFilter) : int(btBroadphaseProxy::StaticFilter);
int collisionFilterMask = isDynamic ? int(btBroadphaseProxy::AllFilter) : int(btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter);
int oldFlags = mb->getBaseCollider()->getCollisionFlags();
mb->getBaseCollider()->setCollisionFlags(oldFlags | btCollisionObject::CF_STATIC_OBJECT);
m_data->m_dynamicsWorld->removeCollisionObject(mb->getBaseCollider());
mb->setFixedBase(true);
m_data->m_dynamicsWorld->addCollisionObject(mb->getBaseCollider(), collisionFilterGroup, collisionFilterMask);
}
}
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_LOCAL_INERTIA_DIAGONAL)
{
mb->setBaseInertia(newLocalInertiaDiagonal);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_ANISOTROPIC_FRICTION)
{
mb->getBaseCollider()->setAnisotropicFriction(anisotropicFriction);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_MAX_JOINT_VELOCITY)
{
mb->setMaxCoordinateVelocity(clientCmd.m_changeDynamicsInfoArgs.m_maxJointVelocity);
}
}
else
{
if (linkIndex >= 0 && linkIndex < mb->getNumLinks())
{
if (mb->getLinkCollider(linkIndex))
{
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_RESTITUTION)
{
mb->getLinkCollider(linkIndex)->setRestitution(restitution);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_SPINNING_FRICTION)
{
mb->getLinkCollider(linkIndex)->setSpinningFriction(spinningFriction);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_ROLLING_FRICTION)
{
mb->getLinkCollider(linkIndex)->setRollingFriction(rollingFriction);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_FRICTION_ANCHOR)
{
if (clientCmd.m_changeDynamicsInfoArgs.m_frictionAnchor)
{
mb->getLinkCollider(linkIndex)->setCollisionFlags(mb->getLinkCollider(linkIndex)->getCollisionFlags() | btCollisionObject::CF_HAS_FRICTION_ANCHOR);
}
else
{
mb->getLinkCollider(linkIndex)->setCollisionFlags(mb->getLinkCollider(linkIndex)->getCollisionFlags() & ~btCollisionObject::CF_HAS_FRICTION_ANCHOR);
}
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_LATERAL_FRICTION)
{
mb->getLinkCollider(linkIndex)->setFriction(lateralFriction);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_CONTACT_STIFFNESS_AND_DAMPING)
{
mb->getLinkCollider(linkIndex)->setContactStiffnessAndDamping(clientCmd.m_changeDynamicsInfoArgs.m_contactStiffness, clientCmd.m_changeDynamicsInfoArgs.m_contactDamping);
}
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_JOINT_DAMPING)
{
mb->getLink(linkIndex).m_jointDamping = clientCmd.m_changeDynamicsInfoArgs.m_jointDamping;
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_MASS)
{
mb->getLink(linkIndex).m_mass = mass;
if (mb->getLinkCollider(linkIndex) && mb->getLinkCollider(linkIndex)->getCollisionShape())
{
btVector3 localInertia;
mb->getLinkCollider(linkIndex)->getCollisionShape()->calculateLocalInertia(mass, localInertia);
mb->getLink(linkIndex).m_inertiaLocal = localInertia;
}
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_LOCAL_INERTIA_DIAGONAL)
{
mb->getLink(linkIndex).m_inertiaLocal = newLocalInertiaDiagonal;
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_ANISOTROPIC_FRICTION)
{
mb->getLinkCollider(linkIndex)->setAnisotropicFriction(anisotropicFriction);
}
}
}
}
else
{
btRigidBody* rb = 0;
if (body && body->m_rigidBody)
{
if (linkIndex == -1)
{
rb = body->m_rigidBody;
}
else
{
if (linkIndex >= 0 && linkIndex < body->m_rigidBodyJoints.size())
{
btRigidBody* parentRb = &body->m_rigidBodyJoints[linkIndex]->getRigidBodyA();
btRigidBody* childRb = &body->m_rigidBodyJoints[linkIndex]->getRigidBodyB();
rb = childRb;
}
}
}
if (rb)
{
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_ACTIVATION_STATE)
{
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateEnableSleeping)
{
rb->forceActivationState(ACTIVE_TAG);
}
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateDisableSleeping)
{
rb->forceActivationState(DISABLE_DEACTIVATION);
}
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateWakeUp)
{
rb->forceActivationState(ACTIVE_TAG);
}
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateSleep)
{
rb->forceActivationState(ISLAND_SLEEPING);
}
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_LINEAR_DAMPING)
{
btScalar angDamping = rb->getAngularDamping();
rb->setDamping(clientCmd.m_changeDynamicsInfoArgs.m_linearDamping, angDamping);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_ANGULAR_DAMPING)
{
btScalar linDamping = rb->getLinearDamping();
rb->setDamping(linDamping, clientCmd.m_changeDynamicsInfoArgs.m_angularDamping);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_CONTACT_STIFFNESS_AND_DAMPING)
{
rb->setContactStiffnessAndDamping(clientCmd.m_changeDynamicsInfoArgs.m_contactStiffness, clientCmd.m_changeDynamicsInfoArgs.m_contactDamping);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_RESTITUTION)
{
rb->setRestitution(restitution);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_LATERAL_FRICTION)
{
rb->setFriction(lateralFriction);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_SPINNING_FRICTION)
{
rb->setSpinningFriction(spinningFriction);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_ROLLING_FRICTION)
{
rb->setRollingFriction(rollingFriction);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_FRICTION_ANCHOR)
{
if (clientCmd.m_changeDynamicsInfoArgs.m_frictionAnchor)
{
rb->setCollisionFlags(rb->getCollisionFlags() | btCollisionObject::CF_HAS_FRICTION_ANCHOR);
}
else
{
rb->setCollisionFlags(rb->getCollisionFlags() & ~btCollisionObject::CF_HAS_FRICTION_ANCHOR);
}
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_MASS)
{
btVector3 localInertia;
if (rb->getCollisionShape())
{
rb->getCollisionShape()->calculateLocalInertia(mass, localInertia);
}
rb->setMassProps(mass, localInertia);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_LOCAL_INERTIA_DIAGONAL)
{
btScalar orgMass = rb->getInvMass();
if (orgMass > 0)
{
rb->setMassProps(mass, newLocalInertiaDiagonal);
}
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_ANISOTROPIC_FRICTION)
{
rb->setAnisotropicFriction(anisotropicFriction);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_CONTACT_PROCESSING_THRESHOLD)
{
rb->setContactProcessingThreshold(clientCmd.m_changeDynamicsInfoArgs.m_contactProcessingThreshold);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_CCD_SWEPT_SPHERE_RADIUS)
{
rb->setCcdSweptSphereRadius(clientCmd.m_changeDynamicsInfoArgs.m_ccdSweptSphereRadius);
//for a given sphere radius, use a motion threshold of half the radius, before the ccd algorithm is enabled
rb->setCcdMotionThreshold(clientCmd.m_changeDynamicsInfoArgs.m_ccdSweptSphereRadius / 2.);
}
}
}
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CLIENT_COMMAND_COMPLETED;
b3Notification notification;
notification.m_notificationType = LINK_DYNAMICS_CHANGED;
notification.m_linkArgs.m_bodyUniqueId = bodyUniqueId;
notification.m_linkArgs.m_linkIndex = linkIndex;
m_data->m_pluginManager.addNotification(notification);
return hasStatus;
}
bool PhysicsServerCommandProcessor::processSetAdditionalSearchPathCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_SET_ADDITIONAL_SEARCH_PATH");
b3ResourcePath::setAdditionalSearchPath(clientCmd.m_searchPathArgs.m_path);
serverStatusOut.m_type = CMD_CLIENT_COMMAND_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processGetDynamicsInfoCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_GET_DYNAMICS_INFO_FAILED;
int bodyUniqueId = clientCmd.m_getDynamicsInfoArgs.m_bodyUniqueId;
int linkIndex = clientCmd.m_getDynamicsInfoArgs.m_linkIndex;
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (body && body->m_multiBody)
{
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_GET_DYNAMICS_INFO_COMPLETED;
serverCmd.m_dynamicsInfo.m_bodyType = BT_MULTI_BODY;
btMultiBody* mb = body->m_multiBody;
if (linkIndex == -1)
{
serverCmd.m_dynamicsInfo.m_mass = mb->getBaseMass();
if (mb->getBaseCollider())
{
serverCmd.m_dynamicsInfo.m_activationState = mb->getBaseCollider()->getActivationState();
serverCmd.m_dynamicsInfo.m_contactProcessingThreshold = mb->getBaseCollider()->getContactProcessingThreshold();
serverCmd.m_dynamicsInfo.m_ccdSweptSphereRadius = mb->getBaseCollider()->getCcdSweptSphereRadius();
serverCmd.m_dynamicsInfo.m_frictionAnchor = mb->getBaseCollider()->getCollisionFlags() & btCollisionObject::CF_HAS_FRICTION_ANCHOR;
}
else
{
serverCmd.m_dynamicsInfo.m_activationState = 0;
serverCmd.m_dynamicsInfo.m_contactProcessingThreshold = 0;
serverCmd.m_dynamicsInfo.m_ccdSweptSphereRadius = 0;
serverCmd.m_dynamicsInfo.m_frictionAnchor = 0;
}
serverCmd.m_dynamicsInfo.m_localInertialDiagonal[0] = mb->getBaseInertia()[0];
serverCmd.m_dynamicsInfo.m_localInertialDiagonal[1] = mb->getBaseInertia()[1];
serverCmd.m_dynamicsInfo.m_localInertialDiagonal[2] = mb->getBaseInertia()[2];
serverCmd.m_dynamicsInfo.m_lateralFrictionCoeff = mb->getBaseCollider()->getFriction();
serverCmd.m_dynamicsInfo.m_localInertialFrame[0] = body->m_rootLocalInertialFrame.getOrigin()[0];
serverCmd.m_dynamicsInfo.m_localInertialFrame[1] = body->m_rootLocalInertialFrame.getOrigin()[1];
serverCmd.m_dynamicsInfo.m_localInertialFrame[2] = body->m_rootLocalInertialFrame.getOrigin()[2];
serverCmd.m_dynamicsInfo.m_localInertialFrame[3] = body->m_rootLocalInertialFrame.getRotation()[0];
serverCmd.m_dynamicsInfo.m_localInertialFrame[4] = body->m_rootLocalInertialFrame.getRotation()[1];
serverCmd.m_dynamicsInfo.m_localInertialFrame[5] = body->m_rootLocalInertialFrame.getRotation()[2];
serverCmd.m_dynamicsInfo.m_localInertialFrame[6] = body->m_rootLocalInertialFrame.getRotation()[3];
serverCmd.m_dynamicsInfo.m_angularDamping = body->m_multiBody->getAngularDamping();
serverCmd.m_dynamicsInfo.m_linearDamping = body->m_multiBody->getLinearDamping();
serverCmd.m_dynamicsInfo.m_restitution = mb->getBaseCollider()->getRestitution();
serverCmd.m_dynamicsInfo.m_rollingFrictionCoeff = mb->getBaseCollider()->getRollingFriction();
serverCmd.m_dynamicsInfo.m_spinningFrictionCoeff = mb->getBaseCollider()->getSpinningFriction();
if (mb->getBaseCollider()->getCollisionFlags() & btCollisionObject::CF_HAS_CONTACT_STIFFNESS_DAMPING)
{
serverCmd.m_dynamicsInfo.m_contactStiffness = mb->getBaseCollider()->getContactStiffness();
serverCmd.m_dynamicsInfo.m_contactDamping = mb->getBaseCollider()->getContactDamping();
}
else
{
serverCmd.m_dynamicsInfo.m_contactStiffness = -1;
serverCmd.m_dynamicsInfo.m_contactDamping = -1;
}
}
else
{
serverCmd.m_dynamicsInfo.m_mass = mb->getLinkMass(linkIndex);
if (mb->getLinkCollider(linkIndex))
{
serverCmd.m_dynamicsInfo.m_activationState = mb->getLinkCollider(linkIndex)->getActivationState();
serverCmd.m_dynamicsInfo.m_contactProcessingThreshold = mb->getLinkCollider(linkIndex)->getContactProcessingThreshold();
serverCmd.m_dynamicsInfo.m_ccdSweptSphereRadius = mb->getLinkCollider(linkIndex)->getCcdSweptSphereRadius();
serverCmd.m_dynamicsInfo.m_frictionAnchor = mb->getLinkCollider(linkIndex)->getCollisionFlags() & btCollisionObject::CF_HAS_FRICTION_ANCHOR;
}
else
{
serverCmd.m_dynamicsInfo.m_activationState = 0;
serverCmd.m_dynamicsInfo.m_contactProcessingThreshold = 0;
serverCmd.m_dynamicsInfo.m_ccdSweptSphereRadius = 0;
serverCmd.m_dynamicsInfo.m_frictionAnchor = 0;
}
serverCmd.m_dynamicsInfo.m_localInertialDiagonal[0] = mb->getLinkInertia(linkIndex)[0];
serverCmd.m_dynamicsInfo.m_localInertialDiagonal[1] = mb->getLinkInertia(linkIndex)[1];
serverCmd.m_dynamicsInfo.m_localInertialDiagonal[2] = mb->getLinkInertia(linkIndex)[2];
serverCmd.m_dynamicsInfo.m_localInertialFrame[0] = body->m_linkLocalInertialFrames[linkIndex].getOrigin()[0];
serverCmd.m_dynamicsInfo.m_localInertialFrame[1] = body->m_linkLocalInertialFrames[linkIndex].getOrigin()[1];
serverCmd.m_dynamicsInfo.m_localInertialFrame[2] = body->m_linkLocalInertialFrames[linkIndex].getOrigin()[2];
serverCmd.m_dynamicsInfo.m_localInertialFrame[3] = body->m_linkLocalInertialFrames[linkIndex].getRotation()[0];
serverCmd.m_dynamicsInfo.m_localInertialFrame[4] = body->m_linkLocalInertialFrames[linkIndex].getRotation()[1];
serverCmd.m_dynamicsInfo.m_localInertialFrame[5] = body->m_linkLocalInertialFrames[linkIndex].getRotation()[2];
serverCmd.m_dynamicsInfo.m_localInertialFrame[6] = body->m_linkLocalInertialFrames[linkIndex].getRotation()[3];
serverCmd.m_dynamicsInfo.m_angularDamping = body->m_multiBody->getAngularDamping();
serverCmd.m_dynamicsInfo.m_linearDamping = body->m_multiBody->getLinearDamping();
if (mb->getLinkCollider(linkIndex))
{
serverCmd.m_dynamicsInfo.m_lateralFrictionCoeff = mb->getLinkCollider(linkIndex)->getFriction();
serverCmd.m_dynamicsInfo.m_restitution = mb->getLinkCollider(linkIndex)->getRestitution();
serverCmd.m_dynamicsInfo.m_rollingFrictionCoeff = mb->getLinkCollider(linkIndex)->getRollingFriction();
serverCmd.m_dynamicsInfo.m_spinningFrictionCoeff = mb->getLinkCollider(linkIndex)->getSpinningFriction();
if (mb->getLinkCollider(linkIndex)->getCollisionFlags() & btCollisionObject::CF_HAS_CONTACT_STIFFNESS_DAMPING)
{
serverCmd.m_dynamicsInfo.m_contactStiffness = mb->getLinkCollider(linkIndex)->getContactStiffness();
serverCmd.m_dynamicsInfo.m_contactDamping = mb->getLinkCollider(linkIndex)->getContactDamping();
}
else
{
serverCmd.m_dynamicsInfo.m_contactStiffness = -1;
serverCmd.m_dynamicsInfo.m_contactDamping = -1;
}
}
else
{
b3Warning("The dynamic info requested is not available");
serverCmd.m_type = CMD_GET_DYNAMICS_INFO_FAILED;
}
}
hasStatus = true;
}
else if (body && body->m_rigidBody)
{
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_GET_DYNAMICS_INFO_COMPLETED;
serverCmd.m_dynamicsInfo.m_bodyType = BT_RIGID_BODY;
btRigidBody* rb = body->m_rigidBody;
serverCmd.m_dynamicsInfo.m_lateralFrictionCoeff = rb->getFriction();
serverCmd.m_dynamicsInfo.m_rollingFrictionCoeff = rb->getRollingFriction();
serverCmd.m_dynamicsInfo.m_spinningFrictionCoeff = rb->getSpinningFriction();
serverCmd.m_dynamicsInfo.m_angularDamping = rb->getAngularDamping();
serverCmd.m_dynamicsInfo.m_linearDamping = rb->getLinearDamping();
serverCmd.m_dynamicsInfo.m_mass = rb->getMass();
}
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
else if (body && body->m_softBody){
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_GET_DYNAMICS_INFO_COMPLETED;
serverCmd.m_dynamicsInfo.m_bodyType = BT_SOFT_BODY;
}
#endif
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestPhysicsSimulationParametersCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_REQUEST_PHYSICS_SIMULATION_PARAMETERS_COMPLETED;
serverCmd.m_simulationParameterResultArgs.m_allowedCcdPenetration = m_data->m_dynamicsWorld->getDispatchInfo().m_allowedCcdPenetration;
serverCmd.m_simulationParameterResultArgs.m_collisionFilterMode = m_data->m_broadphaseCollisionFilterCallback->m_filterMode;
serverCmd.m_simulationParameterResultArgs.m_deltaTime = m_data->m_physicsDeltaTime;
serverCmd.m_simulationParameterResultArgs.m_simulationTimestamp = m_data->m_simulationTimestamp;
serverCmd.m_simulationParameterResultArgs.m_contactBreakingThreshold = gContactBreakingThreshold;
serverCmd.m_simulationParameterResultArgs.m_contactSlop = m_data->m_dynamicsWorld->getSolverInfo().m_linearSlop;
serverCmd.m_simulationParameterResultArgs.m_enableSAT = m_data->m_dynamicsWorld->getDispatchInfo().m_enableSatConvex;
serverCmd.m_simulationParameterResultArgs.m_defaultGlobalCFM = m_data->m_dynamicsWorld->getSolverInfo().m_globalCfm;
serverCmd.m_simulationParameterResultArgs.m_defaultContactERP = m_data->m_dynamicsWorld->getSolverInfo().m_erp2;
serverCmd.m_simulationParameterResultArgs.m_defaultNonContactERP = m_data->m_dynamicsWorld->getSolverInfo().m_erp;
serverCmd.m_simulationParameterResultArgs.m_deltaTime = m_data->m_physicsDeltaTime;
serverCmd.m_simulationParameterResultArgs.m_deterministicOverlappingPairs = m_data->m_dynamicsWorld->getDispatchInfo().m_deterministicOverlappingPairs;
serverCmd.m_simulationParameterResultArgs.m_enableConeFriction = (m_data->m_dynamicsWorld->getSolverInfo().m_solverMode & SOLVER_DISABLE_IMPLICIT_CONE_FRICTION) ? 0 : 1;
serverCmd.m_simulationParameterResultArgs.m_enableFileCaching = b3IsFileCachingEnabled();
serverCmd.m_simulationParameterResultArgs.m_frictionCFM = m_data->m_dynamicsWorld->getSolverInfo().m_frictionCFM;
serverCmd.m_simulationParameterResultArgs.m_frictionERP = m_data->m_dynamicsWorld->getSolverInfo().m_frictionERP;
btVector3 grav = m_data->m_dynamicsWorld->getGravity();
serverCmd.m_simulationParameterResultArgs.m_gravityAcceleration[0] = grav[0];
serverCmd.m_simulationParameterResultArgs.m_gravityAcceleration[1] = grav[1];
serverCmd.m_simulationParameterResultArgs.m_gravityAcceleration[2] = grav[2];
serverCmd.m_simulationParameterResultArgs.m_internalSimFlags = gInternalSimFlags;
serverCmd.m_simulationParameterResultArgs.m_jointFeedbackMode = 0;
if (m_data->m_dynamicsWorld->getSolverInfo().m_jointFeedbackInWorldSpace)
{
serverCmd.m_simulationParameterResultArgs.m_jointFeedbackMode |= JOINT_FEEDBACK_IN_WORLD_SPACE;
}
if (m_data->m_dynamicsWorld->getSolverInfo().m_jointFeedbackInJointFrame)
{
serverCmd.m_simulationParameterResultArgs.m_jointFeedbackMode |= JOINT_FEEDBACK_IN_JOINT_FRAME;
}
serverCmd.m_simulationParameterResultArgs.m_numSimulationSubSteps = m_data->m_numSimulationSubSteps;
serverCmd.m_simulationParameterResultArgs.m_numSolverIterations = m_data->m_dynamicsWorld->getSolverInfo().m_numIterations;
serverCmd.m_simulationParameterResultArgs.m_restitutionVelocityThreshold = m_data->m_dynamicsWorld->getSolverInfo().m_restitutionVelocityThreshold;
serverCmd.m_simulationParameterResultArgs.m_solverResidualThreshold = m_data->m_dynamicsWorld->getSolverInfo().m_leastSquaresResidualThreshold;
serverCmd.m_simulationParameterResultArgs.m_splitImpulsePenetrationThreshold = m_data->m_dynamicsWorld->getSolverInfo().m_splitImpulsePenetrationThreshold;
serverCmd.m_simulationParameterResultArgs.m_useRealTimeSimulation = m_data->m_useRealTimeSimulation;
serverCmd.m_simulationParameterResultArgs.m_useSplitImpulse = m_data->m_dynamicsWorld->getSolverInfo().m_splitImpulse;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processSendPhysicsParametersCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_SEND_PHYSICS_SIMULATION_PARAMETERS");
if (clientCmd.m_updateFlags & SIM_PARAM_ENABLE_CONE_FRICTION)
{
if (clientCmd.m_physSimParamArgs.m_enableConeFriction)
{
m_data->m_dynamicsWorld->getSolverInfo().m_solverMode &= ~SOLVER_DISABLE_IMPLICIT_CONE_FRICTION;
}
else
{
m_data->m_dynamicsWorld->getSolverInfo().m_solverMode |= SOLVER_DISABLE_IMPLICIT_CONE_FRICTION;
}
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_DETERMINISTIC_OVERLAPPING_PAIRS)
{
m_data->m_dynamicsWorld->getDispatchInfo().m_deterministicOverlappingPairs = (clientCmd.m_physSimParamArgs.m_deterministicOverlappingPairs != 0);
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_CCD_ALLOWED_PENETRATION)
{
m_data->m_dynamicsWorld->getDispatchInfo().m_allowedCcdPenetration = clientCmd.m_physSimParamArgs.m_allowedCcdPenetration;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_JOINT_FEEDBACK_MODE)
{
m_data->m_dynamicsWorld->getSolverInfo().m_jointFeedbackInWorldSpace = (clientCmd.m_physSimParamArgs.m_jointFeedbackMode & JOINT_FEEDBACK_IN_WORLD_SPACE) != 0;
m_data->m_dynamicsWorld->getSolverInfo().m_jointFeedbackInJointFrame = (clientCmd.m_physSimParamArgs.m_jointFeedbackMode & JOINT_FEEDBACK_IN_JOINT_FRAME) != 0;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_DELTA_TIME)
{
m_data->m_physicsDeltaTime = clientCmd.m_physSimParamArgs.m_deltaTime;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_REAL_TIME_SIMULATION)
{
m_data->m_useRealTimeSimulation = (clientCmd.m_physSimParamArgs.m_useRealTimeSimulation != 0);
}
//see
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_INTERNAL_SIMULATION_FLAGS)
{
//these flags are for internal/temporary/easter-egg/experimental demo purposes, use at own risk
gInternalSimFlags = clientCmd.m_physSimParamArgs.m_internalSimFlags;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_GRAVITY)
{
btVector3 grav(clientCmd.m_physSimParamArgs.m_gravityAcceleration[0],
clientCmd.m_physSimParamArgs.m_gravityAcceleration[1],
clientCmd.m_physSimParamArgs.m_gravityAcceleration[2]);
this->m_data->m_dynamicsWorld->setGravity(grav);
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
btSoftMultiBodyDynamicsWorld* softWorld = getSoftWorld();
if (softWorld)
{
softWorld->getWorldInfo().m_gravity = grav;
}
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
deformWorld->getWorldInfo().m_gravity = grav;
for (int i = 0; i < m_data->m_lf.size(); ++i)
{
btDeformableLagrangianForce* force = m_data->m_lf[i];
if (force->getForceType() == BT_GRAVITY_FORCE)
{
btDeformableGravityForce* gforce = (btDeformableGravityForce*)force;
gforce->m_gravity = grav;
}
}
}
#endif
if (m_data->m_verboseOutput)
{
b3Printf("Updated Gravity: %f,%f,%f", grav[0], grav[1], grav[2]);
}
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_NUM_SOLVER_ITERATIONS)
{
m_data->m_dynamicsWorld->getSolverInfo().m_numIterations = clientCmd.m_physSimParamArgs.m_numSolverIterations;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_SOLVER_RESIDULAL_THRESHOLD)
{
m_data->m_dynamicsWorld->getSolverInfo().m_leastSquaresResidualThreshold = clientCmd.m_physSimParamArgs.m_solverResidualThreshold;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_CONTACT_BREAKING_THRESHOLD)
{
gContactBreakingThreshold = clientCmd.m_physSimParamArgs.m_contactBreakingThreshold;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_CONTACT_SLOP)
{
m_data->m_dynamicsWorld->getSolverInfo().m_linearSlop = clientCmd.m_physSimParamArgs.m_contactSlop;
}
if (clientCmd.m_updateFlags & SIM_PARAM_ENABLE_SAT)
{
m_data->m_dynamicsWorld->getDispatchInfo().m_enableSatConvex = clientCmd.m_physSimParamArgs.m_enableSAT != 0;
}
if (clientCmd.m_updateFlags & SIM_PARAM_CONSTRAINT_SOLVER_TYPE)
{
//check if the current type is different from requested one
if (m_data->m_constraintSolverType != clientCmd.m_physSimParamArgs.m_constraintSolverType)
{
m_data->m_constraintSolverType = clientCmd.m_physSimParamArgs.m_constraintSolverType;
btConstraintSolver* oldSolver = m_data->m_dynamicsWorld->getConstraintSolver();
btMultiBodyConstraintSolver* newSolver = 0;
switch (clientCmd.m_physSimParamArgs.m_constraintSolverType)
{
case eConstraintSolverLCP_SI:
{
newSolver = new btMultiBodyConstraintSolver;
b3Printf("PyBullet: Constraint Solver: btMultiBodyConstraintSolver\n");
break;
}
case eConstraintSolverLCP_PGS:
{
btSolveProjectedGaussSeidel* mlcp = new btSolveProjectedGaussSeidel();
newSolver = new btMultiBodyMLCPConstraintSolver(mlcp);
b3Printf("PyBullet: Constraint Solver: MLCP + PGS\n");
break;
}
case eConstraintSolverLCP_DANTZIG:
{
btDantzigSolver* mlcp = new btDantzigSolver();
newSolver = new btMultiBodyMLCPConstraintSolver(mlcp);
b3Printf("PyBullet: Constraint Solver: MLCP + Dantzig\n");
break;
}
case eConstraintSolverLCP_BLOCK_PGS:
{
break;
}
default:
{
}
};
if (newSolver)
{
delete oldSolver;
m_data->m_dynamicsWorld->setMultiBodyConstraintSolver(newSolver);
m_data->m_solver = newSolver;
printf("switched solver\n");
}
}
}
if (clientCmd.m_updateFlags & SIM_PARAM_CONSTRAINT_MIN_SOLVER_ISLAND_SIZE)
{
m_data->m_dynamicsWorld->getSolverInfo().m_minimumSolverBatchSize = clientCmd.m_physSimParamArgs.m_minimumSolverIslandSize;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_COLLISION_FILTER_MODE)
{
m_data->m_broadphaseCollisionFilterCallback->m_filterMode = clientCmd.m_physSimParamArgs.m_collisionFilterMode;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_USE_SPLIT_IMPULSE)
{
m_data->m_dynamicsWorld->getSolverInfo().m_splitImpulse = clientCmd.m_physSimParamArgs.m_useSplitImpulse;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_SPLIT_IMPULSE_PENETRATION_THRESHOLD)
{
m_data->m_dynamicsWorld->getSolverInfo().m_splitImpulsePenetrationThreshold = clientCmd.m_physSimParamArgs.m_splitImpulsePenetrationThreshold;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_NUM_SIMULATION_SUB_STEPS)
{
m_data->m_numSimulationSubSteps = clientCmd.m_physSimParamArgs.m_numSimulationSubSteps;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_DEFAULT_CONTACT_ERP)
{
m_data->m_dynamicsWorld->getSolverInfo().m_erp2 = clientCmd.m_physSimParamArgs.m_defaultContactERP;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_DEFAULT_NON_CONTACT_ERP)
{
m_data->m_dynamicsWorld->getSolverInfo().m_erp = clientCmd.m_physSimParamArgs.m_defaultNonContactERP;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_DEFAULT_FRICTION_ERP)
{
m_data->m_dynamicsWorld->getSolverInfo().m_frictionERP = clientCmd.m_physSimParamArgs.m_frictionERP;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_DEFAULT_GLOBAL_CFM)
{
m_data->m_dynamicsWorld->getSolverInfo().m_globalCfm = clientCmd.m_physSimParamArgs.m_defaultGlobalCFM;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_DEFAULT_FRICTION_CFM)
{
m_data->m_dynamicsWorld->getSolverInfo().m_frictionCFM = clientCmd.m_physSimParamArgs.m_frictionCFM;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_SPARSE_SDF)
{
#ifndef SKIP_DEFORMABLE_BODY
{
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
deformWorld ->getWorldInfo().m_sparsesdf.setDefaultVoxelsz(clientCmd.m_physSimParamArgs.m_sparseSdfVoxelSize);
deformWorld ->getWorldInfo().m_sparsesdf.Reset();
}
}
#endif
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
{
btSoftMultiBodyDynamicsWorld* softWorld = getSoftWorld();
if (softWorld)
{
softWorld->getWorldInfo().m_sparsesdf.setDefaultVoxelsz(clientCmd.m_physSimParamArgs.m_sparseSdfVoxelSize);
softWorld->getWorldInfo().m_sparsesdf.Reset();
}
}
#endif
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_RESTITUTION_VELOCITY_THRESHOLD)
{
m_data->m_dynamicsWorld->getSolverInfo().m_restitutionVelocityThreshold = clientCmd.m_physSimParamArgs.m_restitutionVelocityThreshold;
}
if (clientCmd.m_updateFlags & SIM_PARAM_ENABLE_FILE_CACHING)
{
b3EnableFileCaching(clientCmd.m_physSimParamArgs.m_enableFileCaching);
m_data->m_pluginManager.getFileIOInterface()->enableFileCaching(clientCmd.m_physSimParamArgs.m_enableFileCaching != 0);
}
if (clientCmd.m_updateFlags & SIM_PARAM_REPORT_CONSTRAINT_SOLVER_ANALYTICS)
{
m_data->m_dynamicsWorld->getSolverInfo().m_reportSolverAnalytics = clientCmd.m_physSimParamArgs.m_reportSolverAnalytics;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_WARM_STARTING_FACTOR)
{
m_data->m_dynamicsWorld->getSolverInfo().m_warmstartingFactor = clientCmd.m_physSimParamArgs.m_warmStartingFactor;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_ARTICULATED_WARM_STARTING_FACTOR)
{
m_data->m_dynamicsWorld->getSolverInfo().m_solverMode |= SOLVER_USE_ARTICULATED_WARMSTARTING;
m_data->m_dynamicsWorld->getSolverInfo().m_articulatedWarmstartingFactor = clientCmd.m_physSimParamArgs.m_articulatedWarmStartingFactor;
}
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CLIENT_COMMAND_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processInitPoseCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_INIT_POSE");
if (m_data->m_verboseOutput)
{
b3Printf("Server Init Pose not implemented yet");
}
int bodyUniqueId = clientCmd.m_initPoseArgs.m_bodyUniqueId;
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
btVector3 baseLinVel(0, 0, 0);
btVector3 baseAngVel(0, 0, 0);
if (clientCmd.m_updateFlags & INIT_POSE_HAS_BASE_LINEAR_VELOCITY)
{
baseLinVel.setValue(clientCmd.m_initPoseArgs.m_initialStateQdot[0],
clientCmd.m_initPoseArgs.m_initialStateQdot[1],
clientCmd.m_initPoseArgs.m_initialStateQdot[2]);
}
if (clientCmd.m_updateFlags & INIT_POSE_HAS_BASE_ANGULAR_VELOCITY)
{
baseAngVel.setValue(clientCmd.m_initPoseArgs.m_initialStateQdot[3],
clientCmd.m_initPoseArgs.m_initialStateQdot[4],
clientCmd.m_initPoseArgs.m_initialStateQdot[5]);
}
btVector3 basePos(0, 0, 0);
if (clientCmd.m_updateFlags & INIT_POSE_HAS_INITIAL_POSITION)
{
basePos = btVector3(
clientCmd.m_initPoseArgs.m_initialStateQ[0],
clientCmd.m_initPoseArgs.m_initialStateQ[1],
clientCmd.m_initPoseArgs.m_initialStateQ[2]);
}
btQuaternion baseOrn(0, 0, 0, 1);
if (clientCmd.m_updateFlags & INIT_POSE_HAS_INITIAL_ORIENTATION)
{
baseOrn.setValue(clientCmd.m_initPoseArgs.m_initialStateQ[3],
clientCmd.m_initPoseArgs.m_initialStateQ[4],
clientCmd.m_initPoseArgs.m_initialStateQ[5],
clientCmd.m_initPoseArgs.m_initialStateQ[6]);
}
if (body && body->m_multiBody)
{
btMultiBody* mb = body->m_multiBody;
if (clientCmd.m_updateFlags & INIT_POSE_HAS_BASE_LINEAR_VELOCITY)
{
mb->setBaseVel(baseLinVel);
}
if (clientCmd.m_updateFlags & INIT_POSE_HAS_BASE_ANGULAR_VELOCITY)
{
mb->setBaseOmega(baseAngVel);
}
if (clientCmd.m_updateFlags & INIT_POSE_HAS_INITIAL_POSITION)
{
btVector3 zero(0, 0, 0);
btAssert(clientCmd.m_initPoseArgs.m_hasInitialStateQ[0] &&
clientCmd.m_initPoseArgs.m_hasInitialStateQ[1] &&
clientCmd.m_initPoseArgs.m_hasInitialStateQ[2]);
mb->setBaseVel(baseLinVel);
mb->setBasePos(basePos);
}
if (clientCmd.m_updateFlags & INIT_POSE_HAS_INITIAL_ORIENTATION)
{
btAssert(clientCmd.m_initPoseArgs.m_hasInitialStateQ[3] &&
clientCmd.m_initPoseArgs.m_hasInitialStateQ[4] &&
clientCmd.m_initPoseArgs.m_hasInitialStateQ[5] &&
clientCmd.m_initPoseArgs.m_hasInitialStateQ[6]);
mb->setBaseOmega(baseAngVel);
btQuaternion invOrn(baseOrn);
mb->setWorldToBaseRot(invOrn.inverse());
}
if (clientCmd.m_updateFlags & INIT_POSE_HAS_JOINT_STATE)
{
int uDofIndex = 6;
int posVarCountIndex = 7;
for (int i = 0; i < mb->getNumLinks(); i++)
{
int posVarCount = mb->getLink(i).m_posVarCount;
bool hasPosVar = posVarCount > 0;
for (int j = 0; j < posVarCount; j++)
{
if (clientCmd.m_initPoseArgs.m_hasInitialStateQ[posVarCountIndex + j] == 0)
{
hasPosVar = false;
break;
}
}
if (hasPosVar)
{
if (mb->getLink(i).m_dofCount == 1)
{
mb->setJointPos(i, clientCmd.m_initPoseArgs.m_initialStateQ[posVarCountIndex]);
mb->setJointVel(i, 0); //backwards compatibility
}
if (mb->getLink(i).m_dofCount == 3)
{
btQuaternion q(
clientCmd.m_initPoseArgs.m_initialStateQ[posVarCountIndex],
clientCmd.m_initPoseArgs.m_initialStateQ[posVarCountIndex + 1],
clientCmd.m_initPoseArgs.m_initialStateQ[posVarCountIndex + 2],
clientCmd.m_initPoseArgs.m_initialStateQ[posVarCountIndex + 3]);
q.normalize();
mb->setJointPosMultiDof(i, &q[0]);
double vel[6] = {0, 0, 0, 0, 0, 0};
mb->setJointVelMultiDof(i, vel);
}
}
bool hasVel = true;
for (int j = 0; j < mb->getLink(i).m_dofCount; j++)
{
if (clientCmd.m_initPoseArgs.m_hasInitialStateQdot[uDofIndex + j] == 0)
{
hasVel = false;
break;
}
}
if (hasVel)
{
if (mb->getLink(i).m_dofCount == 1)
{
btScalar vel = clientCmd.m_initPoseArgs.m_initialStateQdot[uDofIndex];
mb->setJointVel(i, vel);
}
if (mb->getLink(i).m_dofCount == 3)
{
mb->setJointVelMultiDof(i, &clientCmd.m_initPoseArgs.m_initialStateQdot[uDofIndex]);
}
}
posVarCountIndex += mb->getLink(i).m_posVarCount;
uDofIndex += mb->getLink(i).m_dofCount;
}
}
btAlignedObjectArray<btQuaternion> scratch_q;
btAlignedObjectArray<btVector3> scratch_m;
mb->forwardKinematics(scratch_q, scratch_m);
int nLinks = mb->getNumLinks();
scratch_q.resize(nLinks + 1);
scratch_m.resize(nLinks + 1);
mb->updateCollisionObjectWorldTransforms(scratch_q, scratch_m);
}
if (body && body->m_rigidBody)
{
if (clientCmd.m_updateFlags & INIT_POSE_HAS_BASE_LINEAR_VELOCITY)
{
body->m_rigidBody->setLinearVelocity(baseLinVel);
}
if (clientCmd.m_updateFlags & INIT_POSE_HAS_BASE_ANGULAR_VELOCITY)
{
body->m_rigidBody->setAngularVelocity(baseAngVel);
}
if (clientCmd.m_updateFlags & INIT_POSE_HAS_INITIAL_POSITION)
{
body->m_rigidBody->getWorldTransform().setOrigin(basePos);
body->m_rigidBody->setLinearVelocity(baseLinVel);
}
if (clientCmd.m_updateFlags & INIT_POSE_HAS_INITIAL_ORIENTATION)
{
body->m_rigidBody->getWorldTransform().setRotation(baseOrn);
body->m_rigidBody->setAngularVelocity(baseAngVel);
}
}
syncPhysicsToGraphics2();
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CLIENT_COMMAND_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processResetSimulationCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_RESET_SIMULATION");
m_data->m_guiHelper->setVisualizerFlag(COV_ENABLE_SYNC_RENDERING_INTERNAL, 0);
resetSimulation(clientCmd.m_updateFlags);
m_data->m_guiHelper->setVisualizerFlag(COV_ENABLE_SYNC_RENDERING_INTERNAL, 1);
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_RESET_SIMULATION_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCreateRigidBodyCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_RIGID_BODY_CREATION_COMPLETED;
BT_PROFILE("CMD_CREATE_RIGID_BODY");
btVector3 halfExtents(1, 1, 1);
if (clientCmd.m_updateFlags & BOX_SHAPE_HAS_HALF_EXTENTS)
{
halfExtents = btVector3(
clientCmd.m_createBoxShapeArguments.m_halfExtentsX,
clientCmd.m_createBoxShapeArguments.m_halfExtentsY,
clientCmd.m_createBoxShapeArguments.m_halfExtentsZ);
}
btTransform startTrans;
startTrans.setIdentity();
if (clientCmd.m_updateFlags & BOX_SHAPE_HAS_INITIAL_POSITION)
{
startTrans.setOrigin(btVector3(
clientCmd.m_createBoxShapeArguments.m_initialPosition[0],
clientCmd.m_createBoxShapeArguments.m_initialPosition[1],
clientCmd.m_createBoxShapeArguments.m_initialPosition[2]));
}
if (clientCmd.m_updateFlags & BOX_SHAPE_HAS_INITIAL_ORIENTATION)
{
startTrans.setRotation(btQuaternion(
clientCmd.m_createBoxShapeArguments.m_initialOrientation[0],
clientCmd.m_createBoxShapeArguments.m_initialOrientation[1],
clientCmd.m_createBoxShapeArguments.m_initialOrientation[2],
clientCmd.m_createBoxShapeArguments.m_initialOrientation[3]));
}
btScalar mass = 0.f;
if (clientCmd.m_updateFlags & BOX_SHAPE_HAS_MASS)
{
mass = clientCmd.m_createBoxShapeArguments.m_mass;
}
int shapeType = COLLISION_SHAPE_TYPE_BOX;
if (clientCmd.m_updateFlags & BOX_SHAPE_HAS_COLLISION_SHAPE_TYPE)
{
shapeType = clientCmd.m_createBoxShapeArguments.m_collisionShapeType;
}
btMultiBodyWorldImporter* worldImporter = new btMultiBodyWorldImporter(m_data->m_dynamicsWorld);
m_data->m_worldImporters.push_back(worldImporter);
btCollisionShape* shape = 0;
switch (shapeType)
{
case COLLISION_SHAPE_TYPE_CYLINDER_X:
{
btScalar radius = halfExtents[1];
btScalar height = halfExtents[0];
shape = worldImporter->createCylinderShapeX(radius, height);
break;
}
case COLLISION_SHAPE_TYPE_CYLINDER_Y:
{
btScalar radius = halfExtents[0];
btScalar height = halfExtents[1];
shape = worldImporter->createCylinderShapeY(radius, height);
break;
}
case COLLISION_SHAPE_TYPE_CYLINDER_Z:
{
btScalar radius = halfExtents[1];
btScalar height = halfExtents[2];
shape = worldImporter->createCylinderShapeZ(radius, height);
break;
}
case COLLISION_SHAPE_TYPE_CAPSULE_X:
{
btScalar radius = halfExtents[1];
btScalar height = halfExtents[0];
shape = worldImporter->createCapsuleShapeX(radius, height);
break;
}
case COLLISION_SHAPE_TYPE_CAPSULE_Y:
{
btScalar radius = halfExtents[0];
btScalar height = halfExtents[1];
shape = worldImporter->createCapsuleShapeY(radius, height);
break;
}
case COLLISION_SHAPE_TYPE_CAPSULE_Z:
{
btScalar radius = halfExtents[1];
btScalar height = halfExtents[2];
shape = worldImporter->createCapsuleShapeZ(radius, height);
break;
}
case COLLISION_SHAPE_TYPE_SPHERE:
{
btScalar radius = halfExtents[0];
shape = worldImporter->createSphereShape(radius);
break;
}
case COLLISION_SHAPE_TYPE_BOX:
default:
{
shape = worldImporter->createBoxShape(halfExtents);
}
}
bool isDynamic = (mass > 0);
btRigidBody* rb = worldImporter->createRigidBody(isDynamic, mass, startTrans, shape, 0);
//m_data->m_guiHelper->autogenerateGraphicsObjects(this->m_data->m_dynamicsWorld);
btVector4 colorRGBA(1, 0, 0, 1);
if (clientCmd.m_updateFlags & BOX_SHAPE_HAS_COLOR)
{
colorRGBA[0] = clientCmd.m_createBoxShapeArguments.m_colorRGBA[0];
colorRGBA[1] = clientCmd.m_createBoxShapeArguments.m_colorRGBA[1];
colorRGBA[2] = clientCmd.m_createBoxShapeArguments.m_colorRGBA[2];
colorRGBA[3] = clientCmd.m_createBoxShapeArguments.m_colorRGBA[3];
}
m_data->m_guiHelper->createCollisionShapeGraphicsObject(rb->getCollisionShape());
m_data->m_guiHelper->createCollisionObjectGraphicsObject(rb, colorRGBA);
int bodyUniqueId = m_data->m_bodyHandles.allocHandle();
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(bodyUniqueId);
serverCmd.m_rigidBodyCreateArgs.m_bodyUniqueId = bodyUniqueId;
rb->setUserIndex2(bodyUniqueId);
bodyHandle->m_rootLocalInertialFrame.setIdentity();
bodyHandle->m_rigidBody = rb;
b3Notification notification;
notification.m_notificationType = BODY_ADDED;
notification.m_bodyArgs.m_bodyUniqueId = bodyUniqueId;
m_data->m_pluginManager.addNotification(notification);
return hasStatus;
}
bool PhysicsServerCommandProcessor::processPickBodyCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_PICK_BODY");
pickBody(btVector3(clientCmd.m_pickBodyArguments.m_rayFromWorld[0],
clientCmd.m_pickBodyArguments.m_rayFromWorld[1],
clientCmd.m_pickBodyArguments.m_rayFromWorld[2]),
btVector3(clientCmd.m_pickBodyArguments.m_rayToWorld[0],
clientCmd.m_pickBodyArguments.m_rayToWorld[1],
clientCmd.m_pickBodyArguments.m_rayToWorld[2]));
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CLIENT_COMMAND_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processMovePickedBodyCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_MOVE_PICKED_BODY");
movePickedBody(btVector3(clientCmd.m_pickBodyArguments.m_rayFromWorld[0],
clientCmd.m_pickBodyArguments.m_rayFromWorld[1],
clientCmd.m_pickBodyArguments.m_rayFromWorld[2]),
btVector3(clientCmd.m_pickBodyArguments.m_rayToWorld[0],
clientCmd.m_pickBodyArguments.m_rayToWorld[1],
clientCmd.m_pickBodyArguments.m_rayToWorld[2]));
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CLIENT_COMMAND_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRemovePickingConstraintCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REMOVE_PICKING_CONSTRAINT_BODY");
removePickingConstraint();
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CLIENT_COMMAND_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestAabbOverlapCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_AABB_OVERLAP");
SharedMemoryStatus& serverCmd = serverStatusOut;
int curObjectIndex = clientCmd.m_requestOverlappingObjectsArgs.m_startingOverlappingObjectIndex;
if (0 == curObjectIndex)
{
//clientCmd.m_requestContactPointArguments.m_aabbQueryMin
btVector3 aabbMin, aabbMax;
aabbMin.setValue(clientCmd.m_requestOverlappingObjectsArgs.m_aabbQueryMin[0],
clientCmd.m_requestOverlappingObjectsArgs.m_aabbQueryMin[1],
clientCmd.m_requestOverlappingObjectsArgs.m_aabbQueryMin[2]);
aabbMax.setValue(clientCmd.m_requestOverlappingObjectsArgs.m_aabbQueryMax[0],
clientCmd.m_requestOverlappingObjectsArgs.m_aabbQueryMax[1],
clientCmd.m_requestOverlappingObjectsArgs.m_aabbQueryMax[2]);
m_data->m_cachedOverlappingObjects.clear();
m_data->m_dynamicsWorld->getBroadphase()->aabbTest(aabbMin, aabbMax, m_data->m_cachedOverlappingObjects);
}
int totalBytesPerObject = sizeof(b3OverlappingObject);
int overlapCapacity = bufferSizeInBytes / totalBytesPerObject - 1;
int numOverlap = m_data->m_cachedOverlappingObjects.m_bodyUniqueIds.size();
int remainingObjects = numOverlap - curObjectIndex;
int curNumObjects = btMin(overlapCapacity, remainingObjects);
if (numOverlap < overlapCapacity)
{
b3OverlappingObject* overlapStorage = (b3OverlappingObject*)bufferServerToClient;
for (int i = 0; i < m_data->m_cachedOverlappingObjects.m_bodyUniqueIds.size(); i++)
{
overlapStorage[i].m_objectUniqueId = m_data->m_cachedOverlappingObjects.m_bodyUniqueIds[i];
overlapStorage[i].m_linkIndex = m_data->m_cachedOverlappingObjects.m_links[i];
}
serverCmd.m_type = CMD_REQUEST_AABB_OVERLAP_COMPLETED;
//int m_startingOverlappingObjectIndex;
//int m_numOverlappingObjectsCopied;
//int m_numRemainingOverlappingObjects;
serverCmd.m_sendOverlappingObjectsArgs.m_startingOverlappingObjectIndex = clientCmd.m_requestOverlappingObjectsArgs.m_startingOverlappingObjectIndex;
serverCmd.m_sendOverlappingObjectsArgs.m_numOverlappingObjectsCopied = m_data->m_cachedOverlappingObjects.m_bodyUniqueIds.size();
serverCmd.m_sendOverlappingObjectsArgs.m_numRemainingOverlappingObjects = remainingObjects - curNumObjects;
}
else
{
serverCmd.m_type = CMD_REQUEST_AABB_OVERLAP_FAILED;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestOpenGLVisualizeCameraCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_OPENGL_VISUALIZER_CAMERA");
SharedMemoryStatus& serverCmd = serverStatusOut;
bool result = this->m_data->m_guiHelper->getCameraInfo(
&serverCmd.m_visualizerCameraResultArgs.m_width,
&serverCmd.m_visualizerCameraResultArgs.m_height,
serverCmd.m_visualizerCameraResultArgs.m_viewMatrix,
serverCmd.m_visualizerCameraResultArgs.m_projectionMatrix,
serverCmd.m_visualizerCameraResultArgs.m_camUp,
serverCmd.m_visualizerCameraResultArgs.m_camForward,
serverCmd.m_visualizerCameraResultArgs.m_horizontal,
serverCmd.m_visualizerCameraResultArgs.m_vertical,
&serverCmd.m_visualizerCameraResultArgs.m_yaw,
&serverCmd.m_visualizerCameraResultArgs.m_pitch,
&serverCmd.m_visualizerCameraResultArgs.m_dist,
serverCmd.m_visualizerCameraResultArgs.m_target);
serverCmd.m_type = result ? CMD_REQUEST_OPENGL_VISUALIZER_CAMERA_COMPLETED : CMD_REQUEST_OPENGL_VISUALIZER_CAMERA_FAILED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processConfigureOpenGLVisualizerCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_CONFIGURE_OPENGL_VISUALIZER");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CLIENT_COMMAND_COMPLETED;
hasStatus = true;
if (clientCmd.m_updateFlags & COV_SET_FLAGS)
{
if (clientCmd.m_configureOpenGLVisualizerArguments.m_setFlag == COV_ENABLE_TINY_RENDERER)
{
m_data->m_enableTinyRenderer = clientCmd.m_configureOpenGLVisualizerArguments.m_setEnabled != 0;
}
m_data->m_guiHelper->setVisualizerFlag(clientCmd.m_configureOpenGLVisualizerArguments.m_setFlag,
clientCmd.m_configureOpenGLVisualizerArguments.m_setEnabled);
}
if (clientCmd.m_updateFlags & COV_SET_CAMERA_VIEW_MATRIX)
{
m_data->m_guiHelper->resetCamera(clientCmd.m_configureOpenGLVisualizerArguments.m_cameraDistance,
clientCmd.m_configureOpenGLVisualizerArguments.m_cameraYaw,
clientCmd.m_configureOpenGLVisualizerArguments.m_cameraPitch,
clientCmd.m_configureOpenGLVisualizerArguments.m_cameraTargetPosition[0],
clientCmd.m_configureOpenGLVisualizerArguments.m_cameraTargetPosition[1],
clientCmd.m_configureOpenGLVisualizerArguments.m_cameraTargetPosition[2]);
}
if (m_data->m_guiHelper->getRenderInterface())
{
if (clientCmd.m_updateFlags & COV_SET_LIGHT_POSITION)
{
m_data->m_guiHelper->getRenderInterface()->setLightPosition(clientCmd.m_configureOpenGLVisualizerArguments.m_lightPosition);
}
if (clientCmd.m_updateFlags & COV_SET_SHADOWMAP_RESOLUTION)
{
m_data->m_guiHelper->getRenderInterface()->setShadowMapResolution(clientCmd.m_configureOpenGLVisualizerArguments.m_shadowMapResolution);
}
if (clientCmd.m_updateFlags & COV_SET_SHADOWMAP_WORLD_SIZE)
{
float worldSize = clientCmd.m_configureOpenGLVisualizerArguments.m_shadowMapWorldSize;
m_data->m_guiHelper->getRenderInterface()->setShadowMapWorldSize(worldSize);
}
}
if (clientCmd.m_updateFlags & COV_SET_REMOTE_SYNC_TRANSFORM_INTERVAL)
{
m_data->m_remoteSyncTransformInterval = clientCmd.m_configureOpenGLVisualizerArguments.m_remoteSyncTransformInterval;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processInverseDynamicsCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_CALCULATE_INVERSE_DYNAMICS");
SharedMemoryStatus& serverCmd = serverStatusOut;
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(clientCmd.m_calculateInverseDynamicsArguments.m_bodyUniqueId);
serverCmd.m_type = CMD_CALCULATED_INVERSE_DYNAMICS_FAILED;
if (bodyHandle && bodyHandle->m_multiBody)
{
if (clientCmd.m_calculateInverseDynamicsArguments.m_flags & 1)
{
#ifdef STATIC_LINK_SPD_PLUGIN
{
cRBDModel* rbdModel = m_data->findOrCreateRBDModel(bodyHandle->m_multiBody,
clientCmd.m_calculateInverseDynamicsArguments.m_jointPositionsQ,
clientCmd.m_calculateInverseDynamicsArguments.m_jointVelocitiesQdot);
if (rbdModel)
{
int posVal = bodyHandle->m_multiBody->getNumPosVars();
Eigen::VectorXd acc2 = Eigen::VectorXd::Zero(7 + posVal);
Eigen::VectorXd out_tau = Eigen::VectorXd::Zero(7 + posVal);
cRBDUtil::SolveInvDyna(*rbdModel, acc2, out_tau);
int dof = 7 + bodyHandle->m_multiBody->getNumPosVars();
for (int i = 0; i < dof; i++)
{
serverCmd.m_inverseDynamicsResultArgs.m_jointForces[i] = out_tau[i];
}
serverCmd.m_inverseDynamicsResultArgs.m_bodyUniqueId = clientCmd.m_calculateInverseDynamicsArguments.m_bodyUniqueId;
serverCmd.m_inverseDynamicsResultArgs.m_dofCount = dof;
serverCmd.m_type = CMD_CALCULATED_INVERSE_DYNAMICS_COMPLETED;
}
}
#endif
}
else
{
btInverseDynamics::MultiBodyTree* tree = m_data->findOrCreateTree(bodyHandle->m_multiBody);
int baseDofQ = bodyHandle->m_multiBody->hasFixedBase() ? 0 : 7;
int baseDofQdot = bodyHandle->m_multiBody->hasFixedBase() ? 0 : 6;
const int num_dofs = bodyHandle->m_multiBody->getNumDofs();
if (tree && clientCmd.m_calculateInverseDynamicsArguments.m_dofCountQ == (baseDofQ + num_dofs) &&
clientCmd.m_calculateInverseDynamicsArguments.m_dofCountQdot == (baseDofQdot + num_dofs))
{
btInverseDynamics::vecx nu(num_dofs + baseDofQdot), qdot(num_dofs + baseDofQdot), q(num_dofs + baseDofQdot), joint_force(num_dofs + baseDofQdot);
//for floating base, inverse dynamics expects euler angle x,y,z and position x,y,z in that order
//PyBullet expects quaternion, so convert and swap to have a more consistent PyBullet API
if (baseDofQ)
{
btVector3 pos(clientCmd.m_calculateInverseDynamicsArguments.m_jointPositionsQ[0],
clientCmd.m_calculateInverseDynamicsArguments.m_jointPositionsQ[1],
clientCmd.m_calculateInverseDynamicsArguments.m_jointPositionsQ[2]);
btQuaternion orn(clientCmd.m_calculateInverseDynamicsArguments.m_jointPositionsQ[0],
clientCmd.m_calculateInverseDynamicsArguments.m_jointPositionsQ[1],
clientCmd.m_calculateInverseDynamicsArguments.m_jointPositionsQ[2],
clientCmd.m_calculateInverseDynamicsArguments.m_jointPositionsQ[3]);
btScalar yawZ, pitchY, rollX;
orn.getEulerZYX(yawZ, pitchY, rollX);
q[0] = rollX;
q[1] = pitchY;
q[2] = yawZ;
q[3] = pos[0];
q[4] = pos[1];
q[5] = pos[2];
}
else
{
for (int i = 0; i < num_dofs; i++)
{
q[i] = clientCmd.m_calculateInverseDynamicsArguments.m_jointPositionsQ[i];
}
}
for (int i = 0; i < num_dofs + baseDofQdot; i++)
{
qdot[i] = clientCmd.m_calculateInverseDynamicsArguments.m_jointVelocitiesQdot[i];
nu[i] = clientCmd.m_calculateInverseDynamicsArguments.m_jointAccelerations[i];
}
// Set the gravity to correspond to the world gravity
btInverseDynamics::vec3 id_grav(m_data->m_dynamicsWorld->getGravity());
if (-1 != tree->setGravityInWorldFrame(id_grav) &&
-1 != tree->calculateInverseDynamics(q, qdot, nu, &joint_force))
{
serverCmd.m_inverseDynamicsResultArgs.m_bodyUniqueId = clientCmd.m_calculateInverseDynamicsArguments.m_bodyUniqueId;
serverCmd.m_inverseDynamicsResultArgs.m_dofCount = num_dofs + baseDofQdot;
//inverse dynamics stores angular before linear, swap it to have a consistent PyBullet API.
if (baseDofQdot)
{
serverCmd.m_inverseDynamicsResultArgs.m_jointForces[0] = joint_force[3];
serverCmd.m_inverseDynamicsResultArgs.m_jointForces[1] = joint_force[4];
serverCmd.m_inverseDynamicsResultArgs.m_jointForces[2] = joint_force[5];
serverCmd.m_inverseDynamicsResultArgs.m_jointForces[3] = joint_force[0];
serverCmd.m_inverseDynamicsResultArgs.m_jointForces[4] = joint_force[1];
serverCmd.m_inverseDynamicsResultArgs.m_jointForces[5] = joint_force[2];
}
for (int i = baseDofQdot; i < num_dofs + baseDofQdot; i++)
{
serverCmd.m_inverseDynamicsResultArgs.m_jointForces[i] = joint_force[i];
}
serverCmd.m_type = CMD_CALCULATED_INVERSE_DYNAMICS_COMPLETED;
}
else
{
serverCmd.m_type = CMD_CALCULATED_INVERSE_DYNAMICS_FAILED;
}
}
}
}
else
{
serverCmd.m_type = CMD_CALCULATED_INVERSE_DYNAMICS_FAILED;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCalculateJacobianCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_CALCULATE_JACOBIAN");
SharedMemoryStatus& serverCmd = serverStatusOut;
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(clientCmd.m_calculateJacobianArguments.m_bodyUniqueId);
if (bodyHandle && bodyHandle->m_multiBody)
{
serverCmd.m_type = CMD_CALCULATED_JACOBIAN_FAILED;
btInverseDynamics::MultiBodyTree* tree = m_data->findOrCreateTree(bodyHandle->m_multiBody);
if (tree)
{
int baseDofs = bodyHandle->m_multiBody->hasFixedBase() ? 0 : 6;
const int numDofs = bodyHandle->m_multiBody->getNumDofs();
btInverseDynamics::vecx q(numDofs + baseDofs);
btInverseDynamics::vecx qdot(numDofs + baseDofs);
btInverseDynamics::vecx nu(numDofs + baseDofs);
btInverseDynamics::vecx joint_force(numDofs + baseDofs);
for (int i = 0; i < numDofs; i++)
{
q[i + baseDofs] = clientCmd.m_calculateJacobianArguments.m_jointPositionsQ[i];
qdot[i + baseDofs] = clientCmd.m_calculateJacobianArguments.m_jointVelocitiesQdot[i];
nu[i + baseDofs] = clientCmd.m_calculateJacobianArguments.m_jointAccelerations[i];
}
// Set the gravity to correspond to the world gravity
btInverseDynamics::vec3 id_grav(m_data->m_dynamicsWorld->getGravity());
if (-1 != tree->setGravityInWorldFrame(id_grav) &&
-1 != tree->calculateInverseDynamics(q, qdot, nu, &joint_force))
{
serverCmd.m_jacobianResultArgs.m_dofCount = numDofs + baseDofs;
// Set jacobian value
tree->calculateJacobians(q);
btInverseDynamics::mat3x jac_t(3, numDofs + baseDofs);
btInverseDynamics::mat3x jac_r(3, numDofs + baseDofs);
// Note that inverse dynamics uses zero-based indexing of bodies, not starting from -1 for the base link.
tree->getBodyJacobianTrans(clientCmd.m_calculateJacobianArguments.m_linkIndex + 1, &jac_t);
tree->getBodyJacobianRot(clientCmd.m_calculateJacobianArguments.m_linkIndex + 1, &jac_r);
// Update the translational jacobian based on the desired local point.
// v_pt = v_frame + w x pt
// v_pt = J_t * qd + (J_r * qd) x pt
// v_pt = J_t * qd - pt x (J_r * qd)
// v_pt = J_t * qd - pt_x * J_r * qd)
// v_pt = (J_t - pt_x * J_r) * qd
// J_t_new = J_t - pt_x * J_r
btInverseDynamics::vec3 localPosition;
for (int i = 0; i < 3; ++i)
{
localPosition(i) = clientCmd.m_calculateJacobianArguments.m_localPosition[i];
}
// Only calculate if the localPosition is non-zero.
if (btInverseDynamics::maxAbs(localPosition) > 0.0)
{
// Write the localPosition into world coordinates.
btInverseDynamics::mat33 world_rotation_body;
tree->getBodyTransform(clientCmd.m_calculateJacobianArguments.m_linkIndex + 1, &world_rotation_body);
localPosition = world_rotation_body * localPosition;
// Correct the translational jacobian.
btInverseDynamics::mat33 skewCrossProduct;
btInverseDynamics::skew(localPosition, &skewCrossProduct);
btInverseDynamics::mat3x jac_l(3, numDofs + baseDofs);
btInverseDynamics::mul(skewCrossProduct, jac_r, &jac_l);
btInverseDynamics::mat3x jac_t_new(3, numDofs + baseDofs);
btInverseDynamics::sub(jac_t, jac_l, &jac_t_new);
jac_t = jac_t_new;
}
// Fill in the result into the shared memory.
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < (numDofs + baseDofs); ++j)
{
int element = (numDofs + baseDofs) * i + j;
serverCmd.m_jacobianResultArgs.m_linearJacobian[element] = jac_t(i, j);
serverCmd.m_jacobianResultArgs.m_angularJacobian[element] = jac_r(i, j);
}
}
serverCmd.m_type = CMD_CALCULATED_JACOBIAN_COMPLETED;
}
else
{
serverCmd.m_type = CMD_CALCULATED_JACOBIAN_FAILED;
}
}
}
else
{
serverCmd.m_type = CMD_CALCULATED_JACOBIAN_FAILED;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCalculateMassMatrixCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_CALCULATE_MASS_MATRIX");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CALCULATED_MASS_MATRIX_FAILED;
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(clientCmd.m_calculateMassMatrixArguments.m_bodyUniqueId);
if (bodyHandle && bodyHandle->m_multiBody)
{
if (clientCmd.m_calculateMassMatrixArguments.m_flags & 1)
{
#ifdef STATIC_LINK_SPD_PLUGIN
{
int posVal = bodyHandle->m_multiBody->getNumPosVars();
btAlignedObjectArray<double> zeroVel;
int dof = 7 + posVal;
zeroVel.resize(dof);
cRBDModel* rbdModel = m_data->findOrCreateRBDModel(bodyHandle->m_multiBody, clientCmd.m_calculateMassMatrixArguments.m_jointPositionsQ,
&zeroVel[0]);
if (rbdModel)
{
//Eigen::MatrixXd out_mass;
//cRBDUtil::BuildMassMat(*rbdModel, out_mass);
const Eigen::MatrixXd& out_mass = rbdModel->GetMassMat();
int skipDofs = 0; // 7 - baseDofQ;
int totDofs = dof;
serverCmd.m_massMatrixResultArgs.m_dofCount = totDofs - skipDofs;
// Fill in the result into the shared memory.
double* sharedBuf = (double*)bufferServerToClient;
int sizeInBytes = totDofs * totDofs * sizeof(double);
if (sizeInBytes < bufferSizeInBytes)
{
for (int i = skipDofs; i < (totDofs); ++i)
{
for (int j = skipDofs; j < (totDofs); ++j)
{
int element = (totDofs - skipDofs) * (i - skipDofs) + (j - skipDofs);
double v = out_mass(i, j);
if (i == j && v == 0)
{
v = 1;
}
sharedBuf[element] = v;
}
}
serverCmd.m_type = CMD_CALCULATED_MASS_MATRIX_COMPLETED;
}
}
}
#endif
}
else
{
btInverseDynamics::MultiBodyTree* tree = m_data->findOrCreateTree(bodyHandle->m_multiBody);
if (tree)
{
int baseDofs = bodyHandle->m_multiBody->hasFixedBase() ? 0 : 6;
const int numDofs = bodyHandle->m_multiBody->getNumDofs();
const int totDofs = numDofs + baseDofs;
btInverseDynamics::vecx q(totDofs);
btInverseDynamics::matxx massMatrix(totDofs, totDofs);
for (int i = 0; i < numDofs; i++)
{
q[i + baseDofs] = clientCmd.m_calculateMassMatrixArguments.m_jointPositionsQ[i];
}
if (-1 != tree->calculateMassMatrix(q, &massMatrix))
{
serverCmd.m_massMatrixResultArgs.m_dofCount = totDofs;
// Fill in the result into the shared memory.
double* sharedBuf = (double*)bufferServerToClient;
int sizeInBytes = totDofs * totDofs * sizeof(double);
if (sizeInBytes < bufferSizeInBytes)
{
for (int i = 0; i < (totDofs); ++i)
{
for (int j = 0; j < (totDofs); ++j)
{
int element = (totDofs)*i + j;
sharedBuf[element] = massMatrix(i, j);
}
}
serverCmd.m_type = CMD_CALCULATED_MASS_MATRIX_COMPLETED;
}
}
}
}
}
else
{
serverCmd.m_type = CMD_CALCULATED_MASS_MATRIX_FAILED;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processApplyExternalForceCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_APPLY_EXTERNAL_FORCE");
if (m_data->m_verboseOutput)
{
b3Printf("CMD_APPLY_EXTERNAL_FORCE clientCmd = %d\n", clientCmd.m_sequenceNumber);
}
for (int i = 0; i < clientCmd.m_externalForceArguments.m_numForcesAndTorques; ++i)
{
InternalBodyData* body = m_data->m_bodyHandles.getHandle(clientCmd.m_externalForceArguments.m_bodyUniqueIds[i]);
bool isLinkFrame = ((clientCmd.m_externalForceArguments.m_forceFlags[i] & EF_LINK_FRAME) != 0);
if (body && body->m_multiBody)
{
btMultiBody* mb = body->m_multiBody;
if ((clientCmd.m_externalForceArguments.m_forceFlags[i] & EF_FORCE) != 0)
{
btVector3 tmpForce(clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 0],
clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 1],
clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 2]);
btVector3 tmpPosition(
clientCmd.m_externalForceArguments.m_positions[i * 3 + 0],
clientCmd.m_externalForceArguments.m_positions[i * 3 + 1],
clientCmd.m_externalForceArguments.m_positions[i * 3 + 2]);
if (clientCmd.m_externalForceArguments.m_linkIds[i] == -1)
{
btVector3 forceWorld = isLinkFrame ? mb->getBaseWorldTransform().getBasis() * tmpForce : tmpForce;
btVector3 relPosWorld = isLinkFrame ? mb->getBaseWorldTransform().getBasis() * tmpPosition : tmpPosition - mb->getBaseWorldTransform().getOrigin();
mb->addBaseForce(forceWorld);
mb->addBaseTorque(relPosWorld.cross(forceWorld));
//b3Printf("apply base force of %f,%f,%f at %f,%f,%f\n", forceWorld[0],forceWorld[1],forceWorld[2],positionLocal[0],positionLocal[1],positionLocal[2]);
}
else
{
int link = clientCmd.m_externalForceArguments.m_linkIds[i];
btVector3 forceWorld = isLinkFrame ? mb->getLink(link).m_cachedWorldTransform.getBasis() * tmpForce : tmpForce;
btVector3 relPosWorld = isLinkFrame ? mb->getLink(link).m_cachedWorldTransform.getBasis() * tmpPosition : tmpPosition - mb->getBaseWorldTransform().getOrigin();
mb->addLinkForce(link, forceWorld);
mb->addLinkTorque(link, relPosWorld.cross(forceWorld));
//b3Printf("apply link force of %f,%f,%f at %f,%f,%f\n", forceWorld[0],forceWorld[1],forceWorld[2], positionLocal[0],positionLocal[1],positionLocal[2]);
}
}
if ((clientCmd.m_externalForceArguments.m_forceFlags[i] & EF_TORQUE) != 0)
{
btVector3 torqueLocal(clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 0],
clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 1],
clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 2]);
if (clientCmd.m_externalForceArguments.m_linkIds[i] == -1)
{
btVector3 torqueWorld = isLinkFrame ? torqueLocal : mb->getBaseWorldTransform().getBasis() * torqueLocal;
mb->addBaseTorque(torqueWorld);
//b3Printf("apply base torque of %f,%f,%f\n", torqueWorld[0],torqueWorld[1],torqueWorld[2]);
}
else
{
int link = clientCmd.m_externalForceArguments.m_linkIds[i];
btVector3 torqueWorld = mb->getLink(link).m_cachedWorldTransform.getBasis() * torqueLocal;
mb->addLinkTorque(link, torqueWorld);
//b3Printf("apply link torque of %f,%f,%f\n", torqueWorld[0],torqueWorld[1],torqueWorld[2]);
}
}
}
if (body && body->m_rigidBody)
{
btRigidBody* rb = body->m_rigidBody;
if ((clientCmd.m_externalForceArguments.m_forceFlags[i] & EF_FORCE) != 0)
{
btVector3 forceLocal(clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 0],
clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 1],
clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 2]);
btVector3 positionLocal(
clientCmd.m_externalForceArguments.m_positions[i * 3 + 0],
clientCmd.m_externalForceArguments.m_positions[i * 3 + 1],
clientCmd.m_externalForceArguments.m_positions[i * 3 + 2]);
btVector3 forceWorld = isLinkFrame ? forceLocal : rb->getWorldTransform().getBasis() * forceLocal;
btVector3 relPosWorld = isLinkFrame ? positionLocal : rb->getWorldTransform().getBasis() * positionLocal;
rb->applyForce(forceWorld, relPosWorld);
}
if ((clientCmd.m_externalForceArguments.m_forceFlags[i] & EF_TORQUE) != 0)
{
btVector3 torqueLocal(clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 0],
clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 1],
clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 2]);
btVector3 torqueWorld = isLinkFrame ? torqueLocal : rb->getWorldTransform().getBasis() * torqueLocal;
rb->applyTorque(torqueWorld);
}
}
}
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CLIENT_COMMAND_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRemoveBodyCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_REMOVE_BODY_FAILED;
serverCmd.m_removeObjectArgs.m_numBodies = 0;
serverCmd.m_removeObjectArgs.m_numUserConstraints = 0;
m_data->m_guiHelper->setVisualizerFlag(COV_ENABLE_SYNC_RENDERING_INTERNAL, 0);
for (int i = 0; i < clientCmd.m_removeObjectArgs.m_numBodies; i++)
{
int bodyUniqueId = clientCmd.m_removeObjectArgs.m_bodyUniqueIds[i];
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (bodyHandle)
{
if (bodyHandle->m_multiBody)
{
serverCmd.m_removeObjectArgs.m_bodyUniqueIds[serverCmd.m_removeObjectArgs.m_numBodies++] = bodyUniqueId;
if (m_data->m_pickingMultiBodyPoint2Point && m_data->m_pickingMultiBodyPoint2Point->getMultiBodyA() == bodyHandle->m_multiBody)
{
//memory will be deleted in the code that follows
m_data->m_pickingMultiBodyPoint2Point = 0;
}
//also remove user constraints...
for (int i = m_data->m_dynamicsWorld->getNumMultiBodyConstraints() - 1; i >= 0; i--)
{
btMultiBodyConstraint* mbc = m_data->m_dynamicsWorld->getMultiBodyConstraint(i);
if ((mbc->getMultiBodyA() == bodyHandle->m_multiBody) || (mbc->getMultiBodyB() == bodyHandle->m_multiBody))
{
m_data->m_dynamicsWorld->removeMultiBodyConstraint(mbc);
//also remove user constraint and submit it as removed
for (int c = m_data->m_userConstraints.size() - 1; c >= 0; c--)
{
InteralUserConstraintData* userConstraintPtr = m_data->m_userConstraints.getAtIndex(c);
int userConstraintKey = m_data->m_userConstraints.getKeyAtIndex(c).getUid1();
if (userConstraintPtr->m_mbConstraint == mbc)
{
m_data->m_userConstraints.remove(userConstraintKey);
serverCmd.m_removeObjectArgs.m_userConstraintUniqueIds[serverCmd.m_removeObjectArgs.m_numUserConstraints++] = userConstraintKey;
}
}
delete mbc;
}
}
if (bodyHandle->m_multiBody->getBaseCollider())
{
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->removeVisualShape(bodyHandle->m_multiBody->getBaseCollider()->getUserIndex3());
}
m_data->m_dynamicsWorld->removeCollisionObject(bodyHandle->m_multiBody->getBaseCollider());
int graphicsIndex = bodyHandle->m_multiBody->getBaseCollider()->getUserIndex();
m_data->m_guiHelper->removeGraphicsInstance(graphicsIndex);
delete bodyHandle->m_multiBody->getBaseCollider();
}
for (int link = 0; link < bodyHandle->m_multiBody->getNumLinks(); link++)
{
btCollisionObject* colObj = bodyHandle->m_multiBody->getLink(link).m_collider;
if (colObj)
{
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->removeVisualShape(bodyHandle->m_multiBody->getLink(link).m_collider->getUserIndex3());
}
m_data->m_dynamicsWorld->removeCollisionObject(bodyHandle->m_multiBody->getLink(link).m_collider);
int graphicsIndex = bodyHandle->m_multiBody->getLink(link).m_collider->getUserIndex();
m_data->m_guiHelper->removeGraphicsInstance(graphicsIndex);
delete colObj;
}
}
int numCollisionObjects = m_data->m_dynamicsWorld->getNumCollisionObjects();
m_data->m_dynamicsWorld->removeMultiBody(bodyHandle->m_multiBody);
numCollisionObjects = m_data->m_dynamicsWorld->getNumCollisionObjects();
delete bodyHandle->m_multiBody;
bodyHandle->m_multiBody = 0;
serverCmd.m_type = CMD_REMOVE_BODY_COMPLETED;
}
if (bodyHandle->m_rigidBody)
{
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->removeVisualShape(bodyHandle->m_rigidBody->getUserIndex3());
}
serverCmd.m_removeObjectArgs.m_bodyUniqueIds[serverCmd.m_removeObjectArgs.m_numBodies++] = bodyUniqueId;
if (m_data->m_pickedConstraint && m_data->m_pickedBody == bodyHandle->m_rigidBody)
{
m_data->m_pickedConstraint = 0;
m_data->m_pickedBody = 0;
}
//todo: clear all other remaining data...
m_data->m_dynamicsWorld->removeRigidBody(bodyHandle->m_rigidBody);
int graphicsInstance = bodyHandle->m_rigidBody->getUserIndex2();
m_data->m_guiHelper->removeGraphicsInstance(graphicsInstance);
delete bodyHandle->m_rigidBody;
bodyHandle->m_rigidBody = 0;
serverCmd.m_type = CMD_REMOVE_BODY_COMPLETED;
}
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
if (bodyHandle->m_softBody)
{
btSoftBody* psb = bodyHandle->m_softBody;
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->removeVisualShape(psb->getUserIndex3());
}
serverCmd.m_removeObjectArgs.m_bodyUniqueIds[serverCmd.m_removeObjectArgs.m_numBodies++] = bodyUniqueId;
btSoftMultiBodyDynamicsWorld* softWorld = getSoftWorld();
if (softWorld)
{
softWorld->removeSoftBody(psb);
}
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
deformWorld->removeSoftBody(psb);
}
int graphicsInstance = psb->getUserIndex2();
m_data->m_guiHelper->removeGraphicsInstance(graphicsInstance);
delete psb;
psb = 0;
serverCmd.m_type = CMD_REMOVE_BODY_COMPLETED;
}
#endif
for (int i = 0; i < bodyHandle->m_userDataHandles.size(); i++)
{
int userDataHandle = bodyHandle->m_userDataHandles[i];
SharedMemoryUserData* userData = m_data->m_userDataHandles.getHandle(userDataHandle);
m_data->m_userDataHandleLookup.remove(SharedMemoryUserDataHashKey(userData));
m_data->m_userDataHandles.freeHandle(userDataHandle);
}
m_data->m_bodyHandles.freeHandle(bodyUniqueId);
}
}
for (int i = 0; i < clientCmd.m_removeObjectArgs.m_numUserCollisionShapes; i++)
{
int removeCollisionShapeId = clientCmd.m_removeObjectArgs.m_userCollisionShapes[i];
InternalCollisionShapeHandle* handle = m_data->m_userCollisionShapeHandles.getHandle(removeCollisionShapeId);
if (handle && handle->m_collisionShape)
{
if (handle->m_used)
{
b3Warning("Don't remove collision shape: it is used.");
}
else
{
b3Warning("TODO: dealloc");
int foundIndex = -1;
for (int i = 0; i < m_data->m_worldImporters.size(); i++)
{
btMultiBodyWorldImporter* importer = m_data->m_worldImporters[i];
for (int c = 0; c < importer->getNumCollisionShapes(); c++)
{
if (importer->getCollisionShapeByIndex(c) == handle->m_collisionShape)
{
if ((importer->getNumRigidBodies() == 0) &&
(importer->getNumConstraints() == 0))
{
foundIndex = i;
break;
}
}
}
}
if (foundIndex >= 0)
{
btMultiBodyWorldImporter* importer = m_data->m_worldImporters[foundIndex];
m_data->m_worldImporters.removeAtIndex(foundIndex);
importer->deleteAllData();
delete importer;
m_data->m_userCollisionShapeHandles.freeHandle(removeCollisionShapeId);
serverCmd.m_type = CMD_REMOVE_BODY_COMPLETED;
}
}
}
}
m_data->m_guiHelper->setVisualizerFlag(COV_ENABLE_SYNC_RENDERING_INTERNAL, 1);
for (int i = 0; i < serverCmd.m_removeObjectArgs.m_numBodies; i++)
{
b3Notification notification;
notification.m_notificationType = BODY_REMOVED;
notification.m_bodyArgs.m_bodyUniqueId = serverCmd.m_removeObjectArgs.m_bodyUniqueIds[i];
m_data->m_pluginManager.addNotification(notification);
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCreateUserConstraintCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_USER_CONSTRAINT");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_USER_CONSTRAINT_FAILED;
hasStatus = true;
if (clientCmd.m_updateFlags & USER_CONSTRAINT_ADD_SOFT_BODY_ANCHOR)
{
#ifndef SKIP_DEFORMABLE_BODY
InternalBodyHandle* sbodyHandle = m_data->m_bodyHandles.getHandle(clientCmd.m_userConstraintArguments.m_parentBodyIndex);
if (sbodyHandle)
{
if (sbodyHandle->m_softBody)
{
int nodeIndex = clientCmd.m_userConstraintArguments.m_parentJointIndex;
if (nodeIndex>=0 && nodeIndex < sbodyHandle->m_softBody->m_nodes.size())
{
int bodyUniqueId = clientCmd.m_userConstraintArguments.m_childBodyIndex;
if (bodyUniqueId<=0)
{
//fixed anchor (mass = 0)
sbodyHandle->m_softBody->setMass(nodeIndex,0.0);
int uid = m_data->m_userConstraintUIDGenerator++;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
} else
{
InternalBodyHandle* mbodyHandle = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (mbodyHandle && mbodyHandle->m_multiBody)
{
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
int linkIndex = clientCmd.m_userConstraintArguments.m_childJointIndex;
if (linkIndex<0)
{
sbodyHandle->m_softBody->appendDeformableAnchor(nodeIndex, mbodyHandle->m_multiBody->getBaseCollider());
} else
{
if (linkIndex < mbodyHandle->m_multiBody->getNumLinks())
{
sbodyHandle->m_softBody->appendDeformableAnchor(nodeIndex, mbodyHandle->m_multiBody->getLinkCollider(linkIndex));
}
}
}
}
if (mbodyHandle && mbodyHandle->m_rigidBody)
{
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
//todo: expose those values
bool disableCollisionBetweenLinkedBodies = true;
//btVector3 localPivot(0,0,0);
sbodyHandle->m_softBody->appendDeformableAnchor(nodeIndex, mbodyHandle->m_rigidBody);
}
#if 1
btSoftMultiBodyDynamicsWorld* softWorld = getSoftWorld();
if (softWorld)
{
bool disableCollisionBetweenLinkedBodies = true;
btVector3 localPivot(clientCmd.m_userConstraintArguments.m_childFrame[0],
clientCmd.m_userConstraintArguments.m_childFrame[1],
clientCmd.m_userConstraintArguments.m_childFrame[2]);
sbodyHandle->m_softBody->appendAnchor(nodeIndex, mbodyHandle->m_rigidBody, localPivot, disableCollisionBetweenLinkedBodies);
}
#endif
}
int uid = m_data->m_userConstraintUIDGenerator++;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
}
}
}
}
#endif
}
if (clientCmd.m_updateFlags & USER_CONSTRAINT_REQUEST_STATE)
{
int constraintUid = clientCmd.m_userConstraintArguments.m_userConstraintUniqueId;
InteralUserConstraintData* userConstraintPtr = m_data->m_userConstraints.find(constraintUid);
if (userConstraintPtr)
{
serverCmd.m_userConstraintStateResultArgs.m_numDofs = 0;
for (int i = 0; i < 6; i++)
{
serverCmd.m_userConstraintStateResultArgs.m_appliedConstraintForces[i] = 0;
}
if (userConstraintPtr->m_mbConstraint)
{
serverCmd.m_userConstraintStateResultArgs.m_numDofs = userConstraintPtr->m_mbConstraint->getNumRows();
for (int i = 0; i < userConstraintPtr->m_mbConstraint->getNumRows(); i++)
{
serverCmd.m_userConstraintStateResultArgs.m_appliedConstraintForces[i] = userConstraintPtr->m_mbConstraint->getAppliedImpulse(i) / m_data->m_dynamicsWorld->getSolverInfo().m_timeStep;
}
serverCmd.m_type = CMD_USER_CONSTRAINT_REQUEST_STATE_COMPLETED;
}
}
};
if (clientCmd.m_updateFlags & USER_CONSTRAINT_REQUEST_INFO)
{
int userConstraintUidChange = clientCmd.m_userConstraintArguments.m_userConstraintUniqueId;
InteralUserConstraintData* userConstraintPtr = m_data->m_userConstraints.find(userConstraintUidChange);
if (userConstraintPtr)
{
serverCmd.m_userConstraintResultArgs = userConstraintPtr->m_userConstraintData;
serverCmd.m_type = CMD_USER_CONSTRAINT_INFO_COMPLETED;
}
}
if (clientCmd.m_updateFlags & USER_CONSTRAINT_ADD_CONSTRAINT)
{
btScalar defaultMaxForce = 500.0;
InternalBodyData* parentBody = m_data->m_bodyHandles.getHandle(clientCmd.m_userConstraintArguments.m_parentBodyIndex);
if (parentBody && parentBody->m_multiBody)
{
if ((clientCmd.m_userConstraintArguments.m_parentJointIndex >= -1) && clientCmd.m_userConstraintArguments.m_parentJointIndex < parentBody->m_multiBody->getNumLinks())
{
InternalBodyData* childBody = clientCmd.m_userConstraintArguments.m_childBodyIndex >= 0 ? m_data->m_bodyHandles.getHandle(clientCmd.m_userConstraintArguments.m_childBodyIndex) : 0;
//also create a constraint with just a single multibody/rigid body without child
//if (childBody)
{
btVector3 pivotInParent(clientCmd.m_userConstraintArguments.m_parentFrame[0], clientCmd.m_userConstraintArguments.m_parentFrame[1], clientCmd.m_userConstraintArguments.m_parentFrame[2]);
btVector3 pivotInChild(clientCmd.m_userConstraintArguments.m_childFrame[0], clientCmd.m_userConstraintArguments.m_childFrame[1], clientCmd.m_userConstraintArguments.m_childFrame[2]);
btMatrix3x3 frameInParent(btQuaternion(clientCmd.m_userConstraintArguments.m_parentFrame[3], clientCmd.m_userConstraintArguments.m_parentFrame[4], clientCmd.m_userConstraintArguments.m_parentFrame[5], clientCmd.m_userConstraintArguments.m_parentFrame[6]));
btMatrix3x3 frameInChild(btQuaternion(clientCmd.m_userConstraintArguments.m_childFrame[3], clientCmd.m_userConstraintArguments.m_childFrame[4], clientCmd.m_userConstraintArguments.m_childFrame[5], clientCmd.m_userConstraintArguments.m_childFrame[6]));
btVector3 jointAxis(clientCmd.m_userConstraintArguments.m_jointAxis[0], clientCmd.m_userConstraintArguments.m_jointAxis[1], clientCmd.m_userConstraintArguments.m_jointAxis[2]);
if (clientCmd.m_userConstraintArguments.m_jointType == eGearType)
{
if (childBody && childBody->m_multiBody)
{
if ((clientCmd.m_userConstraintArguments.m_childJointIndex >= -1) && (clientCmd.m_userConstraintArguments.m_childJointIndex < childBody->m_multiBody->getNumLinks()))
{
btMultiBodyGearConstraint* multibodyGear = new btMultiBodyGearConstraint(parentBody->m_multiBody, clientCmd.m_userConstraintArguments.m_parentJointIndex, childBody->m_multiBody, clientCmd.m_userConstraintArguments.m_childJointIndex, pivotInParent, pivotInChild, frameInParent, frameInChild);
multibodyGear->setMaxAppliedImpulse(defaultMaxForce);
m_data->m_dynamicsWorld->addMultiBodyConstraint(multibodyGear);
InteralUserConstraintData userConstraintData;
userConstraintData.m_mbConstraint = multibodyGear;
int uid = m_data->m_userConstraintUIDGenerator++;
serverCmd.m_userConstraintResultArgs = clientCmd.m_userConstraintArguments;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
serverCmd.m_userConstraintResultArgs.m_maxAppliedForce = defaultMaxForce;
userConstraintData.m_userConstraintData = serverCmd.m_userConstraintResultArgs;
m_data->m_userConstraints.insert(uid, userConstraintData);
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
}
}
}
else if (clientCmd.m_userConstraintArguments.m_jointType == eFixedType)
{
if (childBody && childBody->m_multiBody)
{
if ((clientCmd.m_userConstraintArguments.m_childJointIndex >= -1) && (clientCmd.m_userConstraintArguments.m_childJointIndex < childBody->m_multiBody->getNumLinks()))
{
btMultiBodyFixedConstraint* multibodyFixed = new btMultiBodyFixedConstraint(parentBody->m_multiBody, clientCmd.m_userConstraintArguments.m_parentJointIndex, childBody->m_multiBody, clientCmd.m_userConstraintArguments.m_childJointIndex, pivotInParent, pivotInChild, frameInParent, frameInChild);
multibodyFixed->setMaxAppliedImpulse(defaultMaxForce);
m_data->m_dynamicsWorld->addMultiBodyConstraint(multibodyFixed);
InteralUserConstraintData userConstraintData;
userConstraintData.m_mbConstraint = multibodyFixed;
int uid = m_data->m_userConstraintUIDGenerator++;
serverCmd.m_userConstraintResultArgs = clientCmd.m_userConstraintArguments;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
serverCmd.m_userConstraintResultArgs.m_maxAppliedForce = defaultMaxForce;
userConstraintData.m_userConstraintData = serverCmd.m_userConstraintResultArgs;
m_data->m_userConstraints.insert(uid, userConstraintData);
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
}
}
else
{
btRigidBody* rb = childBody ? childBody->m_rigidBody : 0;
btMultiBodyFixedConstraint* rigidbodyFixed = new btMultiBodyFixedConstraint(parentBody->m_multiBody, clientCmd.m_userConstraintArguments.m_parentJointIndex, rb, pivotInParent, pivotInChild, frameInParent, frameInChild);
rigidbodyFixed->setMaxAppliedImpulse(defaultMaxForce);
btMultiBodyDynamicsWorld* world = (btMultiBodyDynamicsWorld*)m_data->m_dynamicsWorld;
world->addMultiBodyConstraint(rigidbodyFixed);
InteralUserConstraintData userConstraintData;
userConstraintData.m_mbConstraint = rigidbodyFixed;
int uid = m_data->m_userConstraintUIDGenerator++;
serverCmd.m_userConstraintResultArgs = clientCmd.m_userConstraintArguments;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
serverCmd.m_userConstraintResultArgs.m_maxAppliedForce = defaultMaxForce;
userConstraintData.m_userConstraintData = serverCmd.m_userConstraintResultArgs;
m_data->m_userConstraints.insert(uid, userConstraintData);
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
}
}
else if (clientCmd.m_userConstraintArguments.m_jointType == ePrismaticType)
{
if (childBody && childBody->m_multiBody)
{
btMultiBodySliderConstraint* multibodySlider = new btMultiBodySliderConstraint(parentBody->m_multiBody, clientCmd.m_userConstraintArguments.m_parentJointIndex, childBody->m_multiBody, clientCmd.m_userConstraintArguments.m_childJointIndex, pivotInParent, pivotInChild, frameInParent, frameInChild, jointAxis);
multibodySlider->setMaxAppliedImpulse(defaultMaxForce);
m_data->m_dynamicsWorld->addMultiBodyConstraint(multibodySlider);
InteralUserConstraintData userConstraintData;
userConstraintData.m_mbConstraint = multibodySlider;
int uid = m_data->m_userConstraintUIDGenerator++;
serverCmd.m_userConstraintResultArgs = clientCmd.m_userConstraintArguments;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
serverCmd.m_userConstraintResultArgs.m_maxAppliedForce = defaultMaxForce;
userConstraintData.m_userConstraintData = serverCmd.m_userConstraintResultArgs;
m_data->m_userConstraints.insert(uid, userConstraintData);
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
}
else
{
btRigidBody* rb = childBody ? childBody->m_rigidBody : 0;
btMultiBodySliderConstraint* rigidbodySlider = new btMultiBodySliderConstraint(parentBody->m_multiBody, clientCmd.m_userConstraintArguments.m_parentJointIndex, rb, pivotInParent, pivotInChild, frameInParent, frameInChild, jointAxis);
rigidbodySlider->setMaxAppliedImpulse(defaultMaxForce);
btMultiBodyDynamicsWorld* world = (btMultiBodyDynamicsWorld*)m_data->m_dynamicsWorld;
world->addMultiBodyConstraint(rigidbodySlider);
InteralUserConstraintData userConstraintData;
userConstraintData.m_mbConstraint = rigidbodySlider;
int uid = m_data->m_userConstraintUIDGenerator++;
serverCmd.m_userConstraintResultArgs = clientCmd.m_userConstraintArguments;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
serverCmd.m_userConstraintResultArgs.m_maxAppliedForce = defaultMaxForce;
userConstraintData.m_userConstraintData = serverCmd.m_userConstraintResultArgs;
m_data->m_userConstraints.insert(uid, userConstraintData);
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
}
}
else if (clientCmd.m_userConstraintArguments.m_jointType == ePoint2PointType)
{
if (childBody && childBody->m_multiBody)
{
btMultiBodyPoint2Point* p2p = new btMultiBodyPoint2Point(parentBody->m_multiBody, clientCmd.m_userConstraintArguments.m_parentJointIndex, childBody->m_multiBody, clientCmd.m_userConstraintArguments.m_childJointIndex, pivotInParent, pivotInChild);
p2p->setMaxAppliedImpulse(defaultMaxForce);
m_data->m_dynamicsWorld->addMultiBodyConstraint(p2p);
InteralUserConstraintData userConstraintData;
userConstraintData.m_mbConstraint = p2p;
int uid = m_data->m_userConstraintUIDGenerator++;
serverCmd.m_userConstraintResultArgs = clientCmd.m_userConstraintArguments;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
serverCmd.m_userConstraintResultArgs.m_maxAppliedForce = defaultMaxForce;
userConstraintData.m_userConstraintData = serverCmd.m_userConstraintResultArgs;
m_data->m_userConstraints.insert(uid, userConstraintData);
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
}
else
{
btRigidBody* rb = childBody ? childBody->m_rigidBody : 0;
btMultiBodyPoint2Point* p2p = new btMultiBodyPoint2Point(parentBody->m_multiBody, clientCmd.m_userConstraintArguments.m_parentJointIndex, rb, pivotInParent, pivotInChild);
p2p->setMaxAppliedImpulse(defaultMaxForce);
btMultiBodyDynamicsWorld* world = (btMultiBodyDynamicsWorld*)m_data->m_dynamicsWorld;
world->addMultiBodyConstraint(p2p);
InteralUserConstraintData userConstraintData;
userConstraintData.m_mbConstraint = p2p;
int uid = m_data->m_userConstraintUIDGenerator++;
serverCmd.m_userConstraintResultArgs = clientCmd.m_userConstraintArguments;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
serverCmd.m_userConstraintResultArgs.m_maxAppliedForce = defaultMaxForce;
userConstraintData.m_userConstraintData = serverCmd.m_userConstraintResultArgs;
m_data->m_userConstraints.insert(uid, userConstraintData);
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
}
}
else
{
b3Warning("unknown constraint type");
}
}
}
}
else
{
InternalBodyData* childBody = clientCmd.m_userConstraintArguments.m_childBodyIndex >= 0 ? m_data->m_bodyHandles.getHandle(clientCmd.m_userConstraintArguments.m_childBodyIndex) : 0;
if (parentBody && childBody)
{
if (parentBody->m_rigidBody)
{
btRigidBody* parentRb = 0;
if (clientCmd.m_userConstraintArguments.m_parentJointIndex == -1)
{
parentRb = parentBody->m_rigidBody;
}
else
{
if ((clientCmd.m_userConstraintArguments.m_parentJointIndex >= 0) &&
(clientCmd.m_userConstraintArguments.m_parentJointIndex < parentBody->m_rigidBodyJoints.size()))
{
parentRb = &parentBody->m_rigidBodyJoints[clientCmd.m_userConstraintArguments.m_parentJointIndex]->getRigidBodyB();
}
}
btRigidBody* childRb = 0;
if (childBody->m_rigidBody)
{
if (clientCmd.m_userConstraintArguments.m_childJointIndex == -1)
{
childRb = childBody->m_rigidBody;
}
else
{
if ((clientCmd.m_userConstraintArguments.m_childJointIndex >= 0) && (clientCmd.m_userConstraintArguments.m_childJointIndex < childBody->m_rigidBodyJoints.size()))
{
childRb = &childBody->m_rigidBodyJoints[clientCmd.m_userConstraintArguments.m_childJointIndex]->getRigidBodyB();
}
}
}
switch (clientCmd.m_userConstraintArguments.m_jointType)
{
case eRevoluteType:
{
break;
}
case ePrismaticType:
{
break;
}
case eFixedType:
{
if (childRb && parentRb && (childRb != parentRb))
{
btVector3 pivotInParent(clientCmd.m_userConstraintArguments.m_parentFrame[0], clientCmd.m_userConstraintArguments.m_parentFrame[1], clientCmd.m_userConstraintArguments.m_parentFrame[2]);
btVector3 pivotInChild(clientCmd.m_userConstraintArguments.m_childFrame[0], clientCmd.m_userConstraintArguments.m_childFrame[1], clientCmd.m_userConstraintArguments.m_childFrame[2]);
btTransform offsetTrA, offsetTrB;
offsetTrA.setIdentity();
offsetTrA.setOrigin(pivotInParent);
offsetTrB.setIdentity();
offsetTrB.setOrigin(pivotInChild);
btGeneric6DofSpring2Constraint* dof6 = new btGeneric6DofSpring2Constraint(*parentRb, *childRb, offsetTrA, offsetTrB);
dof6->setLinearLowerLimit(btVector3(0, 0, 0));
dof6->setLinearUpperLimit(btVector3(0, 0, 0));
dof6->setAngularLowerLimit(btVector3(0, 0, 0));
dof6->setAngularUpperLimit(btVector3(0, 0, 0));
m_data->m_dynamicsWorld->addConstraint(dof6);
InteralUserConstraintData userConstraintData;
userConstraintData.m_rbConstraint = dof6;
int uid = m_data->m_userConstraintUIDGenerator++;
serverCmd.m_userConstraintResultArgs = clientCmd.m_userConstraintArguments;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
serverCmd.m_userConstraintResultArgs.m_maxAppliedForce = defaultMaxForce;
userConstraintData.m_userConstraintData = serverCmd.m_userConstraintResultArgs;
m_data->m_userConstraints.insert(uid, userConstraintData);
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
}
break;
}
case ePoint2PointType:
{
if (childRb && parentRb && (childRb != parentRb))
{
btVector3 pivotInParent(clientCmd.m_userConstraintArguments.m_parentFrame[0], clientCmd.m_userConstraintArguments.m_parentFrame[1], clientCmd.m_userConstraintArguments.m_parentFrame[2]);
btVector3 pivotInChild(clientCmd.m_userConstraintArguments.m_childFrame[0], clientCmd.m_userConstraintArguments.m_childFrame[1], clientCmd.m_userConstraintArguments.m_childFrame[2]);
btPoint2PointConstraint* p2p = new btPoint2PointConstraint(*parentRb, *childRb, pivotInParent, pivotInChild);
p2p->m_setting.m_impulseClamp = defaultMaxForce;
m_data->m_dynamicsWorld->addConstraint(p2p);
InteralUserConstraintData userConstraintData;
userConstraintData.m_rbConstraint = p2p;
int uid = m_data->m_userConstraintUIDGenerator++;
serverCmd.m_userConstraintResultArgs = clientCmd.m_userConstraintArguments;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
serverCmd.m_userConstraintResultArgs.m_maxAppliedForce = defaultMaxForce;
userConstraintData.m_userConstraintData = serverCmd.m_userConstraintResultArgs;
m_data->m_userConstraints.insert(uid, userConstraintData);
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
}
break;
}
case eGearType:
{
if (childRb && parentRb && (childRb != parentRb))
{
btVector3 axisA(clientCmd.m_userConstraintArguments.m_jointAxis[0],
clientCmd.m_userConstraintArguments.m_jointAxis[1],
clientCmd.m_userConstraintArguments.m_jointAxis[2]);
//for now we use the same local axis for both objects
btVector3 axisB(clientCmd.m_userConstraintArguments.m_jointAxis[0],
clientCmd.m_userConstraintArguments.m_jointAxis[1],
clientCmd.m_userConstraintArguments.m_jointAxis[2]);
btScalar ratio = 1;
btGearConstraint* gear = new btGearConstraint(*parentRb, *childRb, axisA, axisB, ratio);
m_data->m_dynamicsWorld->addConstraint(gear, true);
InteralUserConstraintData userConstraintData;
userConstraintData.m_rbConstraint = gear;
int uid = m_data->m_userConstraintUIDGenerator++;
serverCmd.m_userConstraintResultArgs = clientCmd.m_userConstraintArguments;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
serverCmd.m_userConstraintResultArgs.m_maxAppliedForce = defaultMaxForce;
userConstraintData.m_userConstraintData = serverCmd.m_userConstraintResultArgs;
m_data->m_userConstraints.insert(uid, userConstraintData);
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
}
break;
}
case eSphericalType:
{
b3Warning("constraint type not handled yet");
break;
}
case ePlanarType:
{
b3Warning("constraint type not handled yet");
break;
}
default:
{
b3Warning("unknown constraint type");
}
};
}
}
}
}
if (clientCmd.m_updateFlags & USER_CONSTRAINT_CHANGE_CONSTRAINT)
{
serverCmd.m_type = CMD_CHANGE_USER_CONSTRAINT_FAILED;
int userConstraintUidChange = clientCmd.m_userConstraintArguments.m_userConstraintUniqueId;
InteralUserConstraintData* userConstraintPtr = m_data->m_userConstraints.find(userConstraintUidChange);
if (userConstraintPtr)
{
if (userConstraintPtr->m_mbConstraint)
{
if (clientCmd.m_updateFlags & USER_CONSTRAINT_CHANGE_PIVOT_IN_B)
{
btVector3 pivotInB(clientCmd.m_userConstraintArguments.m_childFrame[0],
clientCmd.m_userConstraintArguments.m_childFrame[1],
clientCmd.m_userConstraintArguments.m_childFrame[2]);
userConstraintPtr->m_userConstraintData.m_childFrame[0] = clientCmd.m_userConstraintArguments.m_childFrame[0];
userConstraintPtr->m_userConstraintData.m_childFrame[1] = clientCmd.m_userConstraintArguments.m_childFrame[1];
userConstraintPtr->m_userConstraintData.m_childFrame[2] = clientCmd.m_userConstraintArguments.m_childFrame[2];
userConstraintPtr->m_mbConstraint->setPivotInB(pivotInB);
}
if (clientCmd.m_updateFlags & USER_CONSTRAINT_CHANGE_FRAME_ORN_IN_B)
{
btQuaternion childFrameOrn(clientCmd.m_userConstraintArguments.m_childFrame[3],
clientCmd.m_userConstraintArguments.m_childFrame[4],
clientCmd.m_userConstraintArguments.m_childFrame[5],
clientCmd.m_userConstraintArguments.m_childFrame[6]);
userConstraintPtr->m_userConstraintData.m_childFrame[3] = clientCmd.m_userConstraintArguments.m_childFrame[3];
userConstraintPtr->m_userConstraintData.m_childFrame[4] = clientCmd.m_userConstraintArguments.m_childFrame[4];
userConstraintPtr->m_userConstraintData.m_childFrame[5] = clientCmd.m_userConstraintArguments.m_childFrame[5];
userConstraintPtr->m_userConstraintData.m_childFrame[6] = clientCmd.m_userConstraintArguments.m_childFrame[6];
btMatrix3x3 childFrameBasis(childFrameOrn);
userConstraintPtr->m_mbConstraint->setFrameInB(childFrameBasis);
}
if (clientCmd.m_updateFlags & USER_CONSTRAINT_CHANGE_MAX_FORCE)
{
btScalar maxImp = clientCmd.m_userConstraintArguments.m_maxAppliedForce * m_data->m_physicsDeltaTime;
userConstraintPtr->m_userConstraintData.m_maxAppliedForce = clientCmd.m_userConstraintArguments.m_maxAppliedForce;
userConstraintPtr->m_mbConstraint->setMaxAppliedImpulse(maxImp);
}
if (clientCmd.m_updateFlags & USER_CONSTRAINT_CHANGE_GEAR_RATIO)
{
userConstraintPtr->m_mbConstraint->setGearRatio(clientCmd.m_userConstraintArguments.m_gearRatio);
userConstraintPtr->m_userConstraintData.m_gearRatio = clientCmd.m_userConstraintArguments.m_gearRatio;
}
if (clientCmd.m_updateFlags & USER_CONSTRAINT_CHANGE_RELATIVE_POSITION_TARGET)
{
userConstraintPtr->m_mbConstraint->setRelativePositionTarget(clientCmd.m_userConstraintArguments.m_relativePositionTarget);
userConstraintPtr->m_userConstraintData.m_relativePositionTarget = clientCmd.m_userConstraintArguments.m_relativePositionTarget;
}
if (clientCmd.m_updateFlags & USER_CONSTRAINT_CHANGE_ERP)
{
userConstraintPtr->m_mbConstraint->setErp(clientCmd.m_userConstraintArguments.m_erp);
userConstraintPtr->m_userConstraintData.m_erp = clientCmd.m_userConstraintArguments.m_erp;
}
if (clientCmd.m_updateFlags & USER_CONSTRAINT_CHANGE_GEAR_AUX_LINK)
{
userConstraintPtr->m_mbConstraint->setGearAuxLink(clientCmd.m_userConstraintArguments.m_gearAuxLink);
userConstraintPtr->m_userConstraintData.m_gearAuxLink = clientCmd.m_userConstraintArguments.m_gearAuxLink;
}
}
if (userConstraintPtr->m_rbConstraint)
{
if (clientCmd.m_updateFlags & USER_CONSTRAINT_CHANGE_MAX_FORCE)
{
btScalar maxImp = clientCmd.m_userConstraintArguments.m_maxAppliedForce * m_data->m_physicsDeltaTime;
userConstraintPtr->m_userConstraintData.m_maxAppliedForce = clientCmd.m_userConstraintArguments.m_maxAppliedForce;
//userConstraintPtr->m_rbConstraint->setMaxAppliedImpulse(maxImp);
}
if (clientCmd.m_updateFlags & USER_CONSTRAINT_CHANGE_GEAR_RATIO)
{
if (userConstraintPtr->m_rbConstraint->getObjectType() == GEAR_CONSTRAINT_TYPE)
{
btGearConstraint* gear = (btGearConstraint*)userConstraintPtr->m_rbConstraint;
gear->setRatio(clientCmd.m_userConstraintArguments.m_gearRatio);
}
}
}
serverCmd.m_userConstraintResultArgs = clientCmd.m_userConstraintArguments;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = userConstraintUidChange;
serverCmd.m_updateFlags = clientCmd.m_updateFlags;
serverCmd.m_type = CMD_CHANGE_USER_CONSTRAINT_COMPLETED;
}
}
if (clientCmd.m_updateFlags & USER_CONSTRAINT_REMOVE_CONSTRAINT)
{
serverCmd.m_type = CMD_REMOVE_USER_CONSTRAINT_FAILED;
int userConstraintUidRemove = clientCmd.m_userConstraintArguments.m_userConstraintUniqueId;
InteralUserConstraintData* userConstraintPtr = m_data->m_userConstraints.find(userConstraintUidRemove);
if (userConstraintPtr)
{
if (userConstraintPtr->m_mbConstraint)
{
m_data->m_dynamicsWorld->removeMultiBodyConstraint(userConstraintPtr->m_mbConstraint);
delete userConstraintPtr->m_mbConstraint;
m_data->m_userConstraints.remove(userConstraintUidRemove);
}
if (userConstraintPtr->m_rbConstraint)
{
m_data->m_dynamicsWorld->removeConstraint(userConstraintPtr->m_rbConstraint);
delete userConstraintPtr->m_rbConstraint;
m_data->m_userConstraints.remove(userConstraintUidRemove);
}
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = userConstraintUidRemove;
serverCmd.m_type = CMD_REMOVE_USER_CONSTRAINT_COMPLETED;
}
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCalculateInverseKinematicsCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_CALCULATE_INVERSE_KINEMATICS");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CALCULATE_INVERSE_KINEMATICS_FAILED;
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(clientCmd.m_calculateInverseKinematicsArguments.m_bodyUniqueId);
if (bodyHandle && bodyHandle->m_multiBody)
{
IKTrajectoryHelper** ikHelperPtrPtr = m_data->m_inverseKinematicsHelpers.find(bodyHandle->m_multiBody);
IKTrajectoryHelper* ikHelperPtr = 0;
if (ikHelperPtrPtr)
{
ikHelperPtr = *ikHelperPtrPtr;
}
else
{
IKTrajectoryHelper* tmpHelper = new IKTrajectoryHelper;
m_data->m_inverseKinematicsHelpers.insert(bodyHandle->m_multiBody, tmpHelper);
ikHelperPtr = tmpHelper;
}
int endEffectorLinkIndex = clientCmd.m_calculateInverseKinematicsArguments.m_endEffectorLinkIndices[0];
btAlignedObjectArray<double> startingPositions;
startingPositions.reserve(bodyHandle->m_multiBody->getNumLinks());
btVector3 targetPosWorld(clientCmd.m_calculateInverseKinematicsArguments.m_targetPositions[0],
clientCmd.m_calculateInverseKinematicsArguments.m_targetPositions[1],
clientCmd.m_calculateInverseKinematicsArguments.m_targetPositions[2]);
btQuaternion targetOrnWorld(clientCmd.m_calculateInverseKinematicsArguments.m_targetOrientation[0],
clientCmd.m_calculateInverseKinematicsArguments.m_targetOrientation[1],
clientCmd.m_calculateInverseKinematicsArguments.m_targetOrientation[2],
clientCmd.m_calculateInverseKinematicsArguments.m_targetOrientation[3]);
btTransform targetBaseCoord;
if (clientCmd.m_updateFlags & IK_HAS_CURRENT_JOINT_POSITIONS)
{
targetBaseCoord.setOrigin(targetPosWorld);
targetBaseCoord.setRotation(targetOrnWorld);
}
else
{
btTransform targetWorld;
targetWorld.setOrigin(targetPosWorld);
targetWorld.setRotation(targetOrnWorld);
btTransform tr = bodyHandle->m_multiBody->getBaseWorldTransform();
targetBaseCoord = tr.inverse() * targetWorld;
}
{
int DofIndex = 0;
for (int i = 0; i < bodyHandle->m_multiBody->getNumLinks(); ++i)
{
if (bodyHandle->m_multiBody->getLink(i).m_jointType >= 0 && bodyHandle->m_multiBody->getLink(i).m_jointType <= 2)
{
// 0, 1, 2 represent revolute, prismatic, and spherical joint types respectively. Skip the fixed joints.
double curPos = 0;
if (clientCmd.m_updateFlags & IK_HAS_CURRENT_JOINT_POSITIONS)
{
curPos = clientCmd.m_calculateInverseKinematicsArguments.m_currentPositions[DofIndex];
}
else
{
curPos = bodyHandle->m_multiBody->getJointPos(i);
}
startingPositions.push_back(curPos);
DofIndex++;
}
}
}
int numIterations = 20;
if (clientCmd.m_updateFlags & IK_HAS_MAX_ITERATIONS)
{
numIterations = clientCmd.m_calculateInverseKinematicsArguments.m_maxNumIterations;
}
double residualThreshold = 1e-4;
if (clientCmd.m_updateFlags & IK_HAS_RESIDUAL_THRESHOLD)
{
residualThreshold = clientCmd.m_calculateInverseKinematicsArguments.m_residualThreshold;
}
btScalar currentDiff = 1e30f;
b3AlignedObjectArray<double> jacobian_linear;
b3AlignedObjectArray<double> jacobian_angular;
btAlignedObjectArray<double> q_current;
btAlignedObjectArray<double> q_new;
btAlignedObjectArray<double> lower_limit;
btAlignedObjectArray<double> upper_limit;
btAlignedObjectArray<double> joint_range;
btAlignedObjectArray<double> rest_pose;
const int numDofs = bodyHandle->m_multiBody->getNumDofs();
int baseDofs = bodyHandle->m_multiBody->hasFixedBase() ? 0 : 6;
btInverseDynamics::vecx nu(numDofs + baseDofs), qdot(numDofs + baseDofs), q(numDofs + baseDofs), joint_force(numDofs + baseDofs);
for (int i = 0; i < numIterations && currentDiff > residualThreshold; i++)
{
BT_PROFILE("InverseKinematics1Step");
if (ikHelperPtr && (endEffectorLinkIndex < bodyHandle->m_multiBody->getNumLinks()))
{
jacobian_linear.resize(3 * numDofs);
jacobian_angular.resize(3 * numDofs);
int jacSize = 0;
btInverseDynamics::MultiBodyTree* tree = m_data->findOrCreateTree(bodyHandle->m_multiBody);
q_current.resize(numDofs);
if (tree && ((numDofs + baseDofs) == tree->numDoFs()))
{
btInverseDynamics::vec3 world_origin;
btInverseDynamics::mat33 world_rot;
jacSize = jacobian_linear.size();
// Set jacobian value
int DofIndex = 0;
for (int i = 0; i < bodyHandle->m_multiBody->getNumLinks(); ++i)
{
if (bodyHandle->m_multiBody->getLink(i).m_jointType >= 0 && bodyHandle->m_multiBody->getLink(i).m_jointType <= 2)
{
// 0, 1, 2 represent revolute, prismatic, and spherical joint types respectively. Skip the fixed joints.
double curPos = startingPositions[DofIndex];
q_current[DofIndex] = curPos;
q[DofIndex + baseDofs] = curPos;
qdot[DofIndex + baseDofs] = 0;
nu[DofIndex + baseDofs] = 0;
DofIndex++;
}
} // Set the gravity to correspond to the world gravity
btInverseDynamics::vec3 id_grav(m_data->m_dynamicsWorld->getGravity());
{
BT_PROFILE("calculateInverseDynamics");
if (-1 != tree->setGravityInWorldFrame(id_grav) &&
-1 != tree->calculateInverseDynamics(q, qdot, nu, &joint_force))
{
tree->calculateJacobians(q);
btInverseDynamics::mat3x jac_t(3, numDofs + baseDofs);
btInverseDynamics::mat3x jac_r(3, numDofs + baseDofs);
// Note that inverse dynamics uses zero-based indexing of bodies, not starting from -1 for the base link.
tree->getBodyJacobianTrans(endEffectorLinkIndex + 1, &jac_t);
tree->getBodyJacobianRot(endEffectorLinkIndex + 1, &jac_r);
//calculatePositionKinematics is already done inside calculateInverseDynamics
tree->getBodyOrigin(endEffectorLinkIndex + 1, &world_origin);
tree->getBodyTransform(endEffectorLinkIndex + 1, &world_rot);
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < numDofs; ++j)
{
jacobian_linear[i * numDofs + j] = jac_t(i, (baseDofs + j));
jacobian_angular[i * numDofs + j] = jac_r(i, (baseDofs + j));
}
}
}
}
q_new.resize(numDofs);
int ikMethod = 0;
if ((clientCmd.m_updateFlags & IK_HAS_TARGET_ORIENTATION) && (clientCmd.m_updateFlags & IK_HAS_NULL_SPACE_VELOCITY))
{
//Nullspace task only works with DLS now. TODO: add nullspace task to SDLS.
ikMethod = IK2_VEL_DLS_WITH_ORIENTATION_NULLSPACE;
}
else if (clientCmd.m_updateFlags & IK_HAS_TARGET_ORIENTATION)
{
if (clientCmd.m_updateFlags & IK_SDLS)
{
ikMethod = IK2_VEL_SDLS_WITH_ORIENTATION;
}
else
{
ikMethod = IK2_VEL_DLS_WITH_ORIENTATION;
}
}
else if (clientCmd.m_updateFlags & IK_HAS_NULL_SPACE_VELOCITY)
{
//Nullspace task only works with DLS now. TODO: add nullspace task to SDLS.
ikMethod = IK2_VEL_DLS_WITH_NULLSPACE;
}
else
{
if (clientCmd.m_updateFlags & IK_SDLS)
{
ikMethod = IK2_VEL_SDLS;
}
else
{
ikMethod = IK2_VEL_DLS;
;
}
}
if (clientCmd.m_updateFlags & IK_HAS_NULL_SPACE_VELOCITY)
{
lower_limit.resize(numDofs);
upper_limit.resize(numDofs);
joint_range.resize(numDofs);
rest_pose.resize(numDofs);
for (int i = 0; i < numDofs; ++i)
{
lower_limit[i] = clientCmd.m_calculateInverseKinematicsArguments.m_lowerLimit[i];
upper_limit[i] = clientCmd.m_calculateInverseKinematicsArguments.m_upperLimit[i];
joint_range[i] = clientCmd.m_calculateInverseKinematicsArguments.m_jointRange[i];
rest_pose[i] = clientCmd.m_calculateInverseKinematicsArguments.m_restPose[i];
}
{
BT_PROFILE("computeNullspaceVel");
ikHelperPtr->computeNullspaceVel(numDofs, &q_current[0], &lower_limit[0], &upper_limit[0], &joint_range[0], &rest_pose[0]);
}
}
//btTransform endEffectorTransformWorld = bodyHandle->m_multiBody->getLink(endEffectorLinkIndex).m_cachedWorldTransform * bodyHandle->m_linkLocalInertialFrames[endEffectorLinkIndex].inverse();
btVector3DoubleData endEffectorWorldPosition;
btQuaternionDoubleData endEffectorWorldOrientation;
//get the position from the inverse dynamics (based on q) instead of endEffectorTransformWorld
btVector3 endEffectorPosWorldOrg = world_origin;
btQuaternion endEffectorOriWorldOrg;
world_rot.getRotation(endEffectorOriWorldOrg);
btTransform endEffectorBaseCoord;
endEffectorBaseCoord.setOrigin(endEffectorPosWorldOrg);
endEffectorBaseCoord.setRotation(endEffectorOriWorldOrg);
//don't need the next two lines
//btTransform linkInertiaInv = bodyHandle->m_linkLocalInertialFrames[endEffectorLinkIndex].inverse();
//endEffectorBaseCoord = endEffectorBaseCoord * linkInertiaInv;
//btTransform tr = bodyHandle->m_multiBody->getBaseWorldTransform();
//endEffectorBaseCoord = tr.inverse()*endEffectorTransformWorld;
//endEffectorBaseCoord = tr.inverse()*endEffectorTransformWorld;
btQuaternion endEffectorOriBaseCoord = endEffectorBaseCoord.getRotation();
//btVector4 endEffectorOri(endEffectorOriBaseCoord.x(), endEffectorOriBaseCoord.y(), endEffectorOriBaseCoord.z(), endEffectorOriBaseCoord.w());
endEffectorBaseCoord.getOrigin().serializeDouble(endEffectorWorldPosition);
endEffectorBaseCoord.getRotation().serializeDouble(endEffectorWorldOrientation);
//diff
currentDiff = (endEffectorBaseCoord.getOrigin() - targetBaseCoord.getOrigin()).length();
btVector3DoubleData targetPosBaseCoord;
btQuaternionDoubleData targetOrnBaseCoord;
targetBaseCoord.getOrigin().serializeDouble(targetPosBaseCoord);
targetBaseCoord.getRotation().serializeDouble(targetOrnBaseCoord);
// Set joint damping coefficents. A small default
// damping constant is added to prevent singularity
// with pseudo inverse. The user can set joint damping
// coefficients differently for each joint. The larger
// the damping coefficient is, the less we rely on
// this joint to achieve the IK target.
btAlignedObjectArray<double> joint_damping;
joint_damping.resize(numDofs, 0.5);
if (clientCmd.m_updateFlags & IK_HAS_JOINT_DAMPING)
{
for (int i = 0; i < numDofs; ++i)
{
joint_damping[i] = clientCmd.m_calculateInverseKinematicsArguments.m_jointDamping[i];
}
}
ikHelperPtr->setDampingCoeff(numDofs, &joint_damping[0]);
double targetDampCoeff[6] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
{
BT_PROFILE("computeIK");
ikHelperPtr->computeIK(targetPosBaseCoord.m_floats, targetOrnBaseCoord.m_floats,
endEffectorWorldPosition.m_floats, endEffectorWorldOrientation.m_floats,
&q_current[0],
numDofs, clientCmd.m_calculateInverseKinematicsArguments.m_endEffectorLinkIndices[0],
&q_new[0], ikMethod, &jacobian_linear[0], &jacobian_angular[0], jacSize * 2, targetDampCoeff);
}
serverCmd.m_inverseKinematicsResultArgs.m_bodyUniqueId = clientCmd.m_calculateInverseDynamicsArguments.m_bodyUniqueId;
for (int i = 0; i < numDofs; i++)
{
serverCmd.m_inverseKinematicsResultArgs.m_jointPositions[i] = q_new[i];
}
serverCmd.m_inverseKinematicsResultArgs.m_dofCount = numDofs;
serverCmd.m_type = CMD_CALCULATE_INVERSE_KINEMATICS_COMPLETED;
for (int i = 0; i < numDofs; i++)
{
startingPositions[i] = q_new[i];
}
}
}
}
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCalculateInverseKinematicsCommand2(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_CALCULATE_INVERSE_KINEMATICS");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CALCULATE_INVERSE_KINEMATICS_FAILED;
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(clientCmd.m_calculateInverseKinematicsArguments.m_bodyUniqueId);
if (bodyHandle && bodyHandle->m_multiBody)
{
IKTrajectoryHelper** ikHelperPtrPtr = m_data->m_inverseKinematicsHelpers.find(bodyHandle->m_multiBody);
IKTrajectoryHelper* ikHelperPtr = 0;
if (ikHelperPtrPtr)
{
ikHelperPtr = *ikHelperPtrPtr;
}
else
{
IKTrajectoryHelper* tmpHelper = new IKTrajectoryHelper;
m_data->m_inverseKinematicsHelpers.insert(bodyHandle->m_multiBody, tmpHelper);
ikHelperPtr = tmpHelper;
}
btAlignedObjectArray<double> startingPositions;
startingPositions.reserve(bodyHandle->m_multiBody->getNumLinks());
{
int DofIndex = 0;
for (int i = 0; i < bodyHandle->m_multiBody->getNumLinks(); ++i)
{
if (bodyHandle->m_multiBody->getLink(i).m_jointType >= 0 && bodyHandle->m_multiBody->getLink(i).m_jointType <= 2)
{
// 0, 1, 2 represent revolute, prismatic, and spherical joint types respectively. Skip the fixed joints.
double curPos = 0;
if (clientCmd.m_updateFlags & IK_HAS_CURRENT_JOINT_POSITIONS)
{
curPos = clientCmd.m_calculateInverseKinematicsArguments.m_currentPositions[DofIndex];
}
else
{
curPos = bodyHandle->m_multiBody->getJointPos(i);
}
startingPositions.push_back(curPos);
DofIndex++;
}
}
}
int numIterations = 20;
if (clientCmd.m_updateFlags & IK_HAS_MAX_ITERATIONS)
{
numIterations = clientCmd.m_calculateInverseKinematicsArguments.m_maxNumIterations;
}
double residualThreshold = 1e-4;
if (clientCmd.m_updateFlags & IK_HAS_RESIDUAL_THRESHOLD)
{
residualThreshold = clientCmd.m_calculateInverseKinematicsArguments.m_residualThreshold;
}
btScalar currentDiff = 1e30f;
b3AlignedObjectArray<double> endEffectorTargetWorldPositions;
b3AlignedObjectArray<double> endEffectorTargetWorldOrientations;
b3AlignedObjectArray<double> endEffectorCurrentWorldPositions;
b3AlignedObjectArray<double> jacobian_linear;
b3AlignedObjectArray<double> jacobian_angular;
btAlignedObjectArray<double> q_current;
btAlignedObjectArray<double> q_new;
btAlignedObjectArray<double> lower_limit;
btAlignedObjectArray<double> upper_limit;
btAlignedObjectArray<double> joint_range;
btAlignedObjectArray<double> rest_pose;
const int numDofs = bodyHandle->m_multiBody->getNumDofs();
int baseDofs = bodyHandle->m_multiBody->hasFixedBase() ? 0 : 6;
btInverseDynamics::vecx nu(numDofs + baseDofs), qdot(numDofs + baseDofs), q(numDofs + baseDofs), joint_force(numDofs + baseDofs);
endEffectorTargetWorldPositions.resize(0);
endEffectorTargetWorldPositions.reserve(clientCmd.m_calculateInverseKinematicsArguments.m_numEndEffectorLinkIndices * 3);
endEffectorTargetWorldOrientations.resize(0);
endEffectorTargetWorldOrientations.reserve(clientCmd.m_calculateInverseKinematicsArguments.m_numEndEffectorLinkIndices * 4);
bool validEndEffectorLinkIndices = true;
for (int ne = 0; ne < clientCmd.m_calculateInverseKinematicsArguments.m_numEndEffectorLinkIndices; ne++)
{
int endEffectorLinkIndex = clientCmd.m_calculateInverseKinematicsArguments.m_endEffectorLinkIndices[ne];
validEndEffectorLinkIndices = validEndEffectorLinkIndices && (endEffectorLinkIndex < bodyHandle->m_multiBody->getNumLinks());
btVector3 targetPosWorld(clientCmd.m_calculateInverseKinematicsArguments.m_targetPositions[ne * 3 + 0],
clientCmd.m_calculateInverseKinematicsArguments.m_targetPositions[ne * 3 + 1],
clientCmd.m_calculateInverseKinematicsArguments.m_targetPositions[ne * 3 + 2]);
btQuaternion targetOrnWorld(clientCmd.m_calculateInverseKinematicsArguments.m_targetOrientation[ne * 4 + 0],
clientCmd.m_calculateInverseKinematicsArguments.m_targetOrientation[ne * 4 + 1],
clientCmd.m_calculateInverseKinematicsArguments.m_targetOrientation[ne * 4 + 2],
clientCmd.m_calculateInverseKinematicsArguments.m_targetOrientation[ne * 4 + 3]);
btTransform targetBaseCoord;
if (clientCmd.m_updateFlags & IK_HAS_CURRENT_JOINT_POSITIONS)
{
targetBaseCoord.setOrigin(targetPosWorld);
targetBaseCoord.setRotation(targetOrnWorld);
}
else
{
btTransform targetWorld;
targetWorld.setOrigin(targetPosWorld);
targetWorld.setRotation(targetOrnWorld);
btTransform tr = bodyHandle->m_multiBody->getBaseWorldTransform();
targetBaseCoord = tr.inverse() * targetWorld;
}
btVector3DoubleData targetPosBaseCoord;
btQuaternionDoubleData targetOrnBaseCoord;
targetBaseCoord.getOrigin().serializeDouble(targetPosBaseCoord);
targetBaseCoord.getRotation().serializeDouble(targetOrnBaseCoord);
endEffectorTargetWorldPositions.push_back(targetPosBaseCoord.m_floats[0]);
endEffectorTargetWorldPositions.push_back(targetPosBaseCoord.m_floats[1]);
endEffectorTargetWorldPositions.push_back(targetPosBaseCoord.m_floats[2]);
endEffectorTargetWorldOrientations.push_back(targetOrnBaseCoord.m_floats[0]);
endEffectorTargetWorldOrientations.push_back(targetOrnBaseCoord.m_floats[1]);
endEffectorTargetWorldOrientations.push_back(targetOrnBaseCoord.m_floats[2]);
endEffectorTargetWorldOrientations.push_back(targetOrnBaseCoord.m_floats[3]);
}
for (int i = 0; i < numIterations && currentDiff > residualThreshold; i++)
{
BT_PROFILE("InverseKinematics1Step");
if (ikHelperPtr && validEndEffectorLinkIndices)
{
jacobian_linear.resize(clientCmd.m_calculateInverseKinematicsArguments.m_numEndEffectorLinkIndices * 3 * numDofs);
jacobian_angular.resize(clientCmd.m_calculateInverseKinematicsArguments.m_numEndEffectorLinkIndices * 3 * numDofs);
int jacSize = 0;
btInverseDynamics::MultiBodyTree* tree = m_data->findOrCreateTree(bodyHandle->m_multiBody);
q_current.resize(numDofs);
if (tree && ((numDofs + baseDofs) == tree->numDoFs()))
{
btInverseDynamics::vec3 world_origin;
btInverseDynamics::mat33 world_rot;
jacSize = jacobian_linear.size();
// Set jacobian value
int DofIndex = 0;
for (int i = 0; i < bodyHandle->m_multiBody->getNumLinks(); ++i)
{
if (bodyHandle->m_multiBody->getLink(i).m_jointType >= 0 && bodyHandle->m_multiBody->getLink(i).m_jointType <= 2)
{
// 0, 1, 2 represent revolute, prismatic, and spherical joint types respectively. Skip the fixed joints.
double curPos = startingPositions[DofIndex];
q_current[DofIndex] = curPos;
q[DofIndex + baseDofs] = curPos;
qdot[DofIndex + baseDofs] = 0;
nu[DofIndex + baseDofs] = 0;
DofIndex++;
}
} // Set the gravity to correspond to the world gravity
btInverseDynamics::vec3 id_grav(m_data->m_dynamicsWorld->getGravity());
{
BT_PROFILE("calculateInverseDynamics");
if (-1 != tree->setGravityInWorldFrame(id_grav) &&
-1 != tree->calculateInverseDynamics(q, qdot, nu, &joint_force))
{
tree->calculateJacobians(q);
btInverseDynamics::mat3x jac_t(3, numDofs + baseDofs);
btInverseDynamics::mat3x jac_r(3, numDofs + baseDofs);
currentDiff = 0;
endEffectorCurrentWorldPositions.resize(0);
endEffectorCurrentWorldPositions.reserve(clientCmd.m_calculateInverseKinematicsArguments.m_numEndEffectorLinkIndices * 3);
for (int ne = 0; ne < clientCmd.m_calculateInverseKinematicsArguments.m_numEndEffectorLinkIndices; ne++)
{
int endEffectorLinkIndex2 = clientCmd.m_calculateInverseKinematicsArguments.m_endEffectorLinkIndices[ne];
// Note that inverse dynamics uses zero-based indexing of bodies, not starting from -1 for the base link.
tree->getBodyJacobianTrans(endEffectorLinkIndex2 + 1, &jac_t);
tree->getBodyJacobianRot(endEffectorLinkIndex2 + 1, &jac_r);
//calculatePositionKinematics is already done inside calculateInverseDynamics
tree->getBodyOrigin(endEffectorLinkIndex2 + 1, &world_origin);
tree->getBodyTransform(endEffectorLinkIndex2 + 1, &world_rot);
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < numDofs; ++j)
{
jacobian_linear[(ne * 3 + i) * numDofs + j] = jac_t(i, (baseDofs + j));
jacobian_angular[(ne * 3 + i) * numDofs + j] = jac_r(i, (baseDofs + j));
}
}
endEffectorCurrentWorldPositions.push_back(world_origin[0]);
endEffectorCurrentWorldPositions.push_back(world_origin[1]);
endEffectorCurrentWorldPositions.push_back(world_origin[2]);
btInverseDynamics::vec3 targetPos(btVector3(endEffectorTargetWorldPositions[ne * 3 + 0],
endEffectorTargetWorldPositions[ne * 3 + 1],
endEffectorTargetWorldPositions[ne * 3 + 2]));
//diff
currentDiff = btMax(currentDiff, (world_origin - targetPos).length());
}
}
}
q_new.resize(numDofs);
int ikMethod = 0;
if ((clientCmd.m_updateFlags & IK_HAS_TARGET_ORIENTATION) && (clientCmd.m_updateFlags & IK_HAS_NULL_SPACE_VELOCITY))
{
//Nullspace task only works with DLS now. TODO: add nullspace task to SDLS.
ikMethod = IK2_VEL_DLS_WITH_ORIENTATION_NULLSPACE;
}
else if (clientCmd.m_updateFlags & IK_HAS_TARGET_ORIENTATION)
{
if (clientCmd.m_updateFlags & IK_SDLS)
{
ikMethod = IK2_VEL_SDLS_WITH_ORIENTATION;
}
else
{
ikMethod = IK2_VEL_DLS_WITH_ORIENTATION;
}
}
else if (clientCmd.m_updateFlags & IK_HAS_NULL_SPACE_VELOCITY)
{
//Nullspace task only works with DLS now. TODO: add nullspace task to SDLS.
ikMethod = IK2_VEL_DLS_WITH_NULLSPACE;
}
else
{
if (clientCmd.m_updateFlags & IK_SDLS)
{
ikMethod = IK2_VEL_SDLS;
}
else
{
ikMethod = IK2_VEL_DLS;
;
}
}
if (clientCmd.m_updateFlags & IK_HAS_NULL_SPACE_VELOCITY)
{
lower_limit.resize(numDofs);
upper_limit.resize(numDofs);
joint_range.resize(numDofs);
rest_pose.resize(numDofs);
for (int i = 0; i < numDofs; ++i)
{
lower_limit[i] = clientCmd.m_calculateInverseKinematicsArguments.m_lowerLimit[i];
upper_limit[i] = clientCmd.m_calculateInverseKinematicsArguments.m_upperLimit[i];
joint_range[i] = clientCmd.m_calculateInverseKinematicsArguments.m_jointRange[i];
rest_pose[i] = clientCmd.m_calculateInverseKinematicsArguments.m_restPose[i];
}
{
BT_PROFILE("computeNullspaceVel");
ikHelperPtr->computeNullspaceVel(numDofs, &q_current[0], &lower_limit[0], &upper_limit[0], &joint_range[0], &rest_pose[0]);
}
}
//btTransform endEffectorTransformWorld = bodyHandle->m_multiBody->getLink(endEffectorLinkIndex).m_cachedWorldTransform * bodyHandle->m_linkLocalInertialFrames[endEffectorLinkIndex].inverse();
btVector3DoubleData endEffectorWorldPosition;
btQuaternionDoubleData endEffectorWorldOrientation;
//get the position from the inverse dynamics (based on q) instead of endEffectorTransformWorld
btVector3 endEffectorPosWorldOrg = world_origin;
btQuaternion endEffectorOriWorldOrg;
world_rot.getRotation(endEffectorOriWorldOrg);
btTransform endEffectorBaseCoord;
endEffectorBaseCoord.setOrigin(endEffectorPosWorldOrg);
endEffectorBaseCoord.setRotation(endEffectorOriWorldOrg);
//don't need the next two lines
//btTransform linkInertiaInv = bodyHandle->m_linkLocalInertialFrames[endEffectorLinkIndex].inverse();
//endEffectorBaseCoord = endEffectorBaseCoord * linkInertiaInv;
//btTransform tr = bodyHandle->m_multiBody->getBaseWorldTransform();
//endEffectorBaseCoord = tr.inverse()*endEffectorTransformWorld;
//endEffectorBaseCoord = tr.inverse()*endEffectorTransformWorld;
btQuaternion endEffectorOriBaseCoord = endEffectorBaseCoord.getRotation();
//btVector4 endEffectorOri(endEffectorOriBaseCoord.x(), endEffectorOriBaseCoord.y(), endEffectorOriBaseCoord.z(), endEffectorOriBaseCoord.w());
endEffectorBaseCoord.getOrigin().serializeDouble(endEffectorWorldPosition);
endEffectorBaseCoord.getRotation().serializeDouble(endEffectorWorldOrientation);
// Set joint damping coefficents. A small default
// damping constant is added to prevent singularity
// with pseudo inverse. The user can set joint damping
// coefficients differently for each joint. The larger
// the damping coefficient is, the less we rely on
// this joint to achieve the IK target.
btAlignedObjectArray<double> joint_damping;
joint_damping.resize(numDofs, 0.5);
if (clientCmd.m_updateFlags & IK_HAS_JOINT_DAMPING)
{
for (int i = 0; i < numDofs; ++i)
{
joint_damping[i] = clientCmd.m_calculateInverseKinematicsArguments.m_jointDamping[i];
}
}
ikHelperPtr->setDampingCoeff(numDofs, &joint_damping[0]);
double targetDampCoeff[6] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
bool performedIK = false;
if (clientCmd.m_calculateInverseKinematicsArguments.m_numEndEffectorLinkIndices == 1)
{
BT_PROFILE("computeIK");
ikHelperPtr->computeIK(&endEffectorTargetWorldPositions[0],
&endEffectorTargetWorldOrientations[0],
endEffectorWorldPosition.m_floats, endEffectorWorldOrientation.m_floats,
&q_current[0],
numDofs, clientCmd.m_calculateInverseKinematicsArguments.m_endEffectorLinkIndices[0],
&q_new[0], ikMethod, &jacobian_linear[0], &jacobian_angular[0], jacSize * 2, targetDampCoeff);
performedIK = true;
}
else
{
if (clientCmd.m_calculateInverseKinematicsArguments.m_numEndEffectorLinkIndices > 1)
{
ikHelperPtr->computeIK2(&endEffectorTargetWorldPositions[0],
&endEffectorCurrentWorldPositions[0],
clientCmd.m_calculateInverseKinematicsArguments.m_numEndEffectorLinkIndices,
//endEffectorWorldOrientation.m_floats,
&q_current[0],
numDofs,
&q_new[0], ikMethod, &jacobian_linear[0], targetDampCoeff);
performedIK = true;
}
}
if (performedIK)
{
serverCmd.m_inverseKinematicsResultArgs.m_bodyUniqueId = clientCmd.m_calculateInverseDynamicsArguments.m_bodyUniqueId;
for (int i = 0; i < numDofs; i++)
{
serverCmd.m_inverseKinematicsResultArgs.m_jointPositions[i] = q_new[i];
}
serverCmd.m_inverseKinematicsResultArgs.m_dofCount = numDofs;
serverCmd.m_type = CMD_CALCULATE_INVERSE_KINEMATICS_COMPLETED;
for (int i = 0; i < numDofs; i++)
{
startingPositions[i] = q_new[i];
}
}
}
}
}
}
return hasStatus;
}
// PyModule_AddIntConstant(m, "GEOM_SPHERE", GEOM_SPHERE);
// PyModule_AddIntConstant(m, "GEOM_BOX", GEOM_BOX);
// PyModule_AddIntConstant(m, "GEOM_CYLINDER", GEOM_CYLINDER);
// PyModule_AddIntConstant(m, "GEOM_MESH", GEOM_MESH);
// PyModule_AddIntConstant(m, "GEOM_PLANE", GEOM_PLANE);
// PyModule_AddIntConstant(m, "GEOM_CAPSULE", GEOM_CAPSULE);
int PhysicsServerCommandProcessor::extractCollisionShapes(const btCollisionShape* colShape, const btTransform& transform, b3CollisionShapeData* collisionShapeBuffer, int maxCollisionShapes)
{
if (maxCollisionShapes <= 0)
{
b3Warning("No space in buffer");
return 0;
}
int numConverted = 0;
collisionShapeBuffer[0].m_localCollisionFrame[0] = transform.getOrigin()[0];
collisionShapeBuffer[0].m_localCollisionFrame[1] = transform.getOrigin()[1];
collisionShapeBuffer[0].m_localCollisionFrame[2] = transform.getOrigin()[2];
collisionShapeBuffer[0].m_localCollisionFrame[3] = transform.getRotation()[0];
collisionShapeBuffer[0].m_localCollisionFrame[4] = transform.getRotation()[1];
collisionShapeBuffer[0].m_localCollisionFrame[5] = transform.getRotation()[2];
collisionShapeBuffer[0].m_localCollisionFrame[6] = transform.getRotation()[3];
collisionShapeBuffer[0].m_meshAssetFileName[0] = 0;
switch (colShape->getShapeType())
{
case STATIC_PLANE_PROXYTYPE:
{
btStaticPlaneShape* plane = (btStaticPlaneShape*)colShape;
collisionShapeBuffer[0].m_collisionGeometryType = GEOM_PLANE;
collisionShapeBuffer[0].m_dimensions[0] = plane->getPlaneNormal()[0];
collisionShapeBuffer[0].m_dimensions[1] = plane->getPlaneNormal()[1];
collisionShapeBuffer[0].m_dimensions[2] = plane->getPlaneNormal()[2];
numConverted += 1;
break;
}
case TRIANGLE_MESH_SHAPE_PROXYTYPE:
case SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE:
case CONVEX_HULL_SHAPE_PROXYTYPE:
{
UrdfCollision* urdfCol = m_data->m_bulletCollisionShape2UrdfCollision.find(colShape);
if (urdfCol && (urdfCol->m_geometry.m_type == URDF_GEOM_MESH))
{
collisionShapeBuffer[0].m_collisionGeometryType = GEOM_MESH;
collisionShapeBuffer[0].m_dimensions[0] = urdfCol->m_geometry.m_meshScale[0];
collisionShapeBuffer[0].m_dimensions[1] = urdfCol->m_geometry.m_meshScale[1];
collisionShapeBuffer[0].m_dimensions[2] = urdfCol->m_geometry.m_meshScale[2];
strcpy(collisionShapeBuffer[0].m_meshAssetFileName, urdfCol->m_geometry.m_meshFileName.c_str());
numConverted += 1;
}
else
{
collisionShapeBuffer[0].m_collisionGeometryType = GEOM_MESH;
sprintf(collisionShapeBuffer[0].m_meshAssetFileName, "unknown_file");
collisionShapeBuffer[0].m_dimensions[0] = 1;
collisionShapeBuffer[0].m_dimensions[1] = 1;
collisionShapeBuffer[0].m_dimensions[2] = 1;
numConverted++;
}
break;
}
case CAPSULE_SHAPE_PROXYTYPE:
{
btCapsuleShapeZ* capsule = (btCapsuleShapeZ*)colShape;
collisionShapeBuffer[0].m_collisionGeometryType = GEOM_CAPSULE;
collisionShapeBuffer[0].m_dimensions[0] = 2. * capsule->getHalfHeight();
collisionShapeBuffer[0].m_dimensions[1] = capsule->getRadius();
collisionShapeBuffer[0].m_dimensions[2] = 0;
numConverted++;
break;
}
case CYLINDER_SHAPE_PROXYTYPE:
{
btCylinderShapeZ* cyl = (btCylinderShapeZ*)colShape;
collisionShapeBuffer[0].m_collisionGeometryType = GEOM_CYLINDER;
collisionShapeBuffer[0].m_dimensions[0] = 2. * cyl->getHalfExtentsWithMargin().getZ();
collisionShapeBuffer[0].m_dimensions[1] = cyl->getHalfExtentsWithMargin().getX();
collisionShapeBuffer[0].m_dimensions[2] = 0;
numConverted++;
break;
}
case BOX_SHAPE_PROXYTYPE:
{
btBoxShape* box = (btBoxShape*)colShape;
btVector3 halfExtents = box->getHalfExtentsWithMargin();
collisionShapeBuffer[0].m_collisionGeometryType = GEOM_BOX;
collisionShapeBuffer[0].m_dimensions[0] = 2. * halfExtents[0];
collisionShapeBuffer[0].m_dimensions[1] = 2. * halfExtents[1];
collisionShapeBuffer[0].m_dimensions[2] = 2. * halfExtents[2];
numConverted++;
break;
}
case SPHERE_SHAPE_PROXYTYPE:
{
btSphereShape* sphere = (btSphereShape*)colShape;
collisionShapeBuffer[0].m_collisionGeometryType = GEOM_SPHERE;
collisionShapeBuffer[0].m_dimensions[0] = sphere->getRadius();
collisionShapeBuffer[0].m_dimensions[1] = sphere->getRadius();
collisionShapeBuffer[0].m_dimensions[2] = sphere->getRadius();
numConverted++;
break;
}
case COMPOUND_SHAPE_PROXYTYPE:
{
//it could be a compound mesh from a wavefront OBJ, check it
UrdfCollision* urdfCol = m_data->m_bulletCollisionShape2UrdfCollision.find(colShape);
if (urdfCol && (urdfCol->m_geometry.m_type == URDF_GEOM_MESH))
{
collisionShapeBuffer[0].m_collisionGeometryType = GEOM_MESH;
collisionShapeBuffer[0].m_dimensions[0] = urdfCol->m_geometry.m_meshScale[0];
collisionShapeBuffer[0].m_dimensions[1] = urdfCol->m_geometry.m_meshScale[1];
collisionShapeBuffer[0].m_dimensions[2] = urdfCol->m_geometry.m_meshScale[2];
strcpy(collisionShapeBuffer[0].m_meshAssetFileName, urdfCol->m_geometry.m_meshFileName.c_str());
numConverted += 1;
}
else
{
//recurse, accumulate childTransform
btCompoundShape* compound = (btCompoundShape*)colShape;
for (int i = 0; i < compound->getNumChildShapes(); i++)
{
btTransform childTrans = transform * compound->getChildTransform(i);
int remain = maxCollisionShapes - numConverted;
int converted = extractCollisionShapes(compound->getChildShape(i), childTrans, &collisionShapeBuffer[numConverted], remain);
numConverted += converted;
}
}
break;
}
default:
{
b3Warning("Unexpected collision shape type in PhysicsServerCommandProcessor::extractCollisionShapes");
}
};
return numConverted;
}
bool PhysicsServerCommandProcessor::processRequestCollisionShapeInfoCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_COLLISION_SHAPE_INFO");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_COLLISION_SHAPE_INFO_FAILED;
int bodyUniqueId = clientCmd.m_requestCollisionShapeDataArguments.m_bodyUniqueId;
int linkIndex = clientCmd.m_requestCollisionShapeDataArguments.m_linkIndex;
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (bodyHandle)
{
if (bodyHandle->m_multiBody)
{
b3CollisionShapeData* collisionShapeStoragePtr = (b3CollisionShapeData*)bufferServerToClient;
int totalBytesPerObject = sizeof(b3CollisionShapeData);
int maxNumColObjects = bufferSizeInBytes / totalBytesPerObject - 1;
btTransform childTrans;
childTrans.setIdentity();
serverCmd.m_sendCollisionShapeArgs.m_bodyUniqueId = bodyUniqueId;
serverCmd.m_sendCollisionShapeArgs.m_linkIndex = linkIndex;
if (linkIndex == -1)
{
if (bodyHandle->m_multiBody->getBaseCollider())
{
//extract shape info from base collider
int numConvertedCollisionShapes = extractCollisionShapes(bodyHandle->m_multiBody->getBaseCollider()->getCollisionShape(), childTrans, collisionShapeStoragePtr, maxNumColObjects);
serverCmd.m_sendCollisionShapeArgs.m_numCollisionShapes = numConvertedCollisionShapes;
serverCmd.m_type = CMD_COLLISION_SHAPE_INFO_COMPLETED;
}
}
else
{
if (linkIndex >= 0 && linkIndex < bodyHandle->m_multiBody->getNumLinks() && bodyHandle->m_multiBody->getLinkCollider(linkIndex))
{
int numConvertedCollisionShapes = extractCollisionShapes(bodyHandle->m_multiBody->getLinkCollider(linkIndex)->getCollisionShape(), childTrans, collisionShapeStoragePtr, maxNumColObjects);
serverCmd.m_sendCollisionShapeArgs.m_numCollisionShapes = numConvertedCollisionShapes;
serverCmd.m_type = CMD_COLLISION_SHAPE_INFO_COMPLETED;
}
}
}
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestVisualShapeInfoCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_VISUAL_SHAPE_INFO");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_VISUAL_SHAPE_INFO_FAILED;
//retrieve the visual shape information for a specific body
if (m_data->m_pluginManager.getRenderInterface())
{
int totalNumVisualShapes = m_data->m_pluginManager.getRenderInterface()->getNumVisualShapes(clientCmd.m_requestVisualShapeDataArguments.m_bodyUniqueId);
//int totalBytesPerVisualShape = sizeof (b3VisualShapeData);
//int visualShapeStorage = bufferSizeInBytes / totalBytesPerVisualShape - 1;
//set serverCmd.m_sendVisualShapeArgs when totalNumVisualShapes is zero
if (totalNumVisualShapes == 0)
{
serverCmd.m_sendVisualShapeArgs.m_numRemainingVisualShapes = 0;
serverCmd.m_sendVisualShapeArgs.m_numVisualShapesCopied = 0;
serverCmd.m_sendVisualShapeArgs.m_startingVisualShapeIndex = clientCmd.m_requestVisualShapeDataArguments.m_startingVisualShapeIndex;
serverCmd.m_sendVisualShapeArgs.m_bodyUniqueId = clientCmd.m_requestVisualShapeDataArguments.m_bodyUniqueId;
serverCmd.m_numDataStreamBytes = sizeof(b3VisualShapeData) * serverCmd.m_sendVisualShapeArgs.m_numVisualShapesCopied;
serverCmd.m_type = CMD_VISUAL_SHAPE_INFO_COMPLETED;
}
else
{
b3VisualShapeData* visualShapeStoragePtr = (b3VisualShapeData*)bufferServerToClient;
int remain = totalNumVisualShapes - clientCmd.m_requestVisualShapeDataArguments.m_startingVisualShapeIndex;
int shapeIndex = clientCmd.m_requestVisualShapeDataArguments.m_startingVisualShapeIndex;
int success = m_data->m_pluginManager.getRenderInterface()->getVisualShapesData(clientCmd.m_requestVisualShapeDataArguments.m_bodyUniqueId,
shapeIndex,
visualShapeStoragePtr);
if (success)
{
//find the matching texture unique ids.
if (visualShapeStoragePtr->m_tinyRendererTextureId >= 0)
{
b3AlignedObjectArray<int> usedHandles;
m_data->m_textureHandles.getUsedHandles(usedHandles);
for (int i = 0; i < usedHandles.size(); i++)
{
int texHandle = usedHandles[i];
InternalTextureHandle* texH = m_data->m_textureHandles.getHandle(texHandle);
if (texH && (texH->m_tinyRendererTextureId == visualShapeStoragePtr->m_tinyRendererTextureId))
{
visualShapeStoragePtr->m_openglTextureId = texH->m_openglTextureId;
visualShapeStoragePtr->m_textureUniqueId = texHandle;
}
}
}
serverCmd.m_sendVisualShapeArgs.m_numRemainingVisualShapes = remain - 1;
serverCmd.m_sendVisualShapeArgs.m_numVisualShapesCopied = 1;
serverCmd.m_sendVisualShapeArgs.m_startingVisualShapeIndex = clientCmd.m_requestVisualShapeDataArguments.m_startingVisualShapeIndex;
serverCmd.m_sendVisualShapeArgs.m_bodyUniqueId = clientCmd.m_requestVisualShapeDataArguments.m_bodyUniqueId;
serverCmd.m_numDataStreamBytes = sizeof(b3VisualShapeData) * serverCmd.m_sendVisualShapeArgs.m_numVisualShapesCopied;
serverCmd.m_type = CMD_VISUAL_SHAPE_INFO_COMPLETED;
}
else
{
b3Warning("failed to get shape info");
}
}
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processUpdateVisualShapeCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_UPDATE_VISUAL_SHAPE");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_VISUAL_SHAPE_UPDATE_FAILED;
InternalTextureHandle* texHandle = 0;
if (clientCmd.m_updateFlags & CMD_UPDATE_VISUAL_SHAPE_TEXTURE)
{
if (clientCmd.m_updateVisualShapeDataArguments.m_textureUniqueId >= 0)
{
texHandle = m_data->m_textureHandles.getHandle(clientCmd.m_updateVisualShapeDataArguments.m_textureUniqueId);
}
if (clientCmd.m_updateVisualShapeDataArguments.m_textureUniqueId >= -1)
{
if (texHandle)
{
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->changeShapeTexture(clientCmd.m_updateVisualShapeDataArguments.m_bodyUniqueId,
clientCmd.m_updateVisualShapeDataArguments.m_jointIndex,
clientCmd.m_updateVisualShapeDataArguments.m_shapeIndex,
texHandle->m_tinyRendererTextureId);
}
}
else
{
m_data->m_pluginManager.getRenderInterface()->changeShapeTexture(clientCmd.m_updateVisualShapeDataArguments.m_bodyUniqueId,
clientCmd.m_updateVisualShapeDataArguments.m_jointIndex,
clientCmd.m_updateVisualShapeDataArguments.m_shapeIndex,
-1);
}
}
}
{
int bodyUniqueId = clientCmd.m_updateVisualShapeDataArguments.m_bodyUniqueId;
int linkIndex = clientCmd.m_updateVisualShapeDataArguments.m_jointIndex;
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (bodyHandle)
{
if (bodyHandle->m_multiBody)
{
if (linkIndex == -1)
{
if (bodyHandle->m_multiBody->getBaseCollider())
{
int graphicsIndex = bodyHandle->m_multiBody->getBaseCollider()->getUserIndex();
if (clientCmd.m_updateFlags & CMD_UPDATE_VISUAL_SHAPE_TEXTURE)
{
int shapeIndex = m_data->m_guiHelper->getShapeIndexFromInstance(graphicsIndex);
if (texHandle)
{
m_data->m_guiHelper->replaceTexture(shapeIndex, texHandle->m_openglTextureId);
}
else
{
m_data->m_guiHelper->replaceTexture(shapeIndex, -1);
}
}
if (clientCmd.m_updateFlags & CMD_UPDATE_VISUAL_SHAPE_RGBA_COLOR)
{
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->changeRGBAColor(bodyUniqueId, linkIndex,
clientCmd.m_updateVisualShapeDataArguments.m_shapeIndex,
clientCmd.m_updateVisualShapeDataArguments.m_rgbaColor);
}
m_data->m_guiHelper->changeRGBAColor(graphicsIndex, clientCmd.m_updateVisualShapeDataArguments.m_rgbaColor);
}
if (clientCmd.m_updateFlags & CMD_UPDATE_VISUAL_SHAPE_SPECULAR_COLOR)
{
m_data->m_guiHelper->changeSpecularColor(graphicsIndex, clientCmd.m_updateVisualShapeDataArguments.m_specularColor);
}
}
}
else
{
if (linkIndex < bodyHandle->m_multiBody->getNumLinks())
{
if (bodyHandle->m_multiBody->getLink(linkIndex).m_collider)
{
int graphicsIndex = bodyHandle->m_multiBody->getLink(linkIndex).m_collider->getUserIndex();
if (clientCmd.m_updateFlags & CMD_UPDATE_VISUAL_SHAPE_TEXTURE)
{
int shapeIndex = m_data->m_guiHelper->getShapeIndexFromInstance(graphicsIndex);
if (texHandle)
{
m_data->m_guiHelper->replaceTexture(shapeIndex, texHandle->m_openglTextureId);
}
else
{
m_data->m_guiHelper->replaceTexture(shapeIndex, -1);
}
}
if (clientCmd.m_updateFlags & CMD_UPDATE_VISUAL_SHAPE_RGBA_COLOR)
{
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->changeRGBAColor(bodyUniqueId, linkIndex,
clientCmd.m_updateVisualShapeDataArguments.m_shapeIndex, clientCmd.m_updateVisualShapeDataArguments.m_rgbaColor);
}
m_data->m_guiHelper->changeRGBAColor(graphicsIndex, clientCmd.m_updateVisualShapeDataArguments.m_rgbaColor);
}
if (clientCmd.m_updateFlags & CMD_UPDATE_VISUAL_SHAPE_SPECULAR_COLOR)
{
m_data->m_guiHelper->changeSpecularColor(graphicsIndex, clientCmd.m_updateVisualShapeDataArguments.m_specularColor);
}
}
}
}
}
else
{
if (bodyHandle->m_rigidBody)
{
int graphicsIndex = bodyHandle->m_rigidBody->getUserIndex();
if (clientCmd.m_updateFlags & CMD_UPDATE_VISUAL_SHAPE_TEXTURE)
{
if (texHandle)
{
int shapeIndex = m_data->m_guiHelper->getShapeIndexFromInstance(graphicsIndex);
m_data->m_guiHelper->replaceTexture(shapeIndex, texHandle->m_openglTextureId);
}
}
if (clientCmd.m_updateFlags & CMD_UPDATE_VISUAL_SHAPE_RGBA_COLOR)
{
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->changeRGBAColor(bodyUniqueId, linkIndex,
clientCmd.m_updateVisualShapeDataArguments.m_shapeIndex, clientCmd.m_updateVisualShapeDataArguments.m_rgbaColor);
}
m_data->m_guiHelper->changeRGBAColor(graphicsIndex, clientCmd.m_updateVisualShapeDataArguments.m_rgbaColor);
}
if (clientCmd.m_updateFlags & CMD_UPDATE_VISUAL_SHAPE_SPECULAR_COLOR)
{
m_data->m_guiHelper->changeSpecularColor(graphicsIndex, clientCmd.m_updateVisualShapeDataArguments.m_specularColor);
}
}
}
}
}
serverCmd.m_type = CMD_VISUAL_SHAPE_UPDATE_COMPLETED;
b3Notification notification;
notification.m_notificationType = VISUAL_SHAPE_CHANGED;
notification.m_visualShapeArgs.m_bodyUniqueId = clientCmd.m_updateVisualShapeDataArguments.m_bodyUniqueId;
notification.m_visualShapeArgs.m_linkIndex = clientCmd.m_updateVisualShapeDataArguments.m_jointIndex;
notification.m_visualShapeArgs.m_visualShapeIndex = clientCmd.m_updateVisualShapeDataArguments.m_shapeIndex;
m_data->m_pluginManager.addNotification(notification);
return hasStatus;
}
bool PhysicsServerCommandProcessor::processChangeTextureCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CHANGE_TEXTURE_COMMAND_FAILED;
InternalTextureHandle* texH = m_data->m_textureHandles.getHandle(clientCmd.m_changeTextureArgs.m_textureUniqueId);
if (texH)
{
int gltex = texH->m_openglTextureId;
m_data->m_guiHelper->changeTexture(gltex,
(const unsigned char*)bufferServerToClient, clientCmd.m_changeTextureArgs.m_width, clientCmd.m_changeTextureArgs.m_height);
serverCmd.m_type = CMD_CLIENT_COMMAND_COMPLETED;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processLoadTextureCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_LOAD_TEXTURE");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_LOAD_TEXTURE_FAILED;
char relativeFileName[1024];
char pathPrefix[1024];
CommonFileIOInterface* fileIO(m_data->m_pluginManager.getFileIOInterface());
if (fileIO->findResourcePath(clientCmd.m_loadTextureArguments.m_textureFileName, relativeFileName, 1024))
{
b3FileUtils::extractPath(relativeFileName, pathPrefix, 1024);
int texHandle = m_data->m_textureHandles.allocHandle();
InternalTextureHandle* texH = m_data->m_textureHandles.getHandle(texHandle);
if (texH)
{
texH->m_tinyRendererTextureId = -1;
texH->m_openglTextureId = -1;
int uid = -1;
if (m_data->m_pluginManager.getRenderInterface())
{
uid = m_data->m_pluginManager.getRenderInterface()->loadTextureFile(relativeFileName, fileIO);
}
if (uid >= 0)
{
texH->m_tinyRendererTextureId = uid;
}
{
int width, height, n;
unsigned char* imageData = 0;
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
if (fileIO)
{
b3AlignedObjectArray<char> buffer;
buffer.reserve(1024);
int fileId = fileIO->fileOpen(relativeFileName, "rb");
if (fileId >= 0)
{
int size = fileIO->getFileSize(fileId);
if (size > 0)
{
buffer.resize(size);
int actual = fileIO->fileRead(fileId, &buffer[0], size);
if (actual != size)
{
b3Warning("image filesize mismatch!\n");
buffer.resize(0);
}
}
fileIO->fileClose(fileId);
}
if (buffer.size())
{
imageData = stbi_load_from_memory((const unsigned char*)&buffer[0], buffer.size(), &width, &height, &n, 3);
}
}
else
{
imageData = stbi_load(relativeFileName, &width, &height, &n, 3);
}
if (imageData)
{
texH->m_openglTextureId = m_data->m_guiHelper->registerTexture(imageData, width, height);
free(imageData);
}
else
{
b3Warning("Unsupported texture image format [%s]\n", relativeFileName);
}
}
serverCmd.m_loadTextureResultArguments.m_textureUniqueId = texHandle;
serverCmd.m_type = CMD_LOAD_TEXTURE_COMPLETED;
}
}
else
{
serverCmd.m_type = CMD_LOAD_TEXTURE_FAILED;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processSaveStateCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
BT_PROFILE("CMD_SAVE_STATE");
bool hasStatus = true;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_SAVE_STATE_FAILED;
btDefaultSerializer* ser = new btDefaultSerializer();
int currentFlags = ser->getSerializationFlags();
ser->setSerializationFlags(currentFlags | BT_SERIALIZE_CONTACT_MANIFOLDS);
m_data->m_dynamicsWorld->serialize(ser);
bParse::btBulletFile* bulletFile = new bParse::btBulletFile((char*)ser->getBufferPointer(), ser->getCurrentBufferSize());
bulletFile->parse(false);
if (bulletFile->ok())
{
serverCmd.m_type = CMD_SAVE_STATE_COMPLETED;
//re-use state if available
int reuseStateId = -1;
for (int i = 0; i < m_data->m_savedStates.size(); i++)
{
if (m_data->m_savedStates[i].m_bulletFile == 0)
{
reuseStateId = i;
break;
}
}
SaveStateData sd;
sd.m_bulletFile = bulletFile;
sd.m_serializer = ser;
if (reuseStateId >= 0)
{
serverCmd.m_saveStateResultArgs.m_stateId = reuseStateId;
m_data->m_savedStates[reuseStateId] = sd;
}
else
{
serverCmd.m_saveStateResultArgs.m_stateId = m_data->m_savedStates.size();
m_data->m_savedStates.push_back(sd);
}
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRemoveStateCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
BT_PROFILE("CMD_REMOVE_STATE");
bool hasStatus = true;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_REMOVE_STATE_FAILED;
if (clientCmd.m_loadStateArguments.m_stateId >= 0)
{
if (clientCmd.m_loadStateArguments.m_stateId < m_data->m_savedStates.size())
{
SaveStateData& sd = m_data->m_savedStates[clientCmd.m_loadStateArguments.m_stateId];
delete sd.m_bulletFile;
delete sd.m_serializer;
sd.m_bulletFile = 0;
sd.m_serializer = 0;
serverCmd.m_type = CMD_REMOVE_STATE_COMPLETED;
}
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRestoreStateCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
BT_PROFILE("CMD_RESTORE_STATE");
bool hasStatus = true;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_RESTORE_STATE_FAILED;
btMultiBodyWorldImporter* importer = new btMultiBodyWorldImporter(m_data->m_dynamicsWorld);
importer->setImporterFlags(eRESTORE_EXISTING_OBJECTS);
bool ok = false;
if (clientCmd.m_loadStateArguments.m_stateId >= 0)
{
if (clientCmd.m_loadStateArguments.m_stateId < m_data->m_savedStates.size())
{
bParse::btBulletFile* bulletFile = m_data->m_savedStates[clientCmd.m_loadStateArguments.m_stateId].m_bulletFile;
if (bulletFile)
{
ok = importer->convertAllObjects(bulletFile);
}
}
}
else
{
bool found = false;
char fileName[1024];
fileName[0] = 0;
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
b3AlignedObjectArray<char> buffer;
buffer.reserve(1024);
if (fileIO)
{
int fileId = -1;
found = fileIO->findResourcePath(clientCmd.m_fileArguments.m_fileName, fileName, 1024);
if (found)
{
fileId = fileIO->fileOpen(fileName, "rb");
}
if (fileId >= 0)
{
int size = fileIO->getFileSize(fileId);
if (size > 0)
{
buffer.resize(size);
int actual = fileIO->fileRead(fileId, &buffer[0], size);
if (actual != size)
{
b3Warning("image filesize mismatch!\n");
buffer.resize(0);
}
else
{
found = true;
}
}
fileIO->fileClose(fileId);
}
}
if (found && buffer.size())
{
ok = importer->loadFileFromMemory(&buffer[0], buffer.size());
}
else
{
b3Error("Error in restoreState: cannot load file %s\n", clientCmd.m_fileArguments.m_fileName);
}
}
delete importer;
if (ok)
{
serverCmd.m_type = CMD_RESTORE_STATE_COMPLETED;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processLoadBulletCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
BT_PROFILE("CMD_LOAD_BULLET");
bool hasStatus = true;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_BULLET_LOADING_FAILED;
//btBulletWorldImporter* importer = new btBulletWorldImporter(m_data->m_dynamicsWorld);
btMultiBodyWorldImporter* importer = new btMultiBodyWorldImporter(m_data->m_dynamicsWorld);
bool found = false;
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
b3AlignedObjectArray<char> buffer;
buffer.reserve(1024);
if (fileIO)
{
char fileName[1024];
int fileId = -1;
found = fileIO->findResourcePath(clientCmd.m_fileArguments.m_fileName, fileName, 1024);
if (found)
{
fileId = fileIO->fileOpen(fileName, "rb");
}
if (fileId >= 0)
{
int size = fileIO->getFileSize(fileId);
if (size > 0)
{
buffer.resize(size);
int actual = fileIO->fileRead(fileId, &buffer[0], size);
if (actual != size)
{
b3Warning("image filesize mismatch!\n");
buffer.resize(0);
}
else
{
found = true;
}
}
fileIO->fileClose(fileId);
}
}
if (found && buffer.size())
{
bool ok = importer->loadFileFromMemory(&buffer[0], buffer.size());
if (ok)
{
int numRb = importer->getNumRigidBodies();
serverStatusOut.m_sdfLoadedArgs.m_numBodies = 0;
serverStatusOut.m_sdfLoadedArgs.m_numUserConstraints = 0;
for (int i = 0; i < numRb; i++)
{
btCollisionObject* colObj = importer->getRigidBodyByIndex(i);
if (colObj)
{
btRigidBody* rb = btRigidBody::upcast(colObj);
if (rb)
{
int bodyUniqueId = m_data->m_bodyHandles.allocHandle();
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(bodyUniqueId);
colObj->setUserIndex2(bodyUniqueId);
bodyHandle->m_rigidBody = rb;
if (serverStatusOut.m_sdfLoadedArgs.m_numBodies < MAX_SDF_BODIES)
{
serverStatusOut.m_sdfLoadedArgs.m_numBodies++;
serverStatusOut.m_sdfLoadedArgs.m_bodyUniqueIds[i] = bodyUniqueId;
}
b3Notification notification;
notification.m_notificationType = BODY_ADDED;
notification.m_bodyArgs.m_bodyUniqueId = bodyUniqueId;
m_data->m_pluginManager.addNotification(notification);
}
}
}
serverCmd.m_type = CMD_BULLET_LOADING_COMPLETED;
m_data->m_guiHelper->autogenerateGraphicsObjects(m_data->m_dynamicsWorld);
}
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processLoadMJCFCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_LOAD_MJCF");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_MJCF_LOADING_FAILED;
const MjcfArgs& mjcfArgs = clientCmd.m_mjcfArguments;
if (m_data->m_verboseOutput)
{
b3Printf("Processed CMD_LOAD_MJCF:%s", mjcfArgs.m_mjcfFileName);
}
bool useMultiBody = (clientCmd.m_updateFlags & URDF_ARGS_USE_MULTIBODY) ? (mjcfArgs.m_useMultiBody != 0) : true;
int flags = CUF_USE_MJCF;
if (clientCmd.m_updateFlags & URDF_ARGS_HAS_CUSTOM_URDF_FLAGS)
{
flags |= clientCmd.m_mjcfArguments.m_flags;
}
bool completedOk = loadMjcf(mjcfArgs.m_mjcfFileName, bufferServerToClient, bufferSizeInBytes, useMultiBody, flags);
if (completedOk)
{
m_data->m_guiHelper->autogenerateGraphicsObjects(this->m_data->m_dynamicsWorld);
serverStatusOut.m_sdfLoadedArgs.m_numBodies = m_data->m_sdfRecentLoadedBodies.size();
serverStatusOut.m_sdfLoadedArgs.m_numUserConstraints = 0;
int maxBodies = btMin(MAX_SDF_BODIES, serverStatusOut.m_sdfLoadedArgs.m_numBodies);
for (int i = 0; i < maxBodies; i++)
{
serverStatusOut.m_sdfLoadedArgs.m_bodyUniqueIds[i] = m_data->m_sdfRecentLoadedBodies[i];
}
serverStatusOut.m_type = CMD_MJCF_LOADING_COMPLETED;
}
else
{
serverStatusOut.m_type = CMD_MJCF_LOADING_FAILED;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processSaveBulletCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_SAVE_BULLET");
SharedMemoryStatus& serverCmd = serverStatusOut;
FILE* f = fopen(clientCmd.m_fileArguments.m_fileName, "wb");
if (f)
{
btDefaultSerializer* ser = new btDefaultSerializer();
int currentFlags = ser->getSerializationFlags();
ser->setSerializationFlags(currentFlags | BT_SERIALIZE_CONTACT_MANIFOLDS);
m_data->m_dynamicsWorld->serialize(ser);
fwrite(ser->getBufferPointer(), ser->getCurrentBufferSize(), 1, f);
fclose(f);
serverCmd.m_type = CMD_BULLET_SAVING_COMPLETED;
delete ser;
return hasStatus;
}
serverCmd.m_type = CMD_BULLET_SAVING_FAILED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
// BT_PROFILE("processCommand");
int sz = sizeof(SharedMemoryStatus);
int sz2 = sizeof(SharedMemoryCommand);
bool hasStatus = false;
if (m_data->m_commandLogger)
{
m_data->m_commandLogger->logCommand(clientCmd);
}
serverStatusOut.m_type = CMD_INVALID_STATUS;
serverStatusOut.m_numDataStreamBytes = 0;
serverStatusOut.m_dataStream = 0;
//consume the command
switch (clientCmd.m_type)
{
case CMD_STATE_LOGGING:
{
hasStatus = processStateLoggingCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_SET_VR_CAMERA_STATE:
{
hasStatus = processSetVRCameraStateCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_VR_EVENTS_DATA:
{
hasStatus = processRequestVREventsCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
};
case CMD_REQUEST_MOUSE_EVENTS_DATA:
{
hasStatus = processRequestMouseEventsCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
};
case CMD_REQUEST_KEYBOARD_EVENTS_DATA:
{
hasStatus = processRequestKeyboardEventsCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
};
case CMD_REQUEST_RAY_CAST_INTERSECTIONS:
{
hasStatus = processRequestRaycastIntersectionsCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
};
case CMD_REQUEST_DEBUG_LINES:
{
hasStatus = processRequestDebugLinesCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_CAMERA_IMAGE_DATA:
{
hasStatus = processRequestCameraImageCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_SYNC_BODY_INFO:
{
hasStatus = processSyncBodyInfoCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_BODY_INFO:
{
hasStatus = processRequestBodyInfoCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_SAVE_WORLD:
{
hasStatus = processSaveWorldCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_LOAD_SDF:
{
hasStatus = processLoadSDFCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CREATE_COLLISION_SHAPE:
{
hasStatus = processCreateCollisionShapeCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CREATE_VISUAL_SHAPE:
{
hasStatus = processCreateVisualShapeCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_MESH_DATA:
{
hasStatus = processRequestMeshDataCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CREATE_MULTI_BODY:
{
hasStatus = processCreateMultiBodyCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_SET_ADDITIONAL_SEARCH_PATH:
{
hasStatus = processSetAdditionalSearchPathCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_LOAD_URDF:
{
hasStatus = processLoadURDFCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_LOAD_SOFT_BODY:
{
hasStatus = processLoadSoftBodyCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CREATE_SENSOR:
{
hasStatus = processCreateSensorCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_PROFILE_TIMING:
{
hasStatus = processProfileTimingCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_SEND_DESIRED_STATE:
{
hasStatus = processSendDesiredStateCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_COLLISION_INFO:
{
hasStatus = processRequestCollisionInfoCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_ACTUAL_STATE:
{
hasStatus = processRequestActualStateCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_STEP_FORWARD_SIMULATION:
{
hasStatus = processForwardDynamicsCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_INTERNAL_DATA:
{
hasStatus = processRequestInternalDataCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
};
case CMD_CHANGE_DYNAMICS_INFO:
{
hasStatus = processChangeDynamicsInfoCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
};
case CMD_GET_DYNAMICS_INFO:
{
hasStatus = processGetDynamicsInfoCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_PHYSICS_SIMULATION_PARAMETERS:
{
hasStatus = processRequestPhysicsSimulationParametersCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_SEND_PHYSICS_SIMULATION_PARAMETERS:
{
hasStatus = processSendPhysicsParametersCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
};
case CMD_INIT_POSE:
{
hasStatus = processInitPoseCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_RESET_SIMULATION:
{
hasStatus = processResetSimulationCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CREATE_RIGID_BODY:
{
hasStatus = processCreateRigidBodyCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CREATE_BOX_COLLISION_SHAPE:
{
//for backward compatibility, CMD_CREATE_BOX_COLLISION_SHAPE is the same as CMD_CREATE_RIGID_BODY
hasStatus = processCreateRigidBodyCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_PICK_BODY:
{
hasStatus = processPickBodyCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_MOVE_PICKED_BODY:
{
hasStatus = processMovePickedBodyCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REMOVE_PICKING_CONSTRAINT_BODY:
{
hasStatus = processRemovePickingConstraintCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_AABB_OVERLAP:
{
hasStatus = processRequestAabbOverlapCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_OPENGL_VISUALIZER_CAMERA:
{
hasStatus = processRequestOpenGLVisualizeCameraCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CONFIGURE_OPENGL_VISUALIZER:
{
hasStatus = processConfigureOpenGLVisualizerCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_CONTACT_POINT_INFORMATION:
{
hasStatus = processRequestContactpointInformationCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CALCULATE_INVERSE_DYNAMICS:
{
hasStatus = processInverseDynamicsCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CALCULATE_JACOBIAN:
{
hasStatus = processCalculateJacobianCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CALCULATE_MASS_MATRIX:
{
hasStatus = processCalculateMassMatrixCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_APPLY_EXTERNAL_FORCE:
{
hasStatus = processApplyExternalForceCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REMOVE_BODY:
{
hasStatus = processRemoveBodyCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_USER_CONSTRAINT:
{
hasStatus = processCreateUserConstraintCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CALCULATE_INVERSE_KINEMATICS:
{
if (clientCmd.m_calculateInverseKinematicsArguments.m_numEndEffectorLinkIndices == 1)
{
hasStatus = processCalculateInverseKinematicsCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
}
else
{
hasStatus = processCalculateInverseKinematicsCommand2(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
}
break;
}
case CMD_REQUEST_VISUAL_SHAPE_INFO:
{
hasStatus = processRequestVisualShapeInfoCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_COLLISION_SHAPE_INFO:
{
hasStatus = processRequestCollisionShapeInfoCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_UPDATE_VISUAL_SHAPE:
{
hasStatus = processUpdateVisualShapeCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CHANGE_TEXTURE:
{
hasStatus = processChangeTextureCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_LOAD_TEXTURE:
{
hasStatus = processLoadTextureCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_RESTORE_STATE:
{
hasStatus = processRestoreStateCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_SAVE_STATE:
{
hasStatus = processSaveStateCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REMOVE_STATE:
{
hasStatus = processRemoveStateCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_LOAD_BULLET:
{
hasStatus = processLoadBulletCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_SAVE_BULLET:
{
hasStatus = processSaveBulletCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_LOAD_MJCF:
{
hasStatus = processLoadMJCFCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_USER_DEBUG_DRAW:
{
hasStatus = processUserDebugDrawCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CUSTOM_COMMAND:
{
hasStatus = processCustomCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_SYNC_USER_DATA:
{
hasStatus = processSyncUserDataCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_USER_DATA:
{
hasStatus = processRequestUserDataCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_ADD_USER_DATA:
{
hasStatus = processAddUserDataCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REMOVE_USER_DATA:
{
hasStatus = processRemoveUserDataCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_COLLISION_FILTER:
{
hasStatus = processCollisionFilterCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
default:
{
BT_PROFILE("CMD_UNKNOWN");
b3Error("Unknown command encountered");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_UNKNOWN_COMMAND_FLUSHED;
hasStatus = true;
}
};
return hasStatus;
}
void PhysicsServerCommandProcessor::syncPhysicsToGraphics()
{
m_data->m_guiHelper->syncPhysicsToGraphics(m_data->m_dynamicsWorld);
}
void PhysicsServerCommandProcessor::syncPhysicsToGraphics2()
{
m_data->m_guiHelper->syncPhysicsToGraphics2(m_data->m_dynamicsWorld);
}
void PhysicsServerCommandProcessor::renderScene(int renderFlags)
{
if (m_data->m_guiHelper)
{
if (0 == (renderFlags & COV_DISABLE_SYNC_RENDERING))
{
m_data->m_guiHelper->syncPhysicsToGraphics(m_data->m_dynamicsWorld);
}
m_data->m_guiHelper->render(m_data->m_dynamicsWorld);
}
}
void PhysicsServerCommandProcessor::physicsDebugDraw(int debugDrawFlags)
{
if (m_data->m_dynamicsWorld)
{
if (m_data->m_dynamicsWorld->getDebugDrawer())
{
m_data->m_dynamicsWorld->getDebugDrawer()->setDebugMode(debugDrawFlags);
m_data->m_dynamicsWorld->debugDrawWorld();
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
{
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
for (int i = 0; i < deformWorld->getSoftBodyArray().size(); i++)
{
btSoftBody* psb = (btSoftBody*)deformWorld->getSoftBodyArray()[i];
if (m_data->m_dynamicsWorld->getDebugDrawer() && !(m_data->m_dynamicsWorld->getDebugDrawer()->getDebugMode() & (btIDebugDraw::DBG_DrawWireframe)))
{
//btSoftBodyHelpers::DrawFrame(psb,m_data->m_dynamicsWorld->getDebugDrawer());
btSoftBodyHelpers::Draw(psb, m_data->m_dynamicsWorld->getDebugDrawer(),deformWorld->getDrawFlags());
}
}
}
}
{
btSoftMultiBodyDynamicsWorld* softWorld = getSoftWorld();
if (softWorld)
{
for (int i = 0; i < softWorld->getSoftBodyArray().size(); i++)
{
btSoftBody* psb = (btSoftBody*)softWorld->getSoftBodyArray()[i];
if (m_data->m_dynamicsWorld->getDebugDrawer() && !(m_data->m_dynamicsWorld->getDebugDrawer()->getDebugMode() & (btIDebugDraw::DBG_DrawWireframe)))
{
//btSoftBodyHelpers::DrawFrame(psb,m_data->m_dynamicsWorld->getDebugDrawer());
btSoftBodyHelpers::Draw(psb, m_data->m_dynamicsWorld->getDebugDrawer(),softWorld->getDrawFlags());
}
}
}
}
#endif
}
}
}
struct MyResultCallback : public btCollisionWorld::ClosestRayResultCallback
{
MyResultCallback(const btVector3& rayFromWorld, const btVector3& rayToWorld)
: btCollisionWorld::ClosestRayResultCallback(rayFromWorld, rayToWorld)
{
}
virtual bool needsCollision(btBroadphaseProxy* proxy0) const
{
return true;
}
};
bool PhysicsServerCommandProcessor::pickBody(const btVector3& rayFromWorld, const btVector3& rayToWorld)
{
if (m_data->m_dynamicsWorld == 0)
return false;
//btCollisionWorld::ClosestRayResultCallback rayCallback(rayFromWorld, rayToWorld);
MyResultCallback rayCallback(rayFromWorld, rayToWorld);
rayCallback.m_flags |= btTriangleRaycastCallback::kF_UseGjkConvexCastRaytest;
m_data->m_dynamicsWorld->rayTest(rayFromWorld, rayToWorld, rayCallback);
if (rayCallback.hasHit())
{
btVector3 pickPos = rayCallback.m_hitPointWorld;
btRigidBody* body = (btRigidBody*)btRigidBody::upcast(rayCallback.m_collisionObject);
if (body)
{
//other exclusions?
if (!(body->isStaticObject() || body->isKinematicObject()))
{
m_data->m_pickedBody = body;
m_data->m_savedActivationState = body->getActivationState();
m_data->m_pickedBody->setActivationState(DISABLE_DEACTIVATION);
//printf("pickPos=%f,%f,%f\n",pickPos.getX(),pickPos.getY(),pickPos.getZ());
btVector3 localPivot = body->getCenterOfMassTransform().inverse() * pickPos;
btPoint2PointConstraint* p2p = new btPoint2PointConstraint(*body, localPivot);
m_data->m_dynamicsWorld->addConstraint(p2p, true);
m_data->m_pickedConstraint = p2p;
btScalar mousePickClamping = 30.f;
p2p->m_setting.m_impulseClamp = mousePickClamping;
//very weak constraint for picking
p2p->m_setting.m_tau = 0.001f;
}
}
else
{
btMultiBodyLinkCollider* multiCol = (btMultiBodyLinkCollider*)btMultiBodyLinkCollider::upcast(rayCallback.m_collisionObject);
if (multiCol && multiCol->m_multiBody)
{
m_data->m_prevCanSleep = multiCol->m_multiBody->getCanSleep();
multiCol->m_multiBody->setCanSleep(false);
btVector3 pivotInA = multiCol->m_multiBody->worldPosToLocal(multiCol->m_link, pickPos);
btMultiBodyPoint2Point* p2p = new btMultiBodyPoint2Point(multiCol->m_multiBody, multiCol->m_link, 0, pivotInA, pickPos);
//if you add too much energy to the system, causing high angular velocities, simulation 'explodes'
//see also http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?f=4&t=949
//so we try to avoid it by clamping the maximum impulse (force) that the mouse pick can apply
//it is not satisfying, hopefully we find a better solution (higher order integrator, using joint friction using a zero-velocity target motor with limited force etc?)
btScalar scaling = 10;
p2p->setMaxAppliedImpulse(2 * scaling);
btMultiBodyDynamicsWorld* world = (btMultiBodyDynamicsWorld*)m_data->m_dynamicsWorld;
world->addMultiBodyConstraint(p2p);
m_data->m_pickingMultiBodyPoint2Point = p2p;
}
}
// pickObject(pickPos, rayCallback.m_collisionObject);
m_data->m_oldPickingPos = rayToWorld;
m_data->m_hitPos = pickPos;
m_data->m_oldPickingDist = (pickPos - rayFromWorld).length();
// printf("hit !\n");
//add p2p
}
return false;
}
bool PhysicsServerCommandProcessor::movePickedBody(const btVector3& rayFromWorld, const btVector3& rayToWorld)
{
if (m_data->m_pickedBody && m_data->m_pickedConstraint)
{
btPoint2PointConstraint* pickCon = static_cast<btPoint2PointConstraint*>(m_data->m_pickedConstraint);
if (pickCon)
{
//keep it at the same picking distance
btVector3 dir = rayToWorld - rayFromWorld;
dir.normalize();
dir *= m_data->m_oldPickingDist;
btVector3 newPivotB = rayFromWorld + dir;
pickCon->setPivotB(newPivotB);
}
}
if (m_data->m_pickingMultiBodyPoint2Point)
{
//keep it at the same picking distance
btVector3 dir = rayToWorld - rayFromWorld;
dir.normalize();
dir *= m_data->m_oldPickingDist;
btVector3 newPivotB = rayFromWorld + dir;
m_data->m_pickingMultiBodyPoint2Point->setPivotInB(newPivotB);
}
return false;
}
void PhysicsServerCommandProcessor::removePickingConstraint()
{
if (m_data->m_pickedConstraint)
{
m_data->m_dynamicsWorld->removeConstraint(m_data->m_pickedConstraint);
delete m_data->m_pickedConstraint;
m_data->m_pickedConstraint = 0;
m_data->m_pickedBody->forceActivationState(m_data->m_savedActivationState);
m_data->m_pickedBody = 0;
}
if (m_data->m_pickingMultiBodyPoint2Point)
{
m_data->m_pickingMultiBodyPoint2Point->getMultiBodyA()->setCanSleep(m_data->m_prevCanSleep);
btMultiBodyDynamicsWorld* world = (btMultiBodyDynamicsWorld*)m_data->m_dynamicsWorld;
world->removeMultiBodyConstraint(m_data->m_pickingMultiBodyPoint2Point);
delete m_data->m_pickingMultiBodyPoint2Point;
m_data->m_pickingMultiBodyPoint2Point = 0;
}
}
void PhysicsServerCommandProcessor::enableCommandLogging(bool enable, const char* fileName)
{
if (enable)
{
if (0 == m_data->m_commandLogger)
{
m_data->m_commandLogger = new CommandLogger(fileName);
}
}
else
{
if (0 != m_data->m_commandLogger)
{
delete m_data->m_commandLogger;
m_data->m_commandLogger = 0;
}
}
}
void PhysicsServerCommandProcessor::replayFromLogFile(const char* fileName)
{
CommandLogPlayback* pb = new CommandLogPlayback(fileName);
m_data->m_logPlayback = pb;
}
int gDroppedSimulationSteps = 0;
int gNumSteps = 0;
double gDtInSec = 0.f;
double gSubStep = 0.f;
void PhysicsServerCommandProcessor::enableRealTimeSimulation(bool enableRealTimeSim)
{
m_data->m_useRealTimeSimulation = enableRealTimeSim;
}
bool PhysicsServerCommandProcessor::isRealTimeSimulationEnabled() const
{
return m_data->m_useRealTimeSimulation;
}
void PhysicsServerCommandProcessor::stepSimulationRealTime(double dtInSec, const struct b3VRControllerEvent* vrControllerEvents, int numVRControllerEvents, const struct b3KeyboardEvent* keyEvents, int numKeyEvents, const struct b3MouseEvent* mouseEvents, int numMouseEvents)
{
m_data->m_vrControllerEvents.addNewVREvents(vrControllerEvents, numVRControllerEvents);
m_data->m_pluginManager.addEvents(vrControllerEvents, numVRControllerEvents, keyEvents, numKeyEvents, mouseEvents, numMouseEvents);
for (int i = 0; i < m_data->m_stateLoggers.size(); i++)
{
if (m_data->m_stateLoggers[i]->m_loggingType == STATE_LOGGING_VR_CONTROLLERS)
{
VRControllerStateLogger* vrLogger = (VRControllerStateLogger*)m_data->m_stateLoggers[i];
vrLogger->m_vrEvents.addNewVREvents(vrControllerEvents, numVRControllerEvents);
}
}
for (int ii = 0; ii < numMouseEvents; ii++)
{
const b3MouseEvent& event = mouseEvents[ii];
bool found = false;
//search a matching one first, otherwise add new event
for (int e = 0; e < m_data->m_mouseEvents.size(); e++)
{
if (event.m_eventType == m_data->m_mouseEvents[e].m_eventType)
{
if (event.m_eventType == MOUSE_MOVE_EVENT)
{
m_data->m_mouseEvents[e].m_mousePosX = event.m_mousePosX;
m_data->m_mouseEvents[e].m_mousePosY = event.m_mousePosY;
found = true;
}
else if ((event.m_eventType == MOUSE_BUTTON_EVENT) && event.m_buttonIndex == m_data->m_mouseEvents[e].m_buttonIndex)
{
m_data->m_mouseEvents[e].m_buttonState |= event.m_buttonState;
if (event.m_buttonState & eButtonIsDown)
{
m_data->m_mouseEvents[e].m_buttonState |= eButtonIsDown;
}
else
{
m_data->m_mouseEvents[e].m_buttonState &= ~eButtonIsDown;
}
found = true;
}
}
}
if (!found)
{
m_data->m_mouseEvents.push_back(event);
}
}
for (int i = 0; i < numKeyEvents; i++)
{
const b3KeyboardEvent& event = keyEvents[i];
bool found = false;
//search a matching one first, otherwise add new event
for (int e = 0; e < m_data->m_keyboardEvents.size(); e++)
{
if (event.m_keyCode == m_data->m_keyboardEvents[e].m_keyCode)
{
m_data->m_keyboardEvents[e].m_keyState |= event.m_keyState;
if (event.m_keyState & eButtonIsDown)
{
m_data->m_keyboardEvents[e].m_keyState |= eButtonIsDown;
}
else
{
m_data->m_keyboardEvents[e].m_keyState &= ~eButtonIsDown;
}
found = true;
}
}
if (!found)
{
m_data->m_keyboardEvents.push_back(event);
}
}
if (gResetSimulation)
{
resetSimulation();
gResetSimulation = false;
}
if (gVRTrackingObjectUniqueId >= 0)
{
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(gVRTrackingObjectUniqueId);
if (bodyHandle && bodyHandle->m_multiBody)
{
// gVRTrackingObjectTr = bodyHandle->m_multiBody->getBaseWorldTransform();
if (gVRTrackingObjectUniqueId >= 0)
{
gVRTrackingObjectTr.setOrigin(bodyHandle->m_multiBody->getBaseWorldTransform().getOrigin());
gVRTeleportPos1 = gVRTrackingObjectTr.getOrigin();
}
if (gVRTrackingObjectFlag & VR_CAMERA_TRACK_OBJECT_ORIENTATION)
{
gVRTrackingObjectTr.setBasis(bodyHandle->m_multiBody->getBaseWorldTransform().getBasis());
gVRTeleportOrn = gVRTrackingObjectTr.getRotation();
}
}
}
if ((m_data->m_useRealTimeSimulation) && m_data->m_guiHelper)
{
int maxSteps = m_data->m_numSimulationSubSteps + 3;
if (m_data->m_numSimulationSubSteps)
{
gSubStep = m_data->m_physicsDeltaTime / m_data->m_numSimulationSubSteps;
}
else
{
gSubStep = m_data->m_physicsDeltaTime;
}
btScalar deltaTimeScaled = dtInSec * simTimeScalingFactor;
int numSteps = m_data->m_dynamicsWorld->stepSimulation(deltaTimeScaled, maxSteps, gSubStep);
m_data->m_simulationTimestamp += deltaTimeScaled;
gDroppedSimulationSteps += numSteps > maxSteps ? numSteps - maxSteps : 0;
if (numSteps)
{
gNumSteps = numSteps;
gDtInSec = dtInSec;
addBodyChangedNotifications();
}
}
}
b3Notification createTransformChangedNotification(int bodyUniqueId, int linkIndex, const btCollisionObject* colObj)
{
b3Notification notification;
notification.m_notificationType = TRANSFORM_CHANGED;
notification.m_transformChangeArgs.m_bodyUniqueId = bodyUniqueId;
notification.m_transformChangeArgs.m_linkIndex = linkIndex;
const btTransform& tr = colObj->getWorldTransform();
notification.m_transformChangeArgs.m_worldPosition[0] = tr.getOrigin()[0];
notification.m_transformChangeArgs.m_worldPosition[1] = tr.getOrigin()[1];
notification.m_transformChangeArgs.m_worldPosition[2] = tr.getOrigin()[2];
notification.m_transformChangeArgs.m_worldRotation[0] = tr.getRotation()[0];
notification.m_transformChangeArgs.m_worldRotation[1] = tr.getRotation()[1];
notification.m_transformChangeArgs.m_worldRotation[2] = tr.getRotation()[2];
notification.m_transformChangeArgs.m_worldRotation[3] = tr.getRotation()[3];
const btVector3& scaling = colObj->getCollisionShape()->getLocalScaling();
notification.m_transformChangeArgs.m_localScaling[0] = scaling[0];
notification.m_transformChangeArgs.m_localScaling[1] = scaling[1];
notification.m_transformChangeArgs.m_localScaling[2] = scaling[2];
return notification;
}
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
b3Notification createSoftBodyChangedNotification(int bodyUniqueId, int linkIndex)
{
b3Notification notification;
notification.m_notificationType = SOFTBODY_CHANGED;
notification.m_softBodyChangeArgs.m_bodyUniqueId = bodyUniqueId;
notification.m_softBodyChangeArgs.m_linkIndex = linkIndex;
return notification;
}
#endif
void PhysicsServerCommandProcessor::addBodyChangedNotifications()
{
b3Notification notification;
notification.m_notificationType = SIMULATION_STEPPED;
m_data->m_pluginManager.addNotification(notification);
b3AlignedObjectArray<int> usedHandles;
m_data->m_bodyHandles.getUsedHandles(usedHandles);
for (int i = 0; i < usedHandles.size(); i++)
{
int bodyUniqueId = usedHandles[i];
InternalBodyData* bodyData = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (!bodyData)
{
continue;
}
if (bodyData->m_multiBody)
{
btMultiBody* mb = bodyData->m_multiBody;
if (mb->getBaseCollider()->isActive())
{
m_data->m_pluginManager.addNotification(createTransformChangedNotification(bodyUniqueId, -1, mb->getBaseCollider()));
}
for (int linkIndex = 0; linkIndex < mb->getNumLinks(); linkIndex++)
{
if (mb->getLinkCollider(linkIndex)->isActive())
{
m_data->m_pluginManager.addNotification(createTransformChangedNotification(bodyUniqueId, linkIndex, mb->getLinkCollider(linkIndex)));
}
}
}
else if (bodyData->m_rigidBody && bodyData->m_rigidBody->isActive())
{
m_data->m_pluginManager.addNotification(createTransformChangedNotification(bodyUniqueId, -1, bodyData->m_rigidBody));
}
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
else if (bodyData->m_softBody)
{
int linkIndex = -1;
m_data->m_pluginManager.addNotification(createSoftBodyChangedNotification(bodyUniqueId, linkIndex));
}
#endif
}
}
void PhysicsServerCommandProcessor::resetSimulation(int flags)
{
//clean up all data
m_data->m_remoteSyncTransformTime = m_data->m_remoteSyncTransformInterval;
m_data->m_simulationTimestamp = 0;
m_data->m_cachedVUrdfisualShapes.clear();
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
if (m_data && m_data->m_dynamicsWorld)
{
{
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
deformWorld ->getWorldInfo().m_sparsesdf.Reset();
}
}
{
btSoftMultiBodyDynamicsWorld* softWorld = getSoftWorld();
if (softWorld)
{
softWorld->getWorldInfo().m_sparsesdf.Reset();
}
}
}
#endif
if (m_data && m_data->m_guiHelper)
{
m_data->m_guiHelper->removeAllGraphicsInstances();
m_data->m_guiHelper->removeAllUserDebugItems();
}
if (m_data)
{
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->resetAll();
}
if (m_data->m_pluginManager.getCollisionInterface())
{
m_data->m_pluginManager.getCollisionInterface()->resetAll();
}
for (int i = 0; i < m_data->m_savedStates.size(); i++)
{
delete m_data->m_savedStates[i].m_bulletFile;
delete m_data->m_savedStates[i].m_serializer;
}
m_data->m_savedStates.clear();
}
removePickingConstraint();
deleteDynamicsWorld();
createEmptyDynamicsWorld(flags);
m_data->m_bodyHandles.exitHandles();
m_data->m_bodyHandles.initHandles();
m_data->m_userCollisionShapeHandles.exitHandles();
m_data->m_userCollisionShapeHandles.initHandles();
m_data->m_userDataHandles.exitHandles();
m_data->m_userDataHandles.initHandles();
m_data->m_userDataHandleLookup.clear();
b3Notification notification;
notification.m_notificationType = SIMULATION_RESET;
m_data->m_pluginManager.addNotification(notification);
syncPhysicsToGraphics2();
}
void PhysicsServerCommandProcessor::setTimeOut(double /*timeOutInSeconds*/)
{
}
const btVector3& PhysicsServerCommandProcessor::getVRTeleportPosition() const
{
return gVRTeleportPos1;
}
void PhysicsServerCommandProcessor::setVRTeleportPosition(const btVector3& vrTeleportPos)
{
gVRTeleportPos1 = vrTeleportPos;
}
const btQuaternion& PhysicsServerCommandProcessor::getVRTeleportOrientation() const
{
return gVRTeleportOrn;
}
void PhysicsServerCommandProcessor::setVRTeleportOrientation(const btQuaternion& vrTeleportOrn)
{
gVRTeleportOrn = vrTeleportOrn;
}
|
//
// connect_pair.cpp
// ~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2016 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <iostream>
#include <string>
#include <cctype>
#include <asio.hpp>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#if defined(ASIO_HAS_LOCAL_SOCKETS)
using asio::local::stream_protocol;
class uppercase_filter
{
public:
uppercase_filter(asio::io_service& io_service)
: socket_(io_service)
{
}
stream_protocol::socket& socket()
{
return socket_;
}
void start()
{
// Wait for request.
socket_.async_read_some(asio::buffer(data_),
boost::bind(&uppercase_filter::handle_read,
this, asio::placeholders::error,
asio::placeholders::bytes_transferred));
}
private:
void handle_read(const asio::error_code& ec, std::size_t size)
{
if (!ec)
{
// Compute result.
for (std::size_t i = 0; i < size; ++i)
data_[i] = std::toupper(data_[i]);
// Send result.
asio::async_write(socket_, asio::buffer(data_, size),
boost::bind(&uppercase_filter::handle_write,
this, asio::placeholders::error));
}
else
{
throw asio::system_error(ec);
}
}
void handle_write(const asio::error_code& ec)
{
if (!ec)
{
// Wait for request.
socket_.async_read_some(asio::buffer(data_),
boost::bind(&uppercase_filter::handle_read,
this, asio::placeholders::error,
asio::placeholders::bytes_transferred));
}
else
{
throw asio::system_error(ec);
}
}
stream_protocol::socket socket_;
boost::array<char, 512> data_;
};
void run(asio::io_service* io_service)
{
try
{
io_service->run();
}
catch (std::exception& e)
{
std::cerr << "Exception in thread: " << e.what() << "\n";
std::exit(1);
}
}
int main()
{
try
{
asio::io_service io_service;
// Create filter and establish a connection to it.
uppercase_filter filter(io_service);
stream_protocol::socket socket(io_service);
asio::local::connect_pair(socket, filter.socket());
filter.start();
// The io_service runs in a background thread to perform filtering.
asio::thread thread(boost::bind(run, &io_service));
for (;;)
{
// Collect request from user.
std::cout << "Enter a string: ";
std::string request;
std::getline(std::cin, request);
// Send request to filter.
asio::write(socket, asio::buffer(request));
// Wait for reply from filter.
std::vector<char> reply(request.size());
asio::read(socket, asio::buffer(reply));
// Show reply to user.
std::cout << "Result: ";
std::cout.write(&reply[0], request.size());
std::cout << std::endl;
}
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
std::exit(1);
}
}
#else // defined(ASIO_HAS_LOCAL_SOCKETS)
# error Local sockets not available on this platform.
#endif // defined(ASIO_HAS_LOCAL_SOCKETS)
|
//*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#pragma once
#include "ngraph/node.hpp"
#include "ngraph/op/op.hpp"
namespace ngraph
{
namespace op
{
/// \brief Takes a slice of an input tensor, i.e., the sub-tensor that resides within a
/// bounding box, optionally with stride.
class NGRAPH_API DynReplaceSlice : public Op
{
public:
static constexpr NodeTypeInfo type_info{"DynReplaceSlice", 0};
const NodeTypeInfo& get_type_info() const override { return type_info; }
DynReplaceSlice() = default;
/// \brief Constructs a dynamic tensor replace-slice operation.
///
/// \param arg The tensor in which to replace the slice.
/// \param replacement Data to copy to the slice for replacement.
/// \param lower_bounds The axiswise lower bounds of the slice (inclusive).
/// \param upper_bounds The axiswise upper bounds of the slice (exclusive).
/// \param strides The slicing strides; for example, strides of `{n,m}` means to take
/// every nth row and every mth column of the input matrix.
/// \param lower_bounds_mask Ignores lower_bounds for axis with the mask set
/// \param upper_bounds_mask Ignores upper_bounds for axis with the mask set
/// \param new_axis Add dimension one axis at the set positions
/// \param shrink_axis Delete dimensions at the set positions
/// \param ellipsis_mask Inserts missing dimensions on the set position
DynReplaceSlice(const Output<Node>& arg,
const Output<Node>& replacement,
const Output<Node>& lower_bounds,
const Output<Node>& upper_bounds,
const Output<Node>& strides,
const AxisSet& lower_bounds_mask = AxisSet{},
const AxisSet& upper_bounds_mask = AxisSet{},
const AxisSet& new_axis = AxisSet{},
const AxisSet& shrink_axis = AxisSet{},
const AxisSet& ellipsis_mask = AxisSet{});
const AxisSet& get_lower_bounds_mask() const { return m_lower_bounds_mask; }
const AxisSet& get_upper_bounds_mask() const { return m_upper_bounds_mask; }
const AxisSet& get_new_axis() const { return m_new_axis; }
const AxisSet& get_shrink_axis() const { return m_shrink_axis; }
const AxisSet& get_ellipsis_mask() const { return m_ellipsis_mask; }
virtual std::shared_ptr<Node>
copy_with_new_args(const NodeVector& new_args) const override;
void validate_and_infer_types() override;
protected:
virtual void generate_adjoints(autodiff::Adjoints& adjoints,
const OutputVector& deltas) override;
private:
/// Helper method to compute output shape
Shape compute_output_shape() const;
AxisSet m_lower_bounds_mask;
AxisSet m_upper_bounds_mask;
AxisSet m_new_axis;
AxisSet m_shrink_axis;
AxisSet m_ellipsis_mask;
};
}
}
|
/* Copyright 2019 Stanford
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "optimizer.h"
#include "model.h"
Optimizer::Optimizer(const FFModel* _model)
: model(_model) {}
SGDOptimizer::SGDOptimizer(const FFModel* _model,
double _lr, double _momentum,
bool _nesterov, double _weight_decay)
: Optimizer(_model), lr(_lr), momentum(_momentum),
nesterov(_nesterov), weight_decay(_weight_decay)
{
Context ctx = model->config.lg_ctx;
Runtime* runtime = model->config.lg_hlr;
Initializer* initializer = new ZeroInitializer();
for (size_t i = 0; i < model->parameters.size(); i++) {
Tensor p = model->parameters[i].tensor;
Domain domain = runtime->get_index_space_domain(
ctx, p.region.get_index_space());
switch (domain.get_dim()) {
case 0:
{
// Do not support 0-dim parameter
assert(false);
break;
}
case 1:
case 2:
case 3:
case 4:
{
if (momentum > 0.0f) {
v_regions[p.region] = runtime->create_logical_region(
ctx, p.region.get_index_space(), p.region.get_field_space());
Tensor t;
t.region = v_regions[p.region];
initializer->init(ctx, runtime, &t);
}
break;
}
default:
{
// Unsupported dim
assert(false);
break;
}
}
}
delete initializer;
}
void SGDOptimizer::next(void)
{
}
void SGDOptimizer::update(const Parameter* p)
{
Context ctx = model->config.lg_ctx;
Runtime* runtime = model->config.lg_hlr;
TaskLauncher launcher(SGD_UPD_TASK_ID,
TaskArgument(this, sizeof(SGDOptimizer)),
Predicate::TRUE_PRED, 0/*mapper_id*/,
FFConfig::get_hash_id(std::string(p->op->name)));
// regions[0]: region_grad
launcher.add_region_requirement(
RegionRequirement(p->tensor.region_grad,
READ_ONLY, EXCLUSIVE, p->tensor.region_grad));
launcher.add_field(0, FID_DATA);
// regions[1]: region
launcher.add_region_requirement(
RegionRequirement(p->tensor.region,
READ_WRITE, EXCLUSIVE, p->tensor.region));
launcher.add_field(1, FID_DATA);
if (momentum > 0.0f) {
// regions[2]: v_region
assert(v_regions.find(p->tensor.region) != v_regions.end());
launcher.add_region_requirement(
RegionRequirement(v_regions[p->tensor.region],
READ_WRITE, EXCLUSIVE, v_regions[p->tensor.region]));
launcher.add_field(2, FID_DATA);
}
runtime->execute_task(ctx, launcher);
}
// ------------------------------------------------------------------
// Adam Optimizer
// ------------------------------------------------------------------
AdamOptimizer::AdamOptimizer(const FFModel* _model,
double _alpha, double _beta1,
double _beta2, double _weight_decay,
double _epsilon)
: Optimizer(_model), alpha(_alpha), beta1(_beta1), beta2(_beta2),
weight_decay(_weight_decay),
epsilon(_epsilon), alpha_t(_alpha), beta1_t(1.0f), beta2_t(1.0f)
{
Context ctx = model->config.lg_ctx;
Runtime* runtime = model->config.lg_hlr;
Initializer* initializer = new ZeroInitializer();
for (size_t i = 0; i < model->parameters.size(); i++) {
Tensor p = model->parameters[i].tensor;
Domain domain = runtime->get_index_space_domain(
ctx, p.region.get_index_space());
switch (domain.get_dim()) {
case 0:
{
// Do not support 0-dim parameter
assert(false);
break;
}
case 1:
case 2:
case 3:
{
v_regions[p.region] = runtime->create_logical_region(
ctx, p.region.get_index_space(), p.region.get_field_space());
m_regions[p.region] = runtime->create_logical_region(
ctx, p.region.get_index_space(), p.region.get_field_space());
Tensor t;
// Zeros v_regions and m_regions
t.region = v_regions[p.region];
initializer->init(ctx, runtime, &t);
t.region = m_regions[p.region];
initializer->init(ctx, runtime, &t);
break;
}
default:
{
// Unsupported dim
assert(false);
break;
}
}
}
delete initializer;
}
void AdamOptimizer::set_weight_decay(double _weight_decay)
{
weight_decay = _weight_decay;
}
void AdamOptimizer::next(void)
{
beta1_t *= beta1;
beta2_t *= beta2;
alpha_t = alpha * sqrt(1 - beta2_t) / (1 - beta1_t);
//fprintf(stderr, "lr = %.4lf alpha_t = %.4lf\n", alpha, alpha_t);
}
void AdamOptimizer::update(const Parameter* p)
{
Context ctx = model->config.lg_ctx;
Runtime* runtime = model->config.lg_hlr;
assert(v_regions.find(p->tensor.region) != v_regions.end());
assert(m_regions.find(p->tensor.region) != m_regions.end());
TaskLauncher launcher(ADAM_UPD_TASK_ID,
TaskArgument(this, sizeof(AdamOptimizer)),
Predicate::TRUE_PRED, 0/*mapper_id*/,
FFConfig::get_hash_id(std::string(p->op->name)));
// regions[0]: region_grad
launcher.add_region_requirement(
RegionRequirement(p->tensor.region_grad,
READ_ONLY, EXCLUSIVE, p->tensor.region_grad));
launcher.add_field(0, FID_DATA);
// regions[1]: region
launcher.add_region_requirement(
RegionRequirement(p->tensor.region,
READ_WRITE, EXCLUSIVE, p->tensor.region));
launcher.add_field(1, FID_DATA);
// regions[2]: w_region
launcher.add_region_requirement(
RegionRequirement(v_regions[p->tensor.region],
READ_WRITE, EXCLUSIVE, v_regions[p->tensor.region]));
launcher.add_field(2, FID_DATA);
// regions[3]: m_region
launcher.add_region_requirement(
RegionRequirement(m_regions[p->tensor.region],
READ_WRITE, EXCLUSIVE, m_regions[p->tensor.region]));
launcher.add_field(3, FID_DATA);
runtime->execute_task(ctx, launcher);
}
|
//--------------------------------------------*-C++-*---------------------------------------------//
/*!
* \file ds++/Release.hh
* \author Thomas Evans
* \date Thu Jul 15 09:31:44 1999
* \brief Header file for ds++ library release function.
* \note Copyright (C) 2016-2020 Triad National Security, LLC., All rights reserved. */
//------------------------------------------------------------------------------------------------//
#ifndef rtt_ds_Release_hh
#define rtt_ds_Release_hh
#include "ds++/config.h"
#include <algorithm>
#include <functional>
#include <map>
#include <string>
namespace rtt_dsxx {
// Typedefs
using mmdevs = std::multimap<int, std::string, std::greater<>>;
using fomdev = std::pair<int, std::string>;
//! Query package for the release number.
const std::string release();
//! Return a list of Draco authors
const std::string author_list(bool const use_doxygen_formatting = false);
//! Return a list of Draco authors
const std::string copyright();
//------------------------------------------------------------------------------------------------//
/*!
* \brief Format list of authors to do correct line breaks and ensures total line length is less
* than a specified maximum.
*
* \arg[in] maxlen Maximum line length
* \arg[in] line_name Category title
* \arg[in] list of developers
* \return A formatted message.
*/
std::string print_devs(size_t const maxlinelen, std::string const &line_name, mmdevs const &devs);
} // namespace rtt_dsxx
//! This version can be called by Fortran and wraps the C++ version.
extern "C" void ec_release(char *release_string, size_t maxlen);
#endif // rtt_ds_Release_hh
//------------------------------------------------------------------------------------------------//
// end of ds++/Release.hh
//------------------------------------------------------------------------------------------------//
|
/*********************************************************************
Copyright 2013 Karl Jones
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
For Further Information Please Contact me at
Karljj1@yahoo.com
http://p.sf.net/kdis/UserGuide
*********************************************************************/
#include "./COMBICState.h"
using namespace KDIS;
using namespace DATA_TYPE;
using namespace ENUMS;
//////////////////////////////////////////////////////////////////////////
// public:
//////////////////////////////////////////////////////////////////////////
COMBICState::COMBICState() :
m_ui32TSC( 0 ),
m_ui32NumSrcs( 0 ),
m_ui16GeometryIndex( 0 ),
m_ui16Padding( 0 ),
m_ui32SrcType( 0 ),
m_f32BarrageRate( 0 ),
m_f32BarrageDuration( 0 ),
m_f32BarrageCrosswindLength( 0 ),
m_f32BarrageDownwindLength( 0 ),
m_ui32Padding( 0 )
{
m_ui32EnvRecTyp = COMBICStateType;
m_ui16Length = COMBIC_STATE_SIZE * 8;
}
//////////////////////////////////////////////////////////////////////////
COMBICState::COMBICState( KDataStream & stream )
{
Decode( stream );
}
//////////////////////////////////////////////////////////////////////////
COMBICState::COMBICState( KUINT8 Index, KUINT32 TimeSinceCreation, const EntityType & MunitionSource,
KUINT32 NumberOfSources, KUINT16 GeometryIndex, KUINT32 SourceType,
KFLOAT32 BarrageRate, KFLOAT32 BarrageDuration, KFLOAT32 BarrageCrosswindLength,
KFLOAT32 BarrageDownwindLength, const EulerAngles & DetonationVelocity ) :
m_ui32TSC( TimeSinceCreation ),
m_MunSrc( MunitionSource ),
m_ui32NumSrcs( NumberOfSources ),
m_ui16GeometryIndex( GeometryIndex ),
m_ui16Padding( 0 ),
m_ui32SrcType( SourceType ),
m_f32BarrageRate( BarrageRate ),
m_f32BarrageDuration( BarrageDuration ),
m_f32BarrageCrosswindLength( BarrageCrosswindLength ),
m_f32BarrageDownwindLength( BarrageDownwindLength ),
m_DetVel( DetonationVelocity ),
m_ui32Padding( 0 )
{
m_ui8Index = Index;
m_ui32EnvRecTyp = COMBICStateType;
m_ui16Length = COMBIC_STATE_SIZE * 8;
}
//////////////////////////////////////////////////////////////////////////
COMBICState::~COMBICState()
{
}
//////////////////////////////////////////////////////////////////////////
void COMBICState::SetTimeSinceCreation( KUINT32 TSC )
{
m_ui32TSC = TSC;
}
//////////////////////////////////////////////////////////////////////////
KUINT32 COMBICState::GetTimeSinceCreation() const
{
return m_ui32TSC;
}
//////////////////////////////////////////////////////////////////////////
void COMBICState::SetMunitionSource( const EntityType & MS )
{
m_MunSrc = MS;
}
//////////////////////////////////////////////////////////////////////////
const EntityType COMBICState::GetMunitionSource() const
{
return m_MunSrc;
}
//////////////////////////////////////////////////////////////////////////
EntityType COMBICState::GetMunitionSource()
{
return m_MunSrc;
}
//////////////////////////////////////////////////////////////////////////
void COMBICState::SetNumberOfSources( KUINT32 NOS )
{
m_ui32NumSrcs = NOS;
}
//////////////////////////////////////////////////////////////////////////
KUINT32 COMBICState::GetNumberOfSources() const
{
return m_ui32NumSrcs;
}
//////////////////////////////////////////////////////////////////////////
void COMBICState::SetGeometryIndex( KUINT16 GI )
{
m_ui16GeometryIndex = GI;
}
//////////////////////////////////////////////////////////////////////////
KUINT16 COMBICState::GetGeometryIndex() const
{
return m_ui16GeometryIndex;
}
//////////////////////////////////////////////////////////////////////////
void COMBICState::SetSourceType( KUINT32 ST )
{
m_ui32SrcType = ST;
}
//////////////////////////////////////////////////////////////////////////
KUINT32 COMBICState::GetSourceType() const
{
return m_ui32SrcType;
}
//////////////////////////////////////////////////////////////////////////
void COMBICState::SetBarrageRate( KFLOAT32 BR )
{
m_f32BarrageRate = BR;
}
//////////////////////////////////////////////////////////////////////////
KFLOAT32 COMBICState::GetBarrageRate() const
{
return m_f32BarrageRate;
}
//////////////////////////////////////////////////////////////////////////
void COMBICState::SetBarrageDuration( KFLOAT32 BD )
{
m_f32BarrageDuration = BD;
}
//////////////////////////////////////////////////////////////////////////
KFLOAT32 COMBICState::GetBarrageDuration() const
{
return m_f32BarrageDuration;
}
//////////////////////////////////////////////////////////////////////////
void COMBICState::SetBarrageCrosswindLength( KFLOAT32 BCL )
{
m_f32BarrageCrosswindLength = BCL;
}
//////////////////////////////////////////////////////////////////////////
KFLOAT32 COMBICState::GetBarrageCrosswindLength() const
{
return m_f32BarrageCrosswindLength;
}
//////////////////////////////////////////////////////////////////////////
void COMBICState::SetBarrageDownwindLength( KFLOAT32 BDL )
{
m_f32BarrageDownwindLength = BDL;
}
//////////////////////////////////////////////////////////////////////////
KFLOAT32 COMBICState::GetBarrageDownwindLength() const
{
return m_f32BarrageDownwindLength;
}
//////////////////////////////////////////////////////////////////////////
void COMBICState::SetDetonationVelocity( const EulerAngles & DV )
{
m_DetVel = DV;
}
//////////////////////////////////////////////////////////////////////////
const EulerAngles & COMBICState::GetDetonationVelocity() const
{
return m_DetVel;
}
//////////////////////////////////////////////////////////////////////////
EulerAngles & COMBICState::GetDetonationVelocity()
{
return m_DetVel;
}
//////////////////////////////////////////////////////////////////////////
KString COMBICState::GetAsString() const
{
KStringStream ss;
ss << EnvironmentRecord::GetAsString()
<< "\tTime Since Creation: " << m_ui32TSC << "\n"
<< "\tMunition Source: " << m_MunSrc.GetAsString()
<< "\tNumber Of Sources: " << m_ui32NumSrcs << "\n"
<< "\tGeometry Index: " << m_ui16GeometryIndex << "\n"
<< "\tSource Type: " << m_ui32SrcType << "\n"
<< "\tBarrage Rate: " << m_f32BarrageRate << "\n"
<< "\tBarrage Duration: " << m_f32BarrageDuration << "\n"
<< "\tBarrage Crosswind Length: " << m_f32BarrageCrosswindLength << "\n"
<< "\tBarrage Downwind Length: " << m_f32BarrageDownwindLength << "\n"
<< "\tDetonation Velocity: " << m_DetVel.GetAsString();
return ss.str();
}
//////////////////////////////////////////////////////////////////////////
void COMBICState::Decode( KDataStream & stream )
{
if( stream.GetBufferSize() < COMBIC_STATE_SIZE )throw KException( __FUNCTION__, NOT_ENOUGH_DATA_IN_BUFFER );
stream >> m_ui32EnvRecTyp
>> m_ui16Length
>> m_ui8Index
>> m_ui8Padding
>> m_ui32TSC
>> KDIS_STREAM m_MunSrc
>> m_ui32NumSrcs
>> m_ui16GeometryIndex
>> m_ui16Padding
>> m_ui32SrcType
>> m_f32BarrageRate
>> m_f32BarrageDuration
>> m_f32BarrageCrosswindLength
>> m_f32BarrageDownwindLength
>> KDIS_STREAM m_DetVel
>> m_ui32Padding;
}
//////////////////////////////////////////////////////////////////////////
KDataStream COMBICState::Encode() const
{
KDataStream stream;
COMBICState::Encode( stream );
return stream;
}
//////////////////////////////////////////////////////////////////////////
void COMBICState::Encode( KDataStream & stream ) const
{
stream << m_ui32EnvRecTyp
<< m_ui16Length
<< m_ui8Index
<< m_ui8Padding
<< m_ui32TSC
<< KDIS_STREAM m_MunSrc
<< m_ui32NumSrcs
<< m_ui16GeometryIndex
<< m_ui16Padding
<< m_ui32SrcType
<< m_f32BarrageRate
<< m_f32BarrageDuration
<< m_f32BarrageCrosswindLength
<< m_f32BarrageDownwindLength
<< KDIS_STREAM m_DetVel
<< m_ui32Padding;
}
//////////////////////////////////////////////////////////////////////////
KBOOL COMBICState::operator == ( const COMBICState & Value )const
{
if( EnvironmentRecord::operator !=( Value ) ) return false;
if( m_ui32TSC != Value.m_ui32TSC ) return false;
if( m_MunSrc != Value.m_MunSrc ) return false;
if( m_ui32NumSrcs != Value.m_ui32NumSrcs ) return false;
if( m_ui16GeometryIndex != Value.m_ui16GeometryIndex ) return false;
if( m_ui32SrcType != Value.m_ui32SrcType ) return false;
if( m_f32BarrageRate != Value.m_f32BarrageRate ) return false;
if( m_f32BarrageDuration != Value.m_f32BarrageDuration ) return false;
if( m_f32BarrageCrosswindLength != Value.m_f32BarrageCrosswindLength ) return false;
if( m_f32BarrageDownwindLength != Value.m_f32BarrageDownwindLength ) return false;
if( m_DetVel != Value.m_DetVel ) return false;
return true;
}
//////////////////////////////////////////////////////////////////////////
KBOOL COMBICState::operator != ( const COMBICState & Value )const
{
return !( *this == Value );
}
//////////////////////////////////////////////////////////////////////////
|
// RouteDialog.cpp : implementation file
//
#include "stdafx.h"
#include "CartoTypeDemo.h"
#include "RouteDialog.h"
IMPLEMENT_DYNAMIC(CRouteDialog,CDialog)
CRouteDialog::CRouteDialog(bool aPushPinSelected,CWnd* pParent /*=NULL*/) :
CDialog(CRouteDialog::IDD,pParent),
iPushPinSelected(aPushPinSelected)
{
iAddress= _T("");
iPushPinName = _T("");
iPushPinDesc = _T("");
iButtonIndex = 0;
iUseAsWayPoint = 0;
iBestRoute = 0;
}
CRouteDialog::~CRouteDialog()
{
}
BOOL CRouteDialog::OnInitDialog()
{
CDialog::OnInitDialog();
if (iPushPinSelected)
{
CWnd* add_button = GetDlgItem(IDC_ADD_PUSHPIN);
add_button->SetWindowText(_T("Edit pushpin"));
}
else
{
CWnd* cut_button = GetDlgItem(IDC_CUT_PUSHPIN);
cut_button->ShowWindow(SW_HIDE);
}
ShowOrHidePushPinFields();
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CRouteDialog::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Text(pDX,IDC_ROUTE_ADDRESS,iAddress);
DDX_Text(pDX,IDC_PUSHPIN_NAME,iPushPinName);
DDX_Text(pDX,IDC_PUSHPIN_DESC,iPushPinDesc);
DDX_Radio(pDX,IDC_START_OF_ROUTE,iButtonIndex);
DDX_Check(pDX,IDC_USE_AS_WAYPOINT,iUseAsWayPoint);
DDX_Check(pDX,IDC_BEST_ROUTE,iBestRoute);
}
BEGIN_MESSAGE_MAP(CRouteDialog,CDialog)
ON_BN_CLICKED(IDC_START_OF_ROUTE,&CRouteDialog::OnRadioButtonClicked)
ON_BN_CLICKED(IDC_END_OF_ROUTE,&CRouteDialog::OnRadioButtonClicked)
ON_BN_CLICKED(IDC_ADD_PUSHPIN,&CRouteDialog::OnRadioButtonClicked)
ON_BN_CLICKED(IDC_CUT_PUSHPIN,&CRouteDialog::OnRadioButtonClicked)
END_MESSAGE_MAP()
void CRouteDialog::OnRadioButtonClicked()
{
ShowOrHidePushPinFields();
}
void CRouteDialog::ShowOrHidePushPinFields()
{
int b = GetCheckedRadioButton(IDC_START_OF_ROUTE,IDC_CUT_PUSHPIN);
bool routing = b == IDC_START_OF_ROUTE || b == IDC_END_OF_ROUTE;
GetDlgItem(IDC_PUSHPIN_NAME)->EnableWindow(routing ? false : true);
GetDlgItem(IDC_PUSHPIN_DESC)->EnableWindow(routing ? false : true);
GetDlgItem(IDC_STATIC_PUSHPIN_NAME)->EnableWindow(routing ? false : true);
GetDlgItem(IDC_STATIC_PUSHPIN_DESC)->EnableWindow(routing ? false : true);
GetDlgItem(IDC_USE_AS_WAYPOINT)->EnableWindow(routing ? false : true);
}
|
#pragma once
// PUBG FULL SDK - Generated By Respecter (5.3.4.11 [06/03/2019]) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "PUBG_Basic.hpp"
#include "PUBG_InputHookingWidget_classes.hpp"
#include "PUBG_Engine_classes.hpp"
#include "PUBG_CoreUObject_classes.hpp"
#include "PUBG_UMG_classes.hpp"
#include "PUBG_SlateCore_classes.hpp"
namespace SDK
{
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
#include <cstdio>
#include <fstream>
#include <iostream>
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include "MaeBlock.hpp"
#include "Reader.hpp"
#include "MaeConstants.hpp"
using namespace schrodinger::mae;
using std::shared_ptr;
BOOST_AUTO_TEST_SUITE(ReaderSuite)
BOOST_AUTO_TEST_CASE(Reader0)
{
auto ss = std::make_shared<std::stringstream>();
*ss << "\n"
<< "{"
"\n"
<< " s_m_m2io_version"
"\n"
<< " :::"
"\n"
<< " 1.1.0 "
"\n"
<< "}"
"\n";
Reader r(ss);
auto b = r.next("");
BOOST_REQUIRE(b);
BOOST_REQUIRE_EQUAL(b->getStringProperty(MAE_FORMAT_VERSION), "1.1.0");
}
BOOST_AUTO_TEST_CASE(NamedBlock0)
{
auto ss = std::make_shared<std::stringstream>();
*ss << "\n"
<< "\n"
<< "f_m_ct {"
"\n"
<< " s_m_prop"
"\n"
<< " :::"
"\n"
<< " 1.1.0 "
"\n"
<< "}"
"\n";
Reader r(ss);
auto b = r.next(CT_BLOCK);
BOOST_REQUIRE(b);
BOOST_REQUIRE_EQUAL(b->getStringProperty("s_m_prop"), "1.1.0");
}
BOOST_AUTO_TEST_CASE(NamedBlock1)
{
auto ss = std::make_shared<std::stringstream>();
*ss << "{"
"\n"
<< " s_m_m2io_version"
"\n"
<< " :::"
"\n"
<< " 1.1.0 "
"\n"
<< "}"
"\n"
<< "\n"
<< "f_m_ct {"
"\n"
<< " s_m_prop"
"\n"
<< " :::"
"\n"
<< " 1.1.0 "
"\n"
<< "}"
"\n";
Reader r(ss);
auto b = r.next(CT_BLOCK);
BOOST_REQUIRE(b);
BOOST_REQUIRE_EQUAL(b->getStringProperty("s_m_prop"), "1.1.0");
b = r.next(CT_BLOCK);
BOOST_REQUIRE(b == nullptr);
}
BOOST_AUTO_TEST_CASE(NestedBlock)
{
auto ss = std::make_shared<std::stringstream>();
*ss << "{"
"\n"
<< " s_m_m2io_version"
"\n"
<< " :::"
"\n"
<< " 1.1.0 "
"\n"
<< "}"
"\n"
<< "\n"
<< "f_m_ct {"
"\n"
<< " s_m_prop"
"\n"
<< " :::"
"\n"
<< " 1.1.0 "
"\n"
<< " m_nested {"
"\n"
<< " s_m_prop"
"\n"
<< " :::"
"\n"
<< " 1.1.0 "
"\n"
<< " }"
"\n"
<< "}"
"\n";
Reader r(ss);
auto b = r.next(CT_BLOCK);
BOOST_REQUIRE(b);
BOOST_REQUIRE_EQUAL(b->getStringProperty("s_m_prop"), "1.1.0");
BOOST_REQUIRE(b->hasBlock("m_nested"));
BOOST_REQUIRE_EQUAL(b->getBlock("m_nested")->getStringProperty("s_m_prop"),
"1.1.0");
}
BOOST_AUTO_TEST_CASE(NestedIndexedBlock)
{
auto ss = std::make_shared<std::stringstream>();
*ss << "{"
"\n" // 1
<< " s_m_m2io_version"
"\n" // 2
<< " :::"
"\n" // 3
<< " 1.1.0 "
"\n" // 4
<< "}"
"\n" // 5
<< "\n" // 6
<< "f_m_ct {"
"\n" // 7
<< " s_m_prop"
"\n" // 8
<< " :::"
"\n" // 9
<< " 1.1.0 "
"\n" // 10
<< " m_nested[2] {"
"\n" // 11
<< " s_m_prop"
"\n" // 12
<< " :::"
"\n" // 13
<< " 1 1.1.0 "
"\n" // 14
<< " 2 1.1.0 "
"\n" // 15
<< " :::"
"\n" // 16
<< " }"
"\n" // 17
<< " m_bond[2] {"
"\n" // 18
<< " s_m_prop"
"\n" // 19
<< " :::"
"\n" // 20
<< " 1 1.1.0 "
"\n" // 21
<< " 2 1.1.0 "
"\n" // 22
<< " :::"
"\n" // 23
<< " }"
"\n" // 24
<< " m_dependencies {"
"\n" // 25
<< " s_m_prop"
"\n" // 26
<< " :::"
"\n" // 27
<< " 1.1.0 "
"\n" // 28
<< " }"
"\n" // 29
<< "}"
"\n"; // 30
Reader r(ss);
auto b = r.next(CT_BLOCK);
BOOST_REQUIRE(b);
std::shared_ptr<IndexedBlock> ibn = b->getIndexedBlock("m_nested");
auto prop = ibn->getStringProperty("s_m_prop");
BOOST_REQUIRE_EQUAL((*prop)[0], "1.1.0");
BOOST_REQUIRE_EQUAL((*prop)[1], "1.1.0");
}
BOOST_AUTO_TEST_CASE(BufferedReader)
{
auto ss = std::make_shared<std::ifstream>("test.mae");
Reader r(ss);
size_t count = 0;
std::shared_ptr<Block> b;
while ((b = r.next(CT_BLOCK)) != nullptr) {
std::shared_ptr<IndexedBlock> iba = b->getIndexedBlock(ATOM_BLOCK);
std::shared_ptr<IndexedBlock> ibb = b->getIndexedBlock(BOND_BLOCK);
count++;
}
BOOST_REQUIRE_EQUAL(count, 3u);
}
BOOST_AUTO_TEST_CASE(BufferedFileReader)
{
FILE* f = fopen("test.mae", "r");
Reader r(f);
size_t count = 0;
std::shared_ptr<Block> b;
while ((b = r.next(CT_BLOCK)) != nullptr) {
std::shared_ptr<IndexedBlock> iba = b->getIndexedBlock(ATOM_BLOCK);
std::shared_ptr<IndexedBlock> ibb = b->getIndexedBlock(BOND_BLOCK);
count++;
}
fclose(f);
BOOST_REQUIRE_EQUAL(count, 3u);
}
BOOST_AUTO_TEST_CASE(TextReader)
{
auto ss = std::make_shared<std::ifstream>("test.mae");
Reader r(ss);
size_t count = 0;
std::shared_ptr<Block> b;
while ((b = r.next(CT_BLOCK)) != nullptr) {
count++;
}
BOOST_REQUIRE_EQUAL(count, 3u);
}
BOOST_AUTO_TEST_CASE(TextFileReader)
{
FILE* f = fopen("test.mae", "r");
Reader r(f);
size_t count = 0;
std::shared_ptr<Block> b;
while ((b = r.next(CT_BLOCK)) != nullptr) {
count++;
}
fclose(f);
BOOST_REQUIRE_EQUAL(count, 3u);
}
BOOST_AUTO_TEST_CASE(DirectReader)
{
FILE* f = fopen("test.mae", "r");
auto mae_parser = std::make_shared<DirectMaeParser>(f);
Reader r(mae_parser);
size_t count = 0;
std::shared_ptr<Block> b;
while ((b = r.next(CT_BLOCK)) != nullptr) {
std::shared_ptr<IndexedBlock> iba = b->getIndexedBlock(ATOM_BLOCK);
std::shared_ptr<IndexedBlock> ibb = b->getIndexedBlock(BOND_BLOCK);
count++;
}
fclose(f);
BOOST_REQUIRE_EQUAL(count, 3u);
}
BOOST_AUTO_TEST_CASE(QuotedStringTest)
{
FILE* f = fopen("test.mae", "r");
Reader r(f);
auto b = r.next("f_m_ct");
auto title = b->getStringProperty("s_m_title");
BOOST_REQUIRE_EQUAL(title, R"(Title with p \ " space)");
auto atom_block = b->getIndexedBlock("m_atom");
auto pdb_res = atom_block->getStringProperty("s_m_pdb_residue_name");
BOOST_REQUIRE_EQUAL(pdb_res->at(0), "UNK ");
auto atom_names = atom_block->getStringProperty("s_m_atom_name");
BOOST_REQUIRE_EQUAL(atom_names->at(0), R"(Does p " \this work)");
fclose(f);
}
BOOST_AUTO_TEST_SUITE_END()
|
#include <stdio.h>
int a[2][2][2];//w p t
int i, j, k, l;
void point(int ii, int jj, int kk, int ll){
if(ii==kk&&jj==ll){
face(2);
return;
}
if(ii==ll&&jj==kk){
printf("POINT");
return;
} else if(ii!=ll&&jj!=kk){
printf("POINT");
return;
} else {
line(2, 0, 0, 0);
return;
}
}
void line(int section, int ii, int jj, int ll){
switch(section){
case 1:
if(jj==ll){
face(3);
} else {
printf("LINE");
}
break;
case 2:
printf("LINE");
break;
}
}
void face(int section){
printf("FACE");
}
int main(){
for(i=0;i<2;i++) for(j=0;j<2;j++) for(k=0;k<2;k++){
scanf("%d", &a[i][k][j]);
}
for(i=0;i<2;i++) for(j=0;j<2;j++) for(k=0;k<2;k++) for(l=0;l<2;l++){
//printf("ff\n");
if(a[0][0][i]==a[1][0][k]&&a[0][1][j]==a[1][1][l]){
//printf("fif\n");
point(i, j, k, l);
return 0;
}
}
for(i=0;i<2;i++) for(j=0;j<2;j++) for(l=0;l<2;l++){
//printf("sf\n");
if(a[0][i][j]==a[1][i][l]){
//printf("sif\n");
if(!i){
if((a[0][1][1]<a[1][1][0]&&a[0][1][1]<a[1][1][1])||(a[0][1][0]>a[1][1][0]&&a[0][1][0]>a[1][1][1])){
continue;
}
else if((a[1][1][1]<a[0][1][0]&&a[0][1][1]<a[1][1][1])||(a[1][1][0]>a[0][1][0]&&a[0][1][0]>a[1][1][1])){
continue;
}
} else {
if((a[0][0][1]<a[1][0][0]&&a[0][0][1]<a[1][0][1])||(a[0][0][0]>a[1][0][0]&&a[0][0][0]>a[1][0][1])){
continue;
}
else if((a[1][0][1]<a[0][0][0]&&a[0][0][1]<a[1][0][1])||(a[1][0][0]>a[0][0][0]&&a[0][0][0]>a[1][0][1])){
continue;
}
}
line(1, i, j, l);
return 0;
}
}
for(j=0;j<2;j++) for(l=0;l<2;l++){
//printf("%d %d %d first\n", i, j, l);
if(a[0][0][0]<=a[1][0][j]&&a[1][0][j]<=a[0][0][1]){
//printf("%d %d %d %d %d firstif\n", i, j, a[(i+1)%2][0][j], l, &a[(i+1)%2][1][l]);
if(a[0][1][0]<=a[1][1][l]&&a[1][1][l]<=a[0][1][1]){
face(1);
return 0;
}
if(a[1][1][0]<=a[0][1][l]&&a[0][1][l]<=a[1][1][1]){
face(1);
return 0;
}
}
if(a[1][0][0]<=a[0][0][j]&&a[0][0][j]<=a[1][0][1]){
//printf("%d %d %d %d %d firstif\n", i, j, a[(i+1)%2][0][j], l, &a[(i+1)%2][1][l]);
if(a[1][1][0]<=a[0][1][l]&&a[0][1][l]<=a[1][1][1]){
face(1);
return 0;
}
if(a[0][1][0]<=a[1][1][l]&&a[1][1][l]<=a[0][1][1]){
face(1);
return 0;
}
}
}
printf("NULL");
return 0;
}
|
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(BOOST_SPIRIT_DEBUG_HANDLER_DECEMBER_05_2008_0734PM)
#define BOOST_SPIRIT_DEBUG_HANDLER_DECEMBER_05_2008_0734PM
#if defined(_MSC_VER)
#pragma once
#endif
#include <boost/spirit/home/support/unused.hpp>
#include <boost/spirit/home/qi/nonterminal/rule.hpp>
#include <boost/spirit/home/qi/nonterminal/debug_handler_state.hpp>
#include <boost/spirit/home/qi/operator/expect.hpp>
#include <boost/function.hpp>
#include <boost/fusion/include/at.hpp>
#include <boost/fusion/include/vector.hpp>
#include <boost/fusion/include/out.hpp>
#include <iostream>
namespace boost { namespace spirit { namespace qi
{
template <
typename Iterator, typename Context
, typename Skipper, typename F>
struct debug_handler
{
typedef function<
bool(Iterator& first, Iterator const& last
, Context& context
, Skipper const& skipper
)>
function_type;
debug_handler(
function_type subject_
, F f_
, std::string const& rule_name_)
: subject(subject_)
, f(f_)
, rule_name(rule_name_)
{
}
bool operator()(
Iterator& first, Iterator const& last
, Context& context, Skipper const& skipper) const
{
f(first, last, context, pre_parse, rule_name);
try // subject might throw an exception
{
if (subject(first, last, context, skipper))
{
f(first, last, context, successful_parse, rule_name);
return true;
}
f(first, last, context, failed_parse, rule_name);
}
catch (expectation_failure<Iterator> const& e)
{
f(first, last, context, failed_parse, rule_name);
boost::throw_exception(e);
}
return false;
}
function_type subject;
F f;
std::string rule_name;
};
template <typename Iterator
, typename T1, typename T2, typename T3, typename T4, typename F>
void debug(rule<Iterator, T1, T2, T3, T4>& r, F f)
{
typedef rule<Iterator, T1, T2, T3, T4> rule_type;
typedef
debug_handler<
Iterator
, typename rule_type::context_type
, typename rule_type::skipper_type
, F>
debug_handler;
r.f = debug_handler(r.f, f, r.name());
}
struct simple_trace;
namespace detail
{
// This class provides an extra level of indirection through a
// template to produce the simple_trace type. This way, the use
// of simple_trace below is hidden behind a dependent type, so
// that compilers eagerly type-checking template definitions
// won't complain that simple_trace is incomplete.
template<typename T>
struct get_simple_trace
{
typedef simple_trace type;
};
}
template <typename Iterator
, typename T1, typename T2, typename T3, typename T4>
void debug(rule<Iterator, T1, T2, T3, T4>& r)
{
typedef rule<Iterator, T1, T2, T3, T4> rule_type;
typedef
debug_handler<
Iterator
, typename rule_type::context_type
, typename rule_type::skipper_type
, simple_trace>
debug_handler;
typedef typename qi::detail::get_simple_trace<Iterator>::type trace;
r.f = debug_handler(r.f, trace(), r.name());
}
}}}
///////////////////////////////////////////////////////////////////////////////
// Utility macro for easy enabling of rule and grammar debugging
#if !defined(BOOST_SPIRIT_DEBUG_NODE)
#if defined(BOOST_SPIRIT_DEBUG) || defined(BOOST_SPIRIT_QI_DEBUG)
#define BOOST_SPIRIT_DEBUG_NODE(r) r.name(#r); debug(r)
#else
#define BOOST_SPIRIT_DEBUG_NODE(r) r.name(#r)
#endif
#endif
#define BOOST_SPIRIT_DEBUG_NODE_A(r, _, name) \
BOOST_SPIRIT_DEBUG_NODE(name); \
/***/
#define BOOST_SPIRIT_DEBUG_NODES(seq) \
BOOST_PP_SEQ_FOR_EACH(BOOST_SPIRIT_DEBUG_NODE_A, _, seq) \
/***/
#endif
|
#include <iostream>
#include <fstream>
#include "gtest/gtest.h"
#include "json_fixture.h"
#include "unittest_core.h"
int main(int argc, char **argv) {
std::cout << "Executing tests\n";
unittest_core::configuration_json["counter"] = 2;
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
//===-- llvm/MC/WinCOFFObjectWriter.cpp -------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains an implementation of a Win32 COFF object file writer.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "WinCOFFObjectWriter"
#include "llvm/MC/MCObjectWriter.h"
#include "llvm/MC/MCSection.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCValue.h"
#include "llvm/MC/MCAssembler.h"
#include "llvm/MC/MCAsmLayout.h"
#include "llvm/MC/MCSectionCOFF.h"
#include "llvm/MC/MCWinCOFFObjectWriter.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/COFF.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/TimeValue.h"
#include <cstdio>
using namespace llvm;
namespace {
typedef llvm::SmallString<COFF::NameSize> name;
enum AuxiliaryType {
ATFunctionDefinition,
ATbfAndefSymbol,
ATWeakExternal,
ATFile,
ATSectionDefinition
};
struct AuxSymbol {
AuxiliaryType AuxType;
COFF::Auxiliary Aux;
};
class COFFSymbol;
class COFFSection;
class COFFSymbol {
public:
COFF::symbol Data;
typedef llvm::SmallVector<AuxSymbol, 1> AuxiliarySymbols;
name Name;
int Index;
AuxiliarySymbols Aux;
COFFSymbol *Other;
COFFSection *Section;
int Relocations;
MCSymbolData const *MCData;
COFFSymbol(llvm::StringRef name);
size_t size() const;
void set_name_offset(uint32_t Offset);
bool should_keep() const;
};
// This class contains staging data for a COFF relocation entry.
struct COFFRelocation {
COFF::relocation Data;
COFFSymbol *Symb;
COFFRelocation() : Symb(NULL) {}
static size_t size() { return COFF::RelocationSize; }
};
typedef std::vector<COFFRelocation> relocations;
class COFFSection {
public:
COFF::section Header;
std::string Name;
int Number;
MCSectionData const *MCData;
COFFSymbol *Symbol;
relocations Relocations;
COFFSection(llvm::StringRef name);
static size_t size();
};
// This class holds the COFF string table.
class StringTable {
typedef llvm::StringMap<size_t> map;
map Map;
void update_length();
public:
std::vector<char> Data;
StringTable();
size_t size() const;
size_t insert(llvm::StringRef String);
};
class WinCOFFObjectWriter : public MCObjectWriter {
public:
typedef std::vector<COFFSymbol*> symbols;
typedef std::vector<COFFSection*> sections;
typedef DenseMap<MCSymbol const *, COFFSymbol *> symbol_map;
typedef DenseMap<MCSection const *, COFFSection *> section_map;
llvm::OwningPtr<MCWinCOFFObjectTargetWriter> TargetObjectWriter;
// Root level file contents.
COFF::header Header;
sections Sections;
symbols Symbols;
StringTable Strings;
// Maps used during object file creation.
section_map SectionMap;
symbol_map SymbolMap;
WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW, raw_ostream &OS);
~WinCOFFObjectWriter();
COFFSymbol *createSymbol(StringRef Name);
COFFSymbol *GetOrCreateCOFFSymbol(const MCSymbol * Symbol);
COFFSection *createSection(StringRef Name);
template <typename object_t, typename list_t>
object_t *createCOFFEntity(llvm::StringRef Name, list_t &List);
void DefineSection(MCSectionData const &SectionData);
void DefineSymbol(MCSymbolData const &SymbolData, MCAssembler &Assembler);
void MakeSymbolReal(COFFSymbol &S, size_t Index);
void MakeSectionReal(COFFSection &S, size_t Number);
bool ExportSection(COFFSection const *S);
bool ExportSymbol(MCSymbolData const &SymbolData, MCAssembler &Asm);
bool IsPhysicalSection(COFFSection *S);
// Entity writing methods.
void WriteFileHeader(const COFF::header &Header);
void WriteSymbol(const COFFSymbol *S);
void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S);
void WriteSectionHeader(const COFF::section &S);
void WriteRelocation(const COFF::relocation &R);
// MCObjectWriter interface implementation.
void ExecutePostLayoutBinding(MCAssembler &Asm, const MCAsmLayout &Layout);
void RecordRelocation(const MCAssembler &Asm,
const MCAsmLayout &Layout,
const MCFragment *Fragment,
const MCFixup &Fixup,
MCValue Target,
uint64_t &FixedValue);
void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
};
}
static inline void write_uint32_le(void *Data, uint32_t const &Value) {
uint8_t *Ptr = reinterpret_cast<uint8_t *>(Data);
Ptr[0] = (Value & 0x000000FF) >> 0;
Ptr[1] = (Value & 0x0000FF00) >> 8;
Ptr[2] = (Value & 0x00FF0000) >> 16;
Ptr[3] = (Value & 0xFF000000) >> 24;
}
static inline void write_uint16_le(void *Data, uint16_t const &Value) {
uint8_t *Ptr = reinterpret_cast<uint8_t *>(Data);
Ptr[0] = (Value & 0x00FF) >> 0;
Ptr[1] = (Value & 0xFF00) >> 8;
}
static inline void write_uint8_le(void *Data, uint8_t const &Value) {
uint8_t *Ptr = reinterpret_cast<uint8_t *>(Data);
Ptr[0] = (Value & 0xFF) >> 0;
}
//------------------------------------------------------------------------------
// Symbol class implementation
COFFSymbol::COFFSymbol(llvm::StringRef name)
: Name(name.begin(), name.end())
, Other(NULL)
, Section(NULL)
, Relocations(0)
, MCData(NULL) {
memset(&Data, 0, sizeof(Data));
}
size_t COFFSymbol::size() const {
return COFF::SymbolSize + (Data.NumberOfAuxSymbols * COFF::SymbolSize);
}
// In the case that the name does not fit within 8 bytes, the offset
// into the string table is stored in the last 4 bytes instead, leaving
// the first 4 bytes as 0.
void COFFSymbol::set_name_offset(uint32_t Offset) {
write_uint32_le(Data.Name + 0, 0);
write_uint32_le(Data.Name + 4, Offset);
}
/// logic to decide if the symbol should be reported in the symbol table
bool COFFSymbol::should_keep() const {
// no section means its external, keep it
if (Section == NULL)
return true;
// if it has relocations pointing at it, keep it
if (Relocations > 0) {
assert(Section->Number != -1 && "Sections with relocations must be real!");
return true;
}
// if the section its in is being droped, drop it
if (Section->Number == -1)
return false;
// if it is the section symbol, keep it
if (Section->Symbol == this)
return true;
// if its temporary, drop it
if (MCData && MCData->getSymbol().isTemporary())
return false;
// otherwise, keep it
return true;
}
//------------------------------------------------------------------------------
// Section class implementation
COFFSection::COFFSection(llvm::StringRef name)
: Name(name)
, MCData(NULL)
, Symbol(NULL) {
memset(&Header, 0, sizeof(Header));
}
size_t COFFSection::size() {
return COFF::SectionSize;
}
//------------------------------------------------------------------------------
// StringTable class implementation
/// Write the length of the string table into Data.
/// The length of the string table includes uint32 length header.
void StringTable::update_length() {
write_uint32_le(&Data.front(), Data.size());
}
StringTable::StringTable() {
// The string table data begins with the length of the entire string table
// including the length header. Allocate space for this header.
Data.resize(4);
update_length();
}
size_t StringTable::size() const {
return Data.size();
}
/// Add String to the table iff it is not already there.
/// @returns the index into the string table where the string is now located.
size_t StringTable::insert(llvm::StringRef String) {
map::iterator i = Map.find(String);
if (i != Map.end())
return i->second;
size_t Offset = Data.size();
// Insert string data into string table.
Data.insert(Data.end(), String.begin(), String.end());
Data.push_back('\0');
// Put a reference to it in the map.
Map[String] = Offset;
// Update the internal length field.
update_length();
return Offset;
}
//------------------------------------------------------------------------------
// WinCOFFObjectWriter class implementation
WinCOFFObjectWriter::WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
raw_ostream &OS)
: MCObjectWriter(OS, true)
, TargetObjectWriter(MOTW) {
memset(&Header, 0, sizeof(Header));
Header.Machine = TargetObjectWriter->getMachine();
}
WinCOFFObjectWriter::~WinCOFFObjectWriter() {
for (symbols::iterator I = Symbols.begin(), E = Symbols.end(); I != E; ++I)
delete *I;
for (sections::iterator I = Sections.begin(), E = Sections.end(); I != E; ++I)
delete *I;
}
COFFSymbol *WinCOFFObjectWriter::createSymbol(StringRef Name) {
return createCOFFEntity<COFFSymbol>(Name, Symbols);
}
COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(const MCSymbol * Symbol){
symbol_map::iterator i = SymbolMap.find(Symbol);
if (i != SymbolMap.end())
return i->second;
COFFSymbol *RetSymbol
= createCOFFEntity<COFFSymbol>(Symbol->getName(), Symbols);
SymbolMap[Symbol] = RetSymbol;
return RetSymbol;
}
COFFSection *WinCOFFObjectWriter::createSection(llvm::StringRef Name) {
return createCOFFEntity<COFFSection>(Name, Sections);
}
/// A template used to lookup or create a symbol/section, and initialize it if
/// needed.
template <typename object_t, typename list_t>
object_t *WinCOFFObjectWriter::createCOFFEntity(llvm::StringRef Name,
list_t &List) {
object_t *Object = new object_t(Name);
List.push_back(Object);
return Object;
}
/// This function takes a section data object from the assembler
/// and creates the associated COFF section staging object.
void WinCOFFObjectWriter::DefineSection(MCSectionData const &SectionData) {
assert(SectionData.getSection().getVariant() == MCSection::SV_COFF
&& "Got non COFF section in the COFF backend!");
// FIXME: Not sure how to verify this (at least in a debug build).
MCSectionCOFF const &Sec =
static_cast<MCSectionCOFF const &>(SectionData.getSection());
COFFSection *coff_section = createSection(Sec.getSectionName());
COFFSymbol *coff_symbol = createSymbol(Sec.getSectionName());
coff_section->Symbol = coff_symbol;
coff_symbol->Section = coff_section;
coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
// In this case the auxiliary symbol is a Section Definition.
coff_symbol->Aux.resize(1);
memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
coff_symbol->Aux[0].AuxType = ATSectionDefinition;
coff_symbol->Aux[0].Aux.SectionDefinition.Selection = Sec.getSelection();
coff_section->Header.Characteristics = Sec.getCharacteristics();
uint32_t &Characteristics = coff_section->Header.Characteristics;
switch (SectionData.getAlignment()) {
case 1: Characteristics |= COFF::IMAGE_SCN_ALIGN_1BYTES; break;
case 2: Characteristics |= COFF::IMAGE_SCN_ALIGN_2BYTES; break;
case 4: Characteristics |= COFF::IMAGE_SCN_ALIGN_4BYTES; break;
case 8: Characteristics |= COFF::IMAGE_SCN_ALIGN_8BYTES; break;
case 16: Characteristics |= COFF::IMAGE_SCN_ALIGN_16BYTES; break;
case 32: Characteristics |= COFF::IMAGE_SCN_ALIGN_32BYTES; break;
case 64: Characteristics |= COFF::IMAGE_SCN_ALIGN_64BYTES; break;
case 128: Characteristics |= COFF::IMAGE_SCN_ALIGN_128BYTES; break;
case 256: Characteristics |= COFF::IMAGE_SCN_ALIGN_256BYTES; break;
case 512: Characteristics |= COFF::IMAGE_SCN_ALIGN_512BYTES; break;
case 1024: Characteristics |= COFF::IMAGE_SCN_ALIGN_1024BYTES; break;
case 2048: Characteristics |= COFF::IMAGE_SCN_ALIGN_2048BYTES; break;
case 4096: Characteristics |= COFF::IMAGE_SCN_ALIGN_4096BYTES; break;
case 8192: Characteristics |= COFF::IMAGE_SCN_ALIGN_8192BYTES; break;
default:
llvm_unreachable("unsupported section alignment");
}
// Bind internal COFF section to MC section.
coff_section->MCData = &SectionData;
SectionMap[&SectionData.getSection()] = coff_section;
}
/// This function takes a section data object from the assembler
/// and creates the associated COFF symbol staging object.
void WinCOFFObjectWriter::DefineSymbol(MCSymbolData const &SymbolData,
MCAssembler &Assembler) {
COFFSymbol *coff_symbol = GetOrCreateCOFFSymbol(&SymbolData.getSymbol());
coff_symbol->Data.Type = (SymbolData.getFlags() & 0x0000FFFF) >> 0;
coff_symbol->Data.StorageClass = (SymbolData.getFlags() & 0x00FF0000) >> 16;
if (SymbolData.getFlags() & COFF::SF_WeakExternal) {
coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
if (SymbolData.getSymbol().isVariable()) {
coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
const MCExpr *Value = SymbolData.getSymbol().getVariableValue();
// FIXME: This assert message isn't very good.
assert(Value->getKind() == MCExpr::SymbolRef &&
"Value must be a SymbolRef!");
const MCSymbolRefExpr *SymbolRef =
static_cast<const MCSymbolRefExpr *>(Value);
coff_symbol->Other = GetOrCreateCOFFSymbol(&SymbolRef->getSymbol());
} else {
std::string WeakName = std::string(".weak.")
+ SymbolData.getSymbol().getName().str()
+ ".default";
COFFSymbol *WeakDefault = createSymbol(WeakName);
WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
WeakDefault->Data.StorageClass = COFF::IMAGE_SYM_CLASS_EXTERNAL;
WeakDefault->Data.Type = 0;
WeakDefault->Data.Value = 0;
coff_symbol->Other = WeakDefault;
}
// Setup the Weak External auxiliary symbol.
coff_symbol->Aux.resize(1);
memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
coff_symbol->Aux[0].AuxType = ATWeakExternal;
coff_symbol->Aux[0].Aux.WeakExternal.TagIndex = 0;
coff_symbol->Aux[0].Aux.WeakExternal.Characteristics =
COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY;
}
// If no storage class was specified in the streamer, define it here.
if (coff_symbol->Data.StorageClass == 0) {
bool external = SymbolData.isExternal() || (SymbolData.Fragment == NULL);
coff_symbol->Data.StorageClass =
external ? COFF::IMAGE_SYM_CLASS_EXTERNAL : COFF::IMAGE_SYM_CLASS_STATIC;
}
if (SymbolData.Fragment != NULL)
coff_symbol->Section =
SectionMap[&SymbolData.Fragment->getParent()->getSection()];
// Bind internal COFF symbol to MC symbol.
coff_symbol->MCData = &SymbolData;
SymbolMap[&SymbolData.getSymbol()] = coff_symbol;
}
/// making a section real involves assigned it a number and putting
/// name into the string table if needed
void WinCOFFObjectWriter::MakeSectionReal(COFFSection &S, size_t Number) {
if (S.Name.size() > COFF::NameSize) {
size_t StringTableEntry = Strings.insert(S.Name.c_str());
// FIXME: Why is this number 999999? This number is never mentioned in the
// spec. I'm assuming this is due to the printed value needing to fit into
// the S.Header.Name field. In which case why not 9999999 (7 9's instead of
// 6)? The spec does not state if this entry should be null terminated in
// this case, and thus this seems to be the best way to do it. I think I
// just solved my own FIXME...
if (StringTableEntry > 999999)
report_fatal_error("COFF string table is greater than 999999 bytes.");
std::sprintf(S.Header.Name, "/%d", unsigned(StringTableEntry));
} else
std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
S.Number = Number;
S.Symbol->Data.SectionNumber = S.Number;
S.Symbol->Aux[0].Aux.SectionDefinition.Number = S.Number;
}
void WinCOFFObjectWriter::MakeSymbolReal(COFFSymbol &S, size_t Index) {
if (S.Name.size() > COFF::NameSize) {
size_t StringTableEntry = Strings.insert(S.Name.c_str());
S.set_name_offset(StringTableEntry);
} else
std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
S.Index = Index;
}
bool WinCOFFObjectWriter::ExportSection(COFFSection const *S) {
return !S->MCData->getFragmentList().empty();
}
bool WinCOFFObjectWriter::ExportSymbol(MCSymbolData const &SymbolData,
MCAssembler &Asm) {
// This doesn't seem to be right. Strings referred to from the .data section
// need symbols so they can be linked to code in the .text section right?
// return Asm.isSymbolLinkerVisible (&SymbolData);
// For now, all non-variable symbols are exported,
// the linker will sort the rest out for us.
return SymbolData.isExternal() || !SymbolData.getSymbol().isVariable();
}
bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
return (S->Header.Characteristics
& COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0;
}
//------------------------------------------------------------------------------
// entity writing methods
void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) {
WriteLE16(Header.Machine);
WriteLE16(Header.NumberOfSections);
WriteLE32(Header.TimeDateStamp);
WriteLE32(Header.PointerToSymbolTable);
WriteLE32(Header.NumberOfSymbols);
WriteLE16(Header.SizeOfOptionalHeader);
WriteLE16(Header.Characteristics);
}
void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol *S) {
WriteBytes(StringRef(S->Data.Name, COFF::NameSize));
WriteLE32(S->Data.Value);
WriteLE16(S->Data.SectionNumber);
WriteLE16(S->Data.Type);
Write8(S->Data.StorageClass);
Write8(S->Data.NumberOfAuxSymbols);
WriteAuxiliarySymbols(S->Aux);
}
void WinCOFFObjectWriter::WriteAuxiliarySymbols(
const COFFSymbol::AuxiliarySymbols &S) {
for(COFFSymbol::AuxiliarySymbols::const_iterator i = S.begin(), e = S.end();
i != e; ++i) {
switch(i->AuxType) {
case ATFunctionDefinition:
WriteLE32(i->Aux.FunctionDefinition.TagIndex);
WriteLE32(i->Aux.FunctionDefinition.TotalSize);
WriteLE32(i->Aux.FunctionDefinition.PointerToLinenumber);
WriteLE32(i->Aux.FunctionDefinition.PointerToNextFunction);
WriteZeros(sizeof(i->Aux.FunctionDefinition.unused));
break;
case ATbfAndefSymbol:
WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused1));
WriteLE16(i->Aux.bfAndefSymbol.Linenumber);
WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused2));
WriteLE32(i->Aux.bfAndefSymbol.PointerToNextFunction);
WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused3));
break;
case ATWeakExternal:
WriteLE32(i->Aux.WeakExternal.TagIndex);
WriteLE32(i->Aux.WeakExternal.Characteristics);
WriteZeros(sizeof(i->Aux.WeakExternal.unused));
break;
case ATFile:
WriteBytes(StringRef(reinterpret_cast<const char *>(i->Aux.File.FileName),
sizeof(i->Aux.File.FileName)));
break;
case ATSectionDefinition:
WriteLE32(i->Aux.SectionDefinition.Length);
WriteLE16(i->Aux.SectionDefinition.NumberOfRelocations);
WriteLE16(i->Aux.SectionDefinition.NumberOfLinenumbers);
WriteLE32(i->Aux.SectionDefinition.CheckSum);
WriteLE16(i->Aux.SectionDefinition.Number);
Write8(i->Aux.SectionDefinition.Selection);
WriteZeros(sizeof(i->Aux.SectionDefinition.unused));
break;
}
}
}
void WinCOFFObjectWriter::WriteSectionHeader(const COFF::section &S) {
WriteBytes(StringRef(S.Name, COFF::NameSize));
WriteLE32(S.VirtualSize);
WriteLE32(S.VirtualAddress);
WriteLE32(S.SizeOfRawData);
WriteLE32(S.PointerToRawData);
WriteLE32(S.PointerToRelocations);
WriteLE32(S.PointerToLineNumbers);
WriteLE16(S.NumberOfRelocations);
WriteLE16(S.NumberOfLineNumbers);
WriteLE32(S.Characteristics);
}
void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
WriteLE32(R.VirtualAddress);
WriteLE32(R.SymbolTableIndex);
WriteLE16(R.Type);
}
////////////////////////////////////////////////////////////////////////////////
// MCObjectWriter interface implementations
void WinCOFFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
const MCAsmLayout &Layout) {
// "Define" each section & symbol. This creates section & symbol
// entries in the staging area.
for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e; i++)
DefineSection(*i);
for (MCAssembler::const_symbol_iterator i = Asm.symbol_begin(),
e = Asm.symbol_end(); i != e; i++) {
if (ExportSymbol(*i, Asm))
DefineSymbol(*i, Asm);
}
}
void WinCOFFObjectWriter::RecordRelocation(const MCAssembler &Asm,
const MCAsmLayout &Layout,
const MCFragment *Fragment,
const MCFixup &Fixup,
MCValue Target,
uint64_t &FixedValue) {
assert(Target.getSymA() != NULL && "Relocation must reference a symbol!");
const MCSymbol *A = &Target.getSymA()->getSymbol();
MCSymbolData &A_SD = Asm.getSymbolData(*A);
MCSectionData const *SectionData = Fragment->getParent();
// Mark this symbol as requiring an entry in the symbol table.
assert(SectionMap.find(&SectionData->getSection()) != SectionMap.end() &&
"Section must already have been defined in ExecutePostLayoutBinding!");
assert(SymbolMap.find(&A_SD.getSymbol()) != SymbolMap.end() &&
"Symbol must already have been defined in ExecutePostLayoutBinding!");
COFFSection *coff_section = SectionMap[&SectionData->getSection()];
COFFSymbol *coff_symbol = SymbolMap[&A_SD.getSymbol()];
const MCSymbolRefExpr *SymA = Target.getSymA();
const MCSymbolRefExpr *SymB = Target.getSymB();
const bool CrossSection = SymB &&
&SymA->getSymbol().getSection() != &SymB->getSymbol().getSection();
if (Target.getSymB()) {
const MCSymbol *B = &Target.getSymB()->getSymbol();
MCSymbolData &B_SD = Asm.getSymbolData(*B);
// Offset of the symbol in the section
int64_t a = Layout.getSymbolOffset(&B_SD);
// Ofeset of the relocation in the section
int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
FixedValue = b - a;
// In the case where we have SymbA and SymB, we just need to store the delta
// between the two symbols. Update FixedValue to account for the delta, and
// skip recording the relocation.
if (!CrossSection)
return;
} else {
FixedValue = Target.getConstant();
}
COFFRelocation Reloc;
Reloc.Data.SymbolTableIndex = 0;
Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment);
// Turn relocations for temporary symbols into section relocations.
if (coff_symbol->MCData->getSymbol().isTemporary() || CrossSection) {
Reloc.Symb = coff_symbol->Section->Symbol;
FixedValue += Layout.getFragmentOffset(coff_symbol->MCData->Fragment)
+ coff_symbol->MCData->getOffset();
} else
Reloc.Symb = coff_symbol;
++Reloc.Symb->Relocations;
Reloc.Data.VirtualAddress += Fixup.getOffset();
unsigned FixupKind = Fixup.getKind();
if (CrossSection)
FixupKind = FK_PCRel_4;
Reloc.Data.Type = TargetObjectWriter->getRelocType(FixupKind);
// FIXME: Can anyone explain what this does other than adjust for the size
// of the offset?
if (Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32 ||
Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32)
FixedValue += 4;
coff_section->Relocations.push_back(Reloc);
}
void WinCOFFObjectWriter::WriteObject(MCAssembler &Asm,
const MCAsmLayout &Layout) {
// Assign symbol and section indexes and offsets.
Header.NumberOfSections = 0;
for (sections::iterator i = Sections.begin(),
e = Sections.end(); i != e; i++) {
if (Layout.getSectionAddressSize((*i)->MCData) > 0) {
MakeSectionReal(**i, ++Header.NumberOfSections);
} else {
(*i)->Number = -1;
}
}
Header.NumberOfSymbols = 0;
for (symbols::iterator i = Symbols.begin(), e = Symbols.end(); i != e; i++) {
COFFSymbol *coff_symbol = *i;
MCSymbolData const *SymbolData = coff_symbol->MCData;
// Update section number & offset for symbols that have them.
if ((SymbolData != NULL) && (SymbolData->Fragment != NULL)) {
assert(coff_symbol->Section != NULL);
coff_symbol->Data.SectionNumber = coff_symbol->Section->Number;
coff_symbol->Data.Value = Layout.getFragmentOffset(SymbolData->Fragment)
+ SymbolData->Offset;
}
if (coff_symbol->should_keep()) {
MakeSymbolReal(*coff_symbol, Header.NumberOfSymbols++);
// Update auxiliary symbol info.
coff_symbol->Data.NumberOfAuxSymbols = coff_symbol->Aux.size();
Header.NumberOfSymbols += coff_symbol->Data.NumberOfAuxSymbols;
} else
coff_symbol->Index = -1;
}
// Fixup weak external references.
for (symbols::iterator i = Symbols.begin(), e = Symbols.end(); i != e; i++) {
COFFSymbol *coff_symbol = *i;
if (coff_symbol->Other != NULL) {
assert(coff_symbol->Index != -1);
assert(coff_symbol->Aux.size() == 1 &&
"Symbol must contain one aux symbol!");
assert(coff_symbol->Aux[0].AuxType == ATWeakExternal &&
"Symbol's aux symbol must be a Weak External!");
coff_symbol->Aux[0].Aux.WeakExternal.TagIndex = coff_symbol->Other->Index;
}
}
// Assign file offsets to COFF object file structures.
unsigned offset = 0;
offset += COFF::HeaderSize;
offset += COFF::SectionSize * Header.NumberOfSections;
for (MCAssembler::const_iterator i = Asm.begin(),
e = Asm.end();
i != e; i++) {
COFFSection *Sec = SectionMap[&i->getSection()];
if (Sec->Number == -1)
continue;
Sec->Header.SizeOfRawData = Layout.getSectionAddressSize(i);
if (IsPhysicalSection(Sec)) {
Sec->Header.PointerToRawData = offset;
offset += Sec->Header.SizeOfRawData;
}
if (Sec->Relocations.size() > 0) {
bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
if (RelocationsOverflow) {
// Signal overflow by setting NumberOfSections to max value. Actual
// size is found in reloc #0. Microsoft tools understand this.
Sec->Header.NumberOfRelocations = 0xffff;
} else {
Sec->Header.NumberOfRelocations = Sec->Relocations.size();
}
Sec->Header.PointerToRelocations = offset;
if (RelocationsOverflow) {
// Reloc #0 will contain actual count, so make room for it.
offset += COFF::RelocationSize;
}
offset += COFF::RelocationSize * Sec->Relocations.size();
for (relocations::iterator cr = Sec->Relocations.begin(),
er = Sec->Relocations.end();
cr != er; ++cr) {
assert((*cr).Symb->Index != -1);
(*cr).Data.SymbolTableIndex = (*cr).Symb->Index;
}
}
assert(Sec->Symbol->Aux.size() == 1
&& "Section's symbol must have one aux!");
AuxSymbol &Aux = Sec->Symbol->Aux[0];
assert(Aux.AuxType == ATSectionDefinition &&
"Section's symbol's aux symbol must be a Section Definition!");
Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
Aux.Aux.SectionDefinition.NumberOfRelocations =
Sec->Header.NumberOfRelocations;
Aux.Aux.SectionDefinition.NumberOfLinenumbers =
Sec->Header.NumberOfLineNumbers;
}
Header.PointerToSymbolTable = offset;
Header.TimeDateStamp = sys::TimeValue::now().toEpochTime();
// Write it all to disk...
WriteFileHeader(Header);
{
sections::iterator i, ie;
MCAssembler::const_iterator j, je;
for (i = Sections.begin(), ie = Sections.end(); i != ie; i++)
if ((*i)->Number != -1) {
if ((*i)->Relocations.size() >= 0xffff) {
(*i)->Header.Characteristics |= COFF::IMAGE_SCN_LNK_NRELOC_OVFL;
}
WriteSectionHeader((*i)->Header);
}
for (i = Sections.begin(), ie = Sections.end(),
j = Asm.begin(), je = Asm.end();
(i != ie) && (j != je); ++i, ++j) {
if ((*i)->Number == -1)
continue;
if ((*i)->Header.PointerToRawData != 0) {
assert(OS.tell() == (*i)->Header.PointerToRawData &&
"Section::PointerToRawData is insane!");
Asm.writeSectionData(j, Layout);
}
if ((*i)->Relocations.size() > 0) {
assert(OS.tell() == (*i)->Header.PointerToRelocations &&
"Section::PointerToRelocations is insane!");
if ((*i)->Relocations.size() >= 0xffff) {
// In case of overflow, write actual relocation count as first
// relocation. Including the synthetic reloc itself (+ 1).
COFF::relocation r;
r.VirtualAddress = (*i)->Relocations.size() + 1;
r.SymbolTableIndex = 0;
r.Type = 0;
WriteRelocation(r);
}
for (relocations::const_iterator k = (*i)->Relocations.begin(),
ke = (*i)->Relocations.end();
k != ke; k++) {
WriteRelocation(k->Data);
}
} else
assert((*i)->Header.PointerToRelocations == 0 &&
"Section::PointerToRelocations is insane!");
}
}
assert(OS.tell() == Header.PointerToSymbolTable &&
"Header::PointerToSymbolTable is insane!");
for (symbols::iterator i = Symbols.begin(), e = Symbols.end(); i != e; i++)
if ((*i)->Index != -1)
WriteSymbol(*i);
OS.write((char const *)&Strings.Data.front(), Strings.Data.size());
}
MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_) :
Machine(Machine_) {
}
//------------------------------------------------------------------------------
// WinCOFFObjectWriter factory function
namespace llvm {
MCObjectWriter *createWinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
raw_ostream &OS) {
return new WinCOFFObjectWriter(MOTW, OS);
}
}
|
/**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/runtime/kernel/arm/fp32/convolution_depthwise_indirect_fp32.h"
#include "include/errorcode.h"
#include "src/runtime/runtime_api.h"
using mindspore::lite::RET_ERROR;
using mindspore::lite::RET_INFER_INVALID;
using mindspore::lite::RET_OK;
namespace mindspore::kernel {
ConvolutionDepthwiseIndirectCPUKernel::~ConvolutionDepthwiseIndirectCPUKernel() {
if (packed_weight_ != nullptr) {
free(packed_weight_);
packed_weight_ = nullptr;
}
if (zero_ptr_ != nullptr) {
free(zero_ptr_);
zero_ptr_ = nullptr;
}
if (indirect_buffer_ != nullptr) {
free(indirect_buffer_);
indirect_buffer_ = nullptr;
}
}
int ConvolutionDepthwiseIndirectCPUKernel::InitWeightBias() {
// init weight: o, h, w, i; o == group, i == 1
auto weight_tensor = in_tensors_[kWeightIndex];
auto origin_weight = reinterpret_cast<float *>(weight_tensor->MutableData());
#ifdef ENABLE_AVX
int div_flag = C8NUM;
#else
int div_flag = C4NUM;
#endif
int batch_flag = UP_DIV(weight_tensor->Batch(), div_flag);
int pack_weight_size = div_flag * batch_flag * weight_tensor->Height() * weight_tensor->Width();
packed_weight_ = reinterpret_cast<float *>(malloc(pack_weight_size * sizeof(float)));
if (packed_weight_ == nullptr) {
MS_LOG(ERROR) << "Malloc buffer failed.";
return RET_ERROR;
}
#ifdef ENABLE_AVX
PackDepthwiseIndirectWeightC8Fp32(origin_weight, packed_weight_, weight_tensor->Height(), weight_tensor->Width(),
weight_tensor->Batch());
#else
PackDepthwiseIndirectWeightC4Fp32(origin_weight, packed_weight_, weight_tensor->Height(), weight_tensor->Width(),
weight_tensor->Batch());
#endif
bias_data_ = reinterpret_cast<float *>(malloc(batch_flag * div_flag * sizeof(float)));
if (bias_data_ == nullptr) {
MS_LOG(ERROR) << "Malloc buffer failed.";
return RET_ERROR;
}
if (in_tensors_.size() == kInputSize2) {
auto bias_tensor = in_tensors_[kBiasIndex];
auto ori_bias = reinterpret_cast<float *>(bias_tensor->MutableData());
memcpy(bias_data_, ori_bias, bias_tensor->ElementsNum() * sizeof(float));
} else {
memset(bias_data_, 0, batch_flag * div_flag * sizeof(float));
}
// malloc zero ptr
zero_ptr_ = reinterpret_cast<float *>(malloc(batch_flag * div_flag * sizeof(float)));
if (zero_ptr_ == nullptr) {
MS_LOG(ERROR) << "Malloc buffer failed.";
return RET_ERROR;
}
memset(zero_ptr_, 0, batch_flag * div_flag * sizeof(float));
return RET_OK;
}
int ConvolutionDepthwiseIndirectCPUKernel::Init() {
auto ret = InitWeightBias();
if (ret != 0) {
MS_LOG(ERROR) << "Convolution depthwise Indirect fp32 InitWeightBias failed.";
return RET_ERROR;
}
if (!InferShapeDone()) {
return RET_OK;
}
return ReSize();
}
int ConvolutionDepthwiseIndirectCPUKernel::MallocIndirectBuffer() {
// malloc indirect buffer
step_w = conv_param_->dilation_w_ == 1 ? conv_param_->stride_w_ : conv_param_->kernel_w_;
step_h =
(conv_param_->kernel_h_ * conv_param_->kernel_w_) + (conv_param_->output_w_ - 1) * step_w * conv_param_->kernel_h_;
int buffer_size = conv_param_->output_batch_ * conv_param_->output_h_ * step_h;
indirect_buffer_ = reinterpret_cast<float **>(malloc(buffer_size * sizeof(float *)));
if (indirect_buffer_ == nullptr) {
MS_LOG(ERROR) << "Malloc buffer failed.";
return RET_ERROR;
}
return RET_OK;
}
int ConvolutionDepthwiseIndirectCPUKernel::ReSize() {
if (indirect_buffer_ != nullptr) {
free(indirect_buffer_);
indirect_buffer_ = nullptr;
}
ConvolutionBaseCPUKernel::Init();
auto ret = MallocIndirectBuffer();
if (ret != RET_OK) {
MS_LOG(ERROR) << "ConvolutionDepthwiseIndirect MallocIndirectBuffer failed";
return RET_ERROR;
}
conv_param_->thread_num_ = MSMIN(thread_count_, conv_param_->output_h_);
return RET_OK;
}
int ConvolutionDepthwiseIndirectCPUKernel::Execute(int task_id) {
ConvDwIndirection(output_ptr_, indirect_buffer_, packed_weight_, reinterpret_cast<float *>(bias_data_), zero_ptr_,
conv_param_, task_id);
return RET_OK;
}
int ConvDwIndirectRun(void *cdata, int task_id) {
auto conv_dw = reinterpret_cast<ConvolutionDepthwiseIndirectCPUKernel *>(cdata);
auto ret = conv_dw->Execute(task_id);
if (ret != RET_OK) {
MS_LOG(ERROR) << "ConvolutionDepthwiseIndirectRun error task_id[" << task_id << "] error_code[" << ret << "]";
return RET_ERROR;
}
return RET_OK;
}
int ConvolutionDepthwiseIndirectCPUKernel::MallocPackedInput() {
#ifdef ENABLE_AVX
int div_flag = C8NUM;
#else
int div_flag = C4NUM;
#endif
int IC_DIV = UP_DIV(conv_param_->input_channel_, div_flag);
int pack_input_size = conv_param_->input_batch_ * conv_param_->input_h_ * conv_param_->input_w_ * div_flag * IC_DIV;
packed_input_ = reinterpret_cast<float *>(context_->allocator->Malloc(pack_input_size * sizeof(float)));
if (packed_input_ == nullptr) {
MS_LOG(ERROR) << "Malloc buffer failed.";
return RET_ERROR;
}
return RET_OK;
}
int ConvolutionDepthwiseIndirectCPUKernel::Run() {
auto input_tensor = in_tensors_.at(kInputIndex);
auto input_ptr = reinterpret_cast<float *>(input_tensor->data_c());
#ifdef ENABLE_AVX
int div_flag = C8NUM;
#else
int div_flag = C4NUM;
#endif
if (conv_param_->input_channel_ % div_flag != 0) {
auto ret = MallocPackedInput();
if (ret != 0) {
MS_LOG(ERROR) << "Convolution depthwise fp32 indirect buffer MallocPackedInput failed.";
return RET_ERROR;
}
#ifdef ENABLE_AVX
PackNHWCToNHWC8Fp32(input_ptr, packed_input_, conv_param_->input_batch_,
conv_param_->input_h_ * conv_param_->input_w_, conv_param_->input_channel_);
#else
PackNHWCToNHWC4Fp32(input_ptr, packed_input_, conv_param_->input_batch_,
conv_param_->input_h_ * conv_param_->input_w_, conv_param_->input_channel_);
#endif
} else {
packed_input_ = input_ptr;
}
if (IsTrain() && is_trainable()) {
PackWeight();
}
auto output_tensor = out_tensors_.at(kOutputIndex);
output_ptr_ = reinterpret_cast<float *>(output_tensor->data_c());
ConvDwInitIndirection(indirect_buffer_, packed_input_, zero_ptr_, conv_param_, step_h, step_w);
auto ret = static_cast<const lite::InnerContext *>(this->context_)
->thread_pool_->ParallelLaunch(ConvDwIndirectRun, this, conv_param_->thread_num_);
if (ret != RET_OK) {
MS_LOG(ERROR) << "ConvDwIndirectRun error: error_code[" << ret << "]";
return RET_ERROR;
}
if (conv_param_->input_channel_ % div_flag != 0) {
context_->allocator->Free(packed_input_);
}
return RET_OK;
}
void ConvolutionDepthwiseIndirectCPUKernel::PackWeight() {
auto weight_tensor = in_tensors_[kWeightIndex];
auto origin_weight = reinterpret_cast<float *>(weight_tensor->MutableData());
#ifdef ENABLE_AVX
PackDepthwiseIndirectWeightC8Fp32(origin_weight, packed_weight_, weight_tensor->Height(), weight_tensor->Width(),
weight_tensor->Batch());
#else
PackDepthwiseIndirectWeightC4Fp32(origin_weight, packed_weight_, weight_tensor->Height(), weight_tensor->Width(),
weight_tensor->Batch());
#endif
}
int ConvolutionDepthwiseIndirectCPUKernel::Eval() {
InnerKernel::Eval();
if (is_trainable()) {
PackWeight();
}
return RET_OK;
}
} // namespace mindspore::kernel
|
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkUtils.h"
/* 0xxxxxxx 1 total
10xxxxxx // never a leading byte
110xxxxx 2 total
1110xxxx 3 total
11110xxx 4 total
11 10 01 01 xx xx xx xx 0...
0xE5XX0000
0xE5 << 24
*/
#ifdef SK_DEBUG
static void assert_utf8_leadingbyte(unsigned c) {
SkASSERT(c <= 0xF7); // otherwise leading byte is too big (more than 4 bytes)
SkASSERT((c & 0xC0) != 0x80); // can't begin with a middle char
}
int SkUTF8_LeadByteToCount(unsigned c) {
assert_utf8_leadingbyte(c);
return (((0xE5 << 24) >> (c >> 4 << 1)) & 3) + 1;
}
#else
#define assert_utf8_leadingbyte(c)
#endif
int SkUTF8_CountUnichars(const char utf8[]) {
SkASSERT(utf8);
int count = 0;
for (;;) {
int c = *(const uint8_t*)utf8;
if (c == 0) {
break;
}
utf8 += SkUTF8_LeadByteToCount(c);
count += 1;
}
return count;
}
int SkUTF8_CountUnichars(const char utf8[], size_t byteLength) {
SkASSERT(utf8 || 0 == byteLength);
int count = 0;
const char* stop = utf8 + byteLength;
while (utf8 < stop) {
utf8 += SkUTF8_LeadByteToCount(*(const uint8_t*)utf8);
count += 1;
}
return count;
}
SkUnichar SkUTF8_ToUnichar(const char utf8[]) {
SkASSERT(utf8);
const uint8_t* p = (const uint8_t*)utf8;
int c = *p;
int hic = c << 24;
assert_utf8_leadingbyte(c);
if (hic < 0) {
uint32_t mask = (uint32_t)~0x3F;
hic = SkLeftShift(hic, 1);
do {
c = (c << 6) | (*++p & 0x3F);
mask <<= 5;
} while ((hic = SkLeftShift(hic, 1)) < 0);
c &= ~mask;
}
return c;
}
SkUnichar SkUTF8_NextUnichar(const char** ptr) {
SkASSERT(ptr && *ptr);
const uint8_t* p = (const uint8_t*)*ptr;
int c = *p;
int hic = c << 24;
assert_utf8_leadingbyte(c);
if (hic < 0) {
uint32_t mask = (uint32_t)~0x3F;
hic = SkLeftShift(hic, 1);
do {
c = (c << 6) | (*++p & 0x3F);
mask <<= 5;
} while ((hic = SkLeftShift(hic, 1)) < 0);
c &= ~mask;
}
*ptr = (char*)p + 1;
return c;
}
SkUnichar SkUTF8_PrevUnichar(const char** ptr) {
SkASSERT(ptr && *ptr);
const char* p = *ptr;
if (*--p & 0x80) {
while (*--p & 0x40) {
;
}
}
*ptr = (char*)p;
return SkUTF8_NextUnichar(&p);
}
size_t SkUTF8_FromUnichar(SkUnichar uni, char utf8[]) {
if ((uint32_t)uni > 0x10FFFF) {
SkDEBUGFAIL("bad unichar");
return 0;
}
if (uni <= 127) {
if (utf8) {
*utf8 = (char)uni;
}
return 1;
}
char tmp[4];
char* p = tmp;
size_t count = 1;
SkDEBUGCODE(SkUnichar orig = uni;)
while (uni > 0x7F >> count) {
*p++ = (char)(0x80 | (uni & 0x3F));
uni >>= 6;
count += 1;
}
if (utf8) {
p = tmp;
utf8 += count;
while (p < tmp + count - 1) {
*--utf8 = *p++;
}
*--utf8 = (char)(~(0xFF >> count) | uni);
}
SkASSERT(utf8 == nullptr || orig == SkUTF8_ToUnichar(utf8));
return count;
}
///////////////////////////////////////////////////////////////////////////////
int SkUTF16_CountUnichars(const uint16_t src[]) {
SkASSERT(src);
int count = 0;
unsigned c;
while ((c = *src++) != 0) {
SkASSERT(!SkUTF16_IsLowSurrogate(c));
if (SkUTF16_IsHighSurrogate(c)) {
c = *src++;
SkASSERT(SkUTF16_IsLowSurrogate(c));
}
count += 1;
}
return count;
}
int SkUTF16_CountUnichars(const uint16_t src[], int numberOf16BitValues) {
SkASSERT(src);
const uint16_t* stop = src + numberOf16BitValues;
int count = 0;
while (src < stop) {
unsigned c = *src++;
SkASSERT(!SkUTF16_IsLowSurrogate(c));
if (SkUTF16_IsHighSurrogate(c)) {
SkASSERT(src < stop);
c = *src++;
SkASSERT(SkUTF16_IsLowSurrogate(c));
}
count += 1;
}
return count;
}
SkUnichar SkUTF16_NextUnichar(const uint16_t** srcPtr) {
SkASSERT(srcPtr && *srcPtr);
const uint16_t* src = *srcPtr;
SkUnichar c = *src++;
SkASSERT(!SkUTF16_IsLowSurrogate(c));
if (SkUTF16_IsHighSurrogate(c)) {
unsigned c2 = *src++;
SkASSERT(SkUTF16_IsLowSurrogate(c2));
// c = ((c & 0x3FF) << 10) + (c2 & 0x3FF) + 0x10000
// c = (((c & 0x3FF) + 64) << 10) + (c2 & 0x3FF)
c = (c << 10) + c2 + (0x10000 - (0xD800 << 10) - 0xDC00);
}
*srcPtr = src;
return c;
}
SkUnichar SkUTF16_PrevUnichar(const uint16_t** srcPtr) {
SkASSERT(srcPtr && *srcPtr);
const uint16_t* src = *srcPtr;
SkUnichar c = *--src;
SkASSERT(!SkUTF16_IsHighSurrogate(c));
if (SkUTF16_IsLowSurrogate(c)) {
unsigned c2 = *--src;
SkASSERT(SkUTF16_IsHighSurrogate(c2));
c = (c2 << 10) + c + (0x10000 - (0xD800 << 10) - 0xDC00);
}
*srcPtr = src;
return c;
}
size_t SkUTF16_FromUnichar(SkUnichar uni, uint16_t dst[]) {
SkASSERT((unsigned)uni <= 0x10FFFF);
int extra = (uni > 0xFFFF);
if (dst) {
if (extra) {
// dst[0] = SkToU16(0xD800 | ((uni - 0x10000) >> 10));
// dst[0] = SkToU16(0xD800 | ((uni >> 10) - 64));
dst[0] = SkToU16((0xD800 - 64) + (uni >> 10));
dst[1] = SkToU16(0xDC00 | (uni & 0x3FF));
SkASSERT(SkUTF16_IsHighSurrogate(dst[0]));
SkASSERT(SkUTF16_IsLowSurrogate(dst[1]));
} else {
dst[0] = SkToU16(uni);
SkASSERT(!SkUTF16_IsHighSurrogate(dst[0]));
SkASSERT(!SkUTF16_IsLowSurrogate(dst[0]));
}
}
return 1 + extra;
}
size_t SkUTF16_ToUTF8(const uint16_t utf16[], int numberOf16BitValues,
char utf8[]) {
SkASSERT(numberOf16BitValues >= 0);
if (numberOf16BitValues <= 0) {
return 0;
}
SkASSERT(utf16 != nullptr);
const uint16_t* stop = utf16 + numberOf16BitValues;
size_t size = 0;
if (utf8 == nullptr) { // just count
while (utf16 < stop) {
size += SkUTF8_FromUnichar(SkUTF16_NextUnichar(&utf16), nullptr);
}
} else {
char* start = utf8;
while (utf16 < stop) {
utf8 += SkUTF8_FromUnichar(SkUTF16_NextUnichar(&utf16), utf8);
}
size = utf8 - start;
}
return size;
}
|
#include "src/logger/deduplicator.h"
#include <gtest/gtest.h>
namespace pos_logger
{
TEST(Deduplicator, IsEnabled_)
{
}
TEST(Deduplicator, Enable_)
{
}
TEST(Deduplicator, Disable_)
{
}
TEST(Deduplicator, Sensitivity_)
{
}
TEST(Deduplicator, UpdateSensitivity_)
{
}
TEST(Deduplicator, IsDuplicated_)
{
}
TEST(Deduplicator, _CheckDuplication_)
{
}
} // namespace pos_logger
|
/**
* @file Box_Comp_Test.cpp
* @brief Box class tester.
* @author zer0
* @date 2020-01-07
*/
#include <gtest/gtest.h>
#include <libtbag/box/Box.hpp>
using namespace libtbag;
using namespace libtbag::box;
struct Box_Comp_Test_Fixture : public testing::Test
{
Box src;
Box cmp;
void SetUp() override
{
src = { { 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 } };
cmp = { { 25, 24, 23, 22, 21 },
{ 20, 19, 18, 17, 16 },
{ 15, 14, 13, 12, 11 },
{ 10, 9, 8, 7, 6 },
{ 5, 4, 3, 2, 1 } };
}
void TearDown() override
{
src = nullptr;
cmp = nullptr;
}
};
TEST_F(Box_Comp_Test_Fixture, EqualTo)
{
auto const err_result = src.eq(cmp);
ASSERT_EQ(E_SUCCESS, err_result);
auto const & result = err_result.val;
ASSERT_TRUE(result.is_bool());
ASSERT_TRUE(result.is_device_cpu());
ASSERT_EQ(0, result.ext0());
ASSERT_EQ(0, result.ext1());
ASSERT_EQ(0, result.ext2());
ASSERT_EQ(0, result.ext3());
ASSERT_EQ(2, result.rank());
ASSERT_EQ(5, result.dim(0));
ASSERT_EQ(5, result.dim(1));
ASSERT_EQ(25, result.size());
ASSERT_FALSE(result.at<bool>(0));
ASSERT_FALSE(result.at<bool>(1));
ASSERT_FALSE(result.at<bool>(2));
ASSERT_FALSE(result.at<bool>(3));
ASSERT_FALSE(result.at<bool>(4));
ASSERT_FALSE(result.at<bool>(5));
ASSERT_FALSE(result.at<bool>(6));
ASSERT_FALSE(result.at<bool>(7));
ASSERT_FALSE(result.at<bool>(8));
ASSERT_FALSE(result.at<bool>(9));
ASSERT_FALSE(result.at<bool>(10));
ASSERT_FALSE(result.at<bool>(11));
ASSERT_TRUE(result.at<bool>(12));
ASSERT_FALSE(result.at<bool>(13));
ASSERT_FALSE(result.at<bool>(14));
ASSERT_FALSE(result.at<bool>(15));
ASSERT_FALSE(result.at<bool>(16));
ASSERT_FALSE(result.at<bool>(17));
ASSERT_FALSE(result.at<bool>(18));
ASSERT_FALSE(result.at<bool>(19));
ASSERT_FALSE(result.at<bool>(20));
ASSERT_FALSE(result.at<bool>(21));
ASSERT_FALSE(result.at<bool>(22));
ASSERT_FALSE(result.at<bool>(23));
ASSERT_FALSE(result.at<bool>(24));
}
TEST_F(Box_Comp_Test_Fixture, NotEqual)
{
auto const err_result = src.ne(cmp);
ASSERT_EQ(E_SUCCESS, err_result);
auto const & result = err_result.val;
ASSERT_TRUE(result.is_bool());
ASSERT_TRUE(result.is_device_cpu());
ASSERT_EQ(0, result.ext0());
ASSERT_EQ(0, result.ext1());
ASSERT_EQ(0, result.ext2());
ASSERT_EQ(0, result.ext3());
ASSERT_EQ(2, result.rank());
ASSERT_EQ(5, result.dim(0));
ASSERT_EQ(5, result.dim(1));
ASSERT_EQ(25, result.size());
ASSERT_TRUE(result.at<bool>(0));
ASSERT_TRUE(result.at<bool>(1));
ASSERT_TRUE(result.at<bool>(2));
ASSERT_TRUE(result.at<bool>(3));
ASSERT_TRUE(result.at<bool>(4));
ASSERT_TRUE(result.at<bool>(5));
ASSERT_TRUE(result.at<bool>(6));
ASSERT_TRUE(result.at<bool>(7));
ASSERT_TRUE(result.at<bool>(8));
ASSERT_TRUE(result.at<bool>(9));
ASSERT_TRUE(result.at<bool>(10));
ASSERT_TRUE(result.at<bool>(11));
ASSERT_FALSE(result.at<bool>(12));
ASSERT_TRUE(result.at<bool>(13));
ASSERT_TRUE(result.at<bool>(14));
ASSERT_TRUE(result.at<bool>(15));
ASSERT_TRUE(result.at<bool>(16));
ASSERT_TRUE(result.at<bool>(17));
ASSERT_TRUE(result.at<bool>(18));
ASSERT_TRUE(result.at<bool>(19));
ASSERT_TRUE(result.at<bool>(20));
ASSERT_TRUE(result.at<bool>(21));
ASSERT_TRUE(result.at<bool>(22));
ASSERT_TRUE(result.at<bool>(23));
ASSERT_TRUE(result.at<bool>(24));
}
TEST_F(Box_Comp_Test_Fixture, LessThan)
{
auto const err_result = src.lt(cmp);
ASSERT_EQ(E_SUCCESS, err_result);
auto const & result = err_result.val;
ASSERT_TRUE(result.is_bool());
ASSERT_TRUE(result.is_device_cpu());
ASSERT_EQ(0, result.ext0());
ASSERT_EQ(0, result.ext1());
ASSERT_EQ(0, result.ext2());
ASSERT_EQ(0, result.ext3());
ASSERT_EQ(2, result.rank());
ASSERT_EQ(5, result.dim(0));
ASSERT_EQ(5, result.dim(1));
ASSERT_EQ(25, result.size());
ASSERT_TRUE(result.at<bool>(0));
ASSERT_TRUE(result.at<bool>(1));
ASSERT_TRUE(result.at<bool>(2));
ASSERT_TRUE(result.at<bool>(3));
ASSERT_TRUE(result.at<bool>(4));
ASSERT_TRUE(result.at<bool>(5));
ASSERT_TRUE(result.at<bool>(6));
ASSERT_TRUE(result.at<bool>(7));
ASSERT_TRUE(result.at<bool>(8));
ASSERT_TRUE(result.at<bool>(9));
ASSERT_TRUE(result.at<bool>(10));
ASSERT_TRUE(result.at<bool>(11));
ASSERT_FALSE(result.at<bool>(12));
ASSERT_FALSE(result.at<bool>(13));
ASSERT_FALSE(result.at<bool>(14));
ASSERT_FALSE(result.at<bool>(15));
ASSERT_FALSE(result.at<bool>(16));
ASSERT_FALSE(result.at<bool>(17));
ASSERT_FALSE(result.at<bool>(18));
ASSERT_FALSE(result.at<bool>(19));
ASSERT_FALSE(result.at<bool>(20));
ASSERT_FALSE(result.at<bool>(21));
ASSERT_FALSE(result.at<bool>(22));
ASSERT_FALSE(result.at<bool>(23));
ASSERT_FALSE(result.at<bool>(24));
}
TEST_F(Box_Comp_Test_Fixture, LessEqual)
{
auto const err_result = src.le(cmp);
ASSERT_EQ(E_SUCCESS, err_result);
auto const & result = err_result.val;
ASSERT_TRUE(result.is_bool());
ASSERT_TRUE(result.is_device_cpu());
ASSERT_EQ(0, result.ext0());
ASSERT_EQ(0, result.ext1());
ASSERT_EQ(0, result.ext2());
ASSERT_EQ(0, result.ext3());
ASSERT_EQ(2, result.rank());
ASSERT_EQ(5, result.dim(0));
ASSERT_EQ(5, result.dim(1));
ASSERT_EQ(25, result.size());
ASSERT_TRUE(result.at<bool>(0));
ASSERT_TRUE(result.at<bool>(1));
ASSERT_TRUE(result.at<bool>(2));
ASSERT_TRUE(result.at<bool>(3));
ASSERT_TRUE(result.at<bool>(4));
ASSERT_TRUE(result.at<bool>(5));
ASSERT_TRUE(result.at<bool>(6));
ASSERT_TRUE(result.at<bool>(7));
ASSERT_TRUE(result.at<bool>(8));
ASSERT_TRUE(result.at<bool>(9));
ASSERT_TRUE(result.at<bool>(10));
ASSERT_TRUE(result.at<bool>(11));
ASSERT_TRUE(result.at<bool>(12));
ASSERT_FALSE(result.at<bool>(13));
ASSERT_FALSE(result.at<bool>(14));
ASSERT_FALSE(result.at<bool>(15));
ASSERT_FALSE(result.at<bool>(16));
ASSERT_FALSE(result.at<bool>(17));
ASSERT_FALSE(result.at<bool>(18));
ASSERT_FALSE(result.at<bool>(19));
ASSERT_FALSE(result.at<bool>(20));
ASSERT_FALSE(result.at<bool>(21));
ASSERT_FALSE(result.at<bool>(22));
ASSERT_FALSE(result.at<bool>(23));
ASSERT_FALSE(result.at<bool>(24));
}
TEST_F(Box_Comp_Test_Fixture, GreaterThan)
{
auto const err_result = src.gt(cmp);
ASSERT_EQ(E_SUCCESS, err_result);
auto const & result = err_result.val;
ASSERT_TRUE(result.is_bool());
ASSERT_TRUE(result.is_device_cpu());
ASSERT_EQ(0, result.ext0());
ASSERT_EQ(0, result.ext1());
ASSERT_EQ(0, result.ext2());
ASSERT_EQ(0, result.ext3());
ASSERT_EQ(2, result.rank());
ASSERT_EQ(5, result.dim(0));
ASSERT_EQ(5, result.dim(1));
ASSERT_EQ(25, result.size());
ASSERT_FALSE(result.at<bool>(0));
ASSERT_FALSE(result.at<bool>(1));
ASSERT_FALSE(result.at<bool>(2));
ASSERT_FALSE(result.at<bool>(3));
ASSERT_FALSE(result.at<bool>(4));
ASSERT_FALSE(result.at<bool>(5));
ASSERT_FALSE(result.at<bool>(6));
ASSERT_FALSE(result.at<bool>(7));
ASSERT_FALSE(result.at<bool>(8));
ASSERT_FALSE(result.at<bool>(9));
ASSERT_FALSE(result.at<bool>(10));
ASSERT_FALSE(result.at<bool>(11));
ASSERT_FALSE(result.at<bool>(12));
ASSERT_TRUE(result.at<bool>(13));
ASSERT_TRUE(result.at<bool>(14));
ASSERT_TRUE(result.at<bool>(15));
ASSERT_TRUE(result.at<bool>(16));
ASSERT_TRUE(result.at<bool>(17));
ASSERT_TRUE(result.at<bool>(18));
ASSERT_TRUE(result.at<bool>(19));
ASSERT_TRUE(result.at<bool>(20));
ASSERT_TRUE(result.at<bool>(21));
ASSERT_TRUE(result.at<bool>(22));
ASSERT_TRUE(result.at<bool>(23));
ASSERT_TRUE(result.at<bool>(24));
}
TEST_F(Box_Comp_Test_Fixture, GreaterEqual)
{
auto const err_result = src.ge(cmp);
ASSERT_EQ(E_SUCCESS, err_result);
auto const & result = err_result.val;
ASSERT_TRUE(result.is_bool());
ASSERT_TRUE(result.is_device_cpu());
ASSERT_EQ(0, result.ext0());
ASSERT_EQ(0, result.ext1());
ASSERT_EQ(0, result.ext2());
ASSERT_EQ(0, result.ext3());
ASSERT_EQ(2, result.rank());
ASSERT_EQ(5, result.dim(0));
ASSERT_EQ(5, result.dim(1));
ASSERT_EQ(25, result.size());
ASSERT_FALSE(result.at<bool>(0));
ASSERT_FALSE(result.at<bool>(1));
ASSERT_FALSE(result.at<bool>(2));
ASSERT_FALSE(result.at<bool>(3));
ASSERT_FALSE(result.at<bool>(4));
ASSERT_FALSE(result.at<bool>(5));
ASSERT_FALSE(result.at<bool>(6));
ASSERT_FALSE(result.at<bool>(7));
ASSERT_FALSE(result.at<bool>(8));
ASSERT_FALSE(result.at<bool>(9));
ASSERT_FALSE(result.at<bool>(10));
ASSERT_FALSE(result.at<bool>(11));
ASSERT_TRUE(result.at<bool>(12));
ASSERT_TRUE(result.at<bool>(13));
ASSERT_TRUE(result.at<bool>(14));
ASSERT_TRUE(result.at<bool>(15));
ASSERT_TRUE(result.at<bool>(16));
ASSERT_TRUE(result.at<bool>(17));
ASSERT_TRUE(result.at<bool>(18));
ASSERT_TRUE(result.at<bool>(19));
ASSERT_TRUE(result.at<bool>(20));
ASSERT_TRUE(result.at<bool>(21));
ASSERT_TRUE(result.at<bool>(22));
ASSERT_TRUE(result.at<bool>(23));
ASSERT_TRUE(result.at<bool>(24));
}
|
#include <CGAL/Simple_cartesian.h>
#include <CGAL/boost/graph/graph_traits_Linear_cell_complex_for_combinatorial_map.h>
#include <CGAL/boost/graph/properties_Linear_cell_complex_for_combinatorial_map.h>
#include <CGAL/extract_mean_curvature_flow_skeleton.h>
#include <CGAL/boost/graph/split_graph_into_polylines.h>
#include <fstream>
typedef CGAL::Simple_cartesian<double> Kernel;
typedef Kernel::Point_3 Point;
typedef CGAL::Linear_cell_complex_traits<3, Kernel> MyTraits;
typedef CGAL::Linear_cell_complex_for_bgl_combinatorial_map_helper
<2, 3, MyTraits>::type LCC;
typedef boost::graph_traits<LCC>::vertex_descriptor vertex_descriptor;
typedef CGAL::Mean_curvature_flow_skeletonization<LCC> Skeletonization;
typedef Skeletonization::Skeleton Skeleton;
typedef Skeleton::vertex_descriptor Skeleton_vertex;
typedef Skeleton::edge_descriptor Skeleton_edge;
//only needed for the display of the skeleton as maximal polylines
struct Display_polylines{
const Skeleton& skeleton;
std::ofstream& out;
int polyline_size;
std::stringstream sstr;
Display_polylines(const Skeleton& skeleton, std::ofstream& out)
: skeleton(skeleton), out(out)
{}
void start_new_polyline(){
polyline_size=0;
sstr.str("");
sstr.clear();
}
void add_node(Skeleton_vertex v){
++polyline_size;
sstr << " " << skeleton[v].point;
}
void end_polyline()
{
out << polyline_size << sstr.str() << "\n";
}
};
// This example extracts a medially centered skeleton from a given mesh.
int main()
{
LCC lcc;
CGAL::read_off("data/elephant.off", lcc);
Skeleton skeleton;
CGAL::extract_mean_curvature_flow_skeleton(lcc, skeleton);
std::cout << "Number of vertices of the skeleton: " << boost::num_vertices(skeleton) << "\n";
std::cout << "Number of edges of the skeleton: " << boost::num_edges(skeleton) << "\n";
// Output all the edges of the skeleton.
std::ofstream output("skel-lcc.cgal");
Display_polylines display(skeleton,output);
CGAL::split_graph_into_polylines(skeleton, display);
output.close();
// Output skeleton points and the corresponding surface points
output.open("correspondance-lcc.cgal");
for(Skeleton_vertex v : CGAL::make_range(vertices(skeleton)))
for(vertex_descriptor vd : skeleton[v].vertices)
output << "2 " << skeleton[v].point << " "
<< get(CGAL::vertex_point, lcc, vd) << "\n";
return 0;
}
|
#include "headers.h"
using namespace std ;
string dts( double db )
{
ostringstream strs;
strs << db;
string str = strs.str();
return str ;
}
|
// Copyright (C) 2020-2021 Jonathan Müller <jonathanmueller.dev@gmail.com>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.
#ifndef LEXY_ACTION_BASE_HPP_INCLUDED
#define LEXY_ACTION_BASE_HPP_INCLUDED
#include <lexy/_detail/config.hpp>
#include <lexy/_detail/lazy_init.hpp>
#include <lexy/dsl/base.hpp>
#include <lexy/grammar.hpp>
//=== parse_context ===//
namespace lexy::_detail
{
template <typename Handler, typename Production>
using handler_production_result = typename Handler::template production_result<Production>;
template <typename Handler, typename Production>
using handler_marker = typename Handler::template marker<Production>;
template <typename Handler, typename Production, typename RootProduction>
class parse_context
{
public:
//=== parse context ===//
using handler = Handler;
using production = Production;
using root_production = RootProduction;
constexpr auto& production_context()
{
return *this;
}
template <typename Event, typename... Args>
constexpr auto on(Event ev, Args&&... args) -> std::enable_if_t<
!std::is_base_of_v<parse_events::_production_event, Event>,
decltype(LEXY_DECLVAL(Handler&).on(LEXY_DECLVAL(const handler_marker<Handler, Production>&),
ev, LEXY_FWD(args)...))>
{
LEXY_ASSERT(_handler, "using already finished context");
return _handler->on(_marker, ev, LEXY_FWD(args)...);
}
//=== context variables ===//
template <typename Id>
static LEXY_CONSTEVAL bool contains(Id)
{
return false;
}
template <typename Id>
constexpr auto get(Id)
{
static_assert(lexy::_detail::error<Id>, "context does not contain a variable with that id");
return nullptr;
}
#ifndef _MSC_VER
private:
// MSVC is a bad compiler and should feel bad.
// Or at least fix their friend declarations.
#endif
template <typename Iterator>
constexpr explicit parse_context(Handler& handler, Iterator begin)
: _handler(&handler), _marker(handler.on(parse_events::production_start<Production>{}, begin))
{}
template <typename ChildProduction, typename Iterator>
constexpr auto on(parse_events::production_start<ChildProduction>, Iterator begin)
{
// If the new production is a token production, need to re-root it.
using new_root = std::conditional_t<lexy::is_token_production<ChildProduction>,
ChildProduction, root_production>;
return parse_context<Handler, ChildProduction, new_root>(*_handler, begin);
}
template <typename Iterator, typename... Args>
constexpr void on(parse_events::production_finish<Production> ev, Iterator end,
Args&&... args) &&
{
using result_t = handler_production_result<Handler, Production>;
if constexpr (std::is_void_v<result_t>)
{
_handler->on(LEXY_MOV(_marker), ev, end, LEXY_FWD(args)...);
_result.emplace();
}
else
{
_result.emplace(_handler->on(LEXY_MOV(_marker), ev, end, LEXY_FWD(args)...));
}
_handler = nullptr; // invalidate
}
template <typename Iterator>
constexpr void on(parse_events::production_cancel<Production> ev, Iterator pos) &&
{
_handler->on(LEXY_MOV(_marker), ev, pos);
_handler = nullptr; // invalidate
}
Handler* _handler;
handler_marker<Handler, Production> _marker;
lazy_init<handler_production_result<Handler, Production>> _result;
template <typename, typename, typename>
friend class parse_context;
friend struct final_parser;
template <typename, typename>
friend struct production_parser;
template <typename P, typename H, typename Reader>
friend constexpr auto action_impl(H& handler, Reader& reader)
-> lazy_init<handler_production_result<H, P>>;
};
} // namespace lexy::_detail
//=== do_action ===//
namespace lexy::_detail
{
struct final_parser
{
template <typename Context, typename Reader, typename... Args>
LEXY_DSL_FUNC bool parse(Context& context, Reader& reader, Args&&... args)
{
using event = parse_events::production_finish<typename Context::production>;
LEXY_MOV(context.production_context()).on(event{}, reader.cur(), LEXY_FWD(args)...);
return true;
}
};
template <typename Production, typename Context, typename Reader>
constexpr bool parse_production(Context& context, Reader& reader)
{
using rule = lexy::production_rule<Production>;
return lexy::rule_parser<rule, final_parser>::parse(context, reader);
}
template <typename Production, typename Context, typename Reader>
constexpr auto try_parse_production(Context& context, Reader& reader)
{
using rule = lexy::production_rule<Production>;
return lexy::rule_parser<rule, final_parser>::try_parse(context, reader);
}
template <typename Production, typename NextParser>
struct production_parser
{
struct _continuation
{
template <typename Context, typename Reader, typename Handler, typename Root,
typename... Args>
LEXY_DSL_FUNC bool parse(Context& context, Reader& reader,
parse_context<Handler, Production, Root>& new_context,
Args&&... args)
{
// Might need to skip whitespace, according to the original context.
using continuation
= std::conditional_t<lexy::is_token_production<Production>,
lexy::whitespace_parser<Context, NextParser>, NextParser>;
// Pass the produced value to the next parser.
using result_t = handler_production_result<Handler, Production>;
if constexpr (std::is_void_v<result_t>)
return continuation::parse(context, reader, LEXY_FWD(args)...);
else
return continuation::parse(context, reader, LEXY_FWD(args)...,
LEXY_MOV(*new_context._result));
}
};
template <typename Context, typename Reader, typename... Args>
LEXY_DSL_FUNC bool parse(Context& context, Reader& reader, Args&&... args)
{
auto new_context
= context.production_context().on(parse_events::production_start<Production>{},
reader.cur());
if (parse_production<Production>(new_context, reader))
{
// Extract the value and continue.
return _continuation::parse(context, reader, new_context, LEXY_FWD(args)...);
}
else
{
// We had an error, cancel the production.
LEXY_MOV(new_context).on(parse_events::production_cancel<Production>{}, reader.cur());
return false;
}
}
template <typename Context, typename Reader, typename... Args>
LEXY_DSL_FUNC auto try_parse(Context& context, Reader& reader, Args&&... args)
-> lexy::rule_try_parse_result
{
auto new_context
= context.production_context().on(parse_events::production_start<Production>{},
reader.cur());
if (auto result = try_parse_production<Production>(new_context, reader);
result == lexy::rule_try_parse_result::ok)
{
// Extract the value and continue.
return _continuation::parse(context, reader, new_context, LEXY_FWD(args)...)
? lexy::rule_try_parse_result::ok
: lexy::rule_try_parse_result::canceled;
}
else
{
// We had an error, cancel the production.
LEXY_MOV(new_context).on(parse_events::production_cancel<Production>{}, reader.cur());
return result;
}
}
};
template <typename Production, typename Handler, typename Reader>
constexpr auto action_impl(Handler& handler, Reader& reader)
-> lazy_init<handler_production_result<Handler, Production>>
{
parse_context<Handler, Production, Production> context(handler, reader.cur());
if (!parse_production<Production>(context, reader))
{
// We had an error, cancel the production.
LEXY_ASSERT(!context._result, "result must be empty on cancel");
LEXY_MOV(context).on(parse_events::production_cancel<Production>{}, reader.cur());
}
return LEXY_MOV(context._result);
}
} // namespace lexy::_detail
namespace lexy
{
template <typename Production, typename Handler, typename Reader>
constexpr auto do_action(Handler&& handler, Reader& reader)
{
static_assert(!std::is_reference_v<Handler>, "need to move handler in");
auto result = _detail::action_impl<Production>(handler, reader);
if (result)
{
using result_t = _detail::handler_production_result<Handler, Production>;
if constexpr (std::is_void_v<result_t>)
return LEXY_MOV(handler).template get_result_value<Production>();
else
return LEXY_MOV(handler).template get_result_value<Production>(LEXY_MOV(*result));
}
else
{
return LEXY_MOV(handler).template get_result_empty<Production>();
}
}
} // namespace lexy
#endif // LEXY_ACTION_BASE_HPP_INCLUDED
|
// license [
// This file is part of the Phantom project. Copyright 2011-2020 Vivien Millet.
// Distributed under the MIT license. Text available here at
// https://github.com/vlmillet/phantom
// ]
#include "UserData.hxx"
|
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define FAST_IO ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define endl "\n"
#define pb push_back
#define loop(i,n) for(int i=0;i<n;i++)
#define iloop(a,i,n) for(int i=a;i<=n;i++)
#define bug(i) cout<<"debug at:"<<__LINE__<<" "<<i<<endl
#define out(i) cout<<i<<endl
#define mod 1000000007 //10e9+7
typedef pair<ll, int> pi;
void pre(){
FAST_IO;
//code for pre celculations
}
struct Test{
int x, y;
ll z;
};
void solve(){
int n;
cin>>n;
ll f,temp;
cin>>f;
priority_queue<pi, vector<pi>, greater<pi> > pq;
vector<Test> ans;
pi t;
iloop(2,i,n){
cin>>temp;
pq.push(make_pair(temp,i));
}
int count=0;
Test next;
while(!pq.empty()){
count++;
t = pq.top();
pq.pop();
if(f>=t.first){
next.x=t.second;
next.y=1;
next.z=t.first;
ans.pb(next);
f+=t.first;
}
else{
if(pq.empty()){
count=2*n;
}
else{
pi nt = pq.top();
pq.pop();
ll dif = t.first - f;
t.first -= dif;
nt.first += dif;
f+=t.first;
next.x=t.second;
next.y=nt.second;
next.z=dif;
ans.pb(next);
next.x=t.second;
next.y=1;
next.z=t.first;
ans.pb(next);
pq.push(nt);
}
}
if(count>=2*n){
out("-1");
return;
}
}
out(ans.size());
for(auto l:ans){
cout<<l.x<<" "<<l.y<<" "<<l.z<<endl;
}
return;
}
void test(){
int t;
cin>>t;
iloop(1,i,t){
// cout<<"Case #"<<i<<": ";
solve();
}
return;
}
int main(){
// std::cout << std::fixed;
// std::cout << std::setprecision(10);
pre();
test();
// solve();
return 0;
}
|
// Copyright (c) 2001-2010 Hartmut Kaiser
// Copyright (c) 2001-2010 Joel de Guzman
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !defined(SPIRIT_REPOSITORY_QI_DIRECTIVE_APR_28_2009_1258PM)
#define SPIRIT_REPOSITORY_QI_DIRECTIVE_APR_28_2009_1258PM
#if defined(_MSC_VER)
#pragma once
#endif
#include <boost/spirit/repository/home/qi/directive/distinct.hpp>
#include <boost/spirit/repository/home/qi/directive/confix.hpp>
#endif
|
#include <mettle.hpp>
using namespace mettle;
#include <mettle/driver/log/xunit.hpp>
#include "log_runs.hpp"
#define XML "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
struct logger_factory {
logger_factory(std::size_t runs)
: ss(new std::ostringstream()),
logger(std::unique_ptr<std::ostream>(ss), runs) {}
std::ostringstream *ss;
log::xunit logger;
};
using namespace std::literals::chrono_literals;
suite<> test_verbose("xunit logger", [](auto &_) {
subsuite<logger_factory>(_, "single run", bind_factory(1), [](auto &_) {
_.test("passing run", [](logger_factory &f) {
passing_run(f.logger);
expect(f.ss->str(), equal_to(
XML
"<testsuites failures=\"0\" skipped=\"0\" tests=\"4\" "
"time=\"0.400000\">\n"
" <testsuite failures=\"0\" name=\"suite > subsuite\" "
"skipped=\"0\" tests=\"1\" time=\"0.100000\">\n"
" <testcase name=\"test 3\" time=\"0.100000\">\n"
" <system-out>\n"
" standard output\n"
" </system-out>\n"
" <system-err>\n"
" standard error\n"
" </system-err>\n"
" </testcase>\n"
" </testsuite>\n"
" <testsuite failures=\"0\" name=\"suite\" skipped=\"0\" tests=\"2\" "
"time=\"0.200000\">\n"
" <testcase name=\"test 1\" time=\"0.100000\"/>\n"
" <testcase name=\"test 2\" time=\"0.100000\"/>\n"
" </testsuite>\n"
" <testsuite failures=\"0\" name=\"second suite\" skipped=\"0\" "
"tests=\"1\" time=\"0.100000\">\n"
" <testcase name=\"test 4\" time=\"0.100000\">\n"
" <system-out>\n"
" standard output\n"
" </system-out>\n"
" <system-err>\n"
" standard error\n"
" </system-err>\n"
" </testcase>\n"
" </testsuite>\n"
"</testsuites>\n"
));
});
_.test("failing run", [](logger_factory &f) {
failing_run(f.logger);
expect(f.ss->str(), equal_to(
XML
"<testsuites failures=\"2\" skipped=\"1\" tests=\"4\" "
"time=\"0.300000\">\n"
" <testsuite failures=\"0\" name=\"suite > subsuite\" "
"skipped=\"1\" tests=\"1\" time=\"0.000000\">\n"
" <testcase name=\"test 3\">\n"
" <skipped message=\"message more\"/>\n"
" </testcase>\n"
" </testsuite>\n"
" <testsuite failures=\"1\" name=\"suite\" skipped=\"0\" tests=\"2\" "
"time=\"0.200000\">\n"
" <testcase name=\"test 1\" time=\"0.100000\">\n"
" <system-out>\n"
" standard output\n"
" </system-out>\n"
" <system-err>\n"
" standard error\n"
" </system-err>\n"
" </testcase>\n"
" <testcase name=\"test 2\" time=\"0.100000\">\n"
" <failure message=\"error\"/>\n"
" </testcase>\n"
" </testsuite>\n"
" <testsuite failures=\"1\" name=\"second suite\" skipped=\"0\" "
"tests=\"1\" time=\"0.100000\">\n"
" <testcase name=\"test 4\" time=\"0.100000\">\n"
" <failure message=\"error more\"/>\n"
" <system-out>\n"
" standard output\n"
" </system-out>\n"
" <system-err>\n"
" standard error\n"
" </system-err>\n"
" </testcase>\n"
" </testsuite>\n"
"</testsuites>\n"
));
});
_.test("failing file run", [](logger_factory &f) {
failing_file_run(f.logger);
expect(f.ss->str(), equal_to(
XML
"<testsuites failures=\"1\" skipped=\"1\" tests=\"5\" "
"time=\"0.300000\">\n"
" <testsuite failures=\"1\" name=\"file `test_file`\" tests=\"1\" "
"time=\"0\">\n"
" <testcase name=\"<file>\" time=\"0\">\n"
" <failure message=\"error more\"/>\n"
" </testcase>\n"
" </testsuite>\n"
" <testsuite failures=\"0\" name=\"second suite\" skipped=\"0\" "
"tests=\"1\" time=\"0.100000\">\n"
" <testcase name=\"test 4\" time=\"0.100000\">\n"
" <system-out>\n"
" standard output\n"
" </system-out>\n"
" <system-err>\n"
" standard error\n"
" </system-err>\n"
" </testcase>\n"
" </testsuite>\n"
"</testsuites>\n"
));
});
_.test("failing test and file run", [](logger_factory &f) {
failing_test_and_file_run(f.logger);
expect(f.ss->str(), equal_to(
XML
"<testsuites failures=\"3\" skipped=\"1\" tests=\"5\" "
"time=\"0.300000\">\n"
" <testsuite failures=\"1\" name=\"file `test_file`\" tests=\"1\" "
"time=\"0\">\n"
" <testcase name=\"<file>\" time=\"0\">\n"
" <failure message=\"error more\"/>\n"
" </testcase>\n"
" </testsuite>\n"
" <testsuite failures=\"1\" name=\"second suite\" skipped=\"0\" "
"tests=\"1\" time=\"0.100000\">\n"
" <testcase name=\"test 4\" time=\"0.100000\">\n"
" <failure message=\"error more\"/>\n"
" <system-out>\n"
" standard output\n"
" </system-out>\n"
" <system-err>\n"
" standard error\n"
" </system-err>\n"
" </testcase>\n"
" </testsuite>\n"
"</testsuites>\n"
));
});
});
_.test("multiple runs", []() {
expect([]() { log::xunit("file.xml", 2); }, thrown<std::domain_error>(
"xunit logger may only be used with --runs=1"
));
});
});
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2004, 2005 StatPro Italia srl
Copyright (C) 2007, 2012 Ferdinando Ametrano
Copyright (C) 2007, 2009 Piter Dias
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#include "bonds.hpp"
#include "utilities.hpp"
#include <ql/instruments/bonds/fixedratebond.hpp>
#include <ql/instruments/bonds/floatingratebond.hpp>
#include <ql/instruments/bonds/zerocouponbond.hpp>
#include <ql/time/calendars/target.hpp>
#include <ql/time/calendars/unitedstates.hpp>
#include <ql/time/calendars/unitedkingdom.hpp>
#include <ql/time/calendars/australia.hpp>
#include <ql/time/calendars/brazil.hpp>
#include <ql/time/calendars/nullcalendar.hpp>
#include <ql/time/daycounters/thirty360.hpp>
#include <ql/time/daycounters/actual360.hpp>
#include <ql/time/daycounters/actualactual.hpp>
#include <ql/time/daycounters/business252.hpp>
#include <ql/indexes/ibor/usdlibor.hpp>
#include <ql/quotes/simplequote.hpp>
#include <ql/utilities/dataformatters.hpp>
#include <ql/time/schedule.hpp>
#include <ql/cashflows/fixedratecoupon.hpp>
#include <ql/cashflows/simplecashflow.hpp>
#include <ql/cashflows/couponpricer.hpp>
#include <ql/cashflows/cashflows.hpp>
#include <ql/pricingengines/bond/discountingbondengine.hpp>
#include <ql/pricingengines/bond/bondfunctions.hpp>
using namespace QuantLib;
using namespace boost::unit_test_framework;
using boost::shared_ptr;
#define ASSERT_CLOSE(name, settlement, calculated, expected, tolerance) \
if (std::fabs(calculated-expected) > tolerance) { \
BOOST_FAIL("Failed to reproduce " << name << " at " << settlement \
<< "\n calculated: " << std::setprecision(8) << calculated \
<< "\n expected: " << std::setprecision(8) << expected); \
}
namespace {
struct CommonVars {
// common data
Calendar calendar;
Date today;
Real faceAmount;
// cleanup
SavedSettings backup;
// setup
CommonVars() {
calendar = TARGET();
today = calendar.adjust(Date::todaysDate());
Settings::instance().evaluationDate() = today;
faceAmount = 1000000.0;
}
};
}
void BondTest::testYield() {
BOOST_TEST_MESSAGE("Testing consistency of bond price/yield calculation...");
CommonVars vars;
Real tolerance = 1.0e-7;
Size maxEvaluations = 100;
Integer issueMonths[] = { -24, -18, -12, -6, 0, 6, 12, 18, 24 };
Integer lengths[] = { 3, 5, 10, 15, 20 };
Natural settlementDays = 3;
Real coupons[] = { 0.02, 0.05, 0.08 };
Frequency frequencies[] = { Semiannual, Annual };
DayCounter bondDayCount = Thirty360();
BusinessDayConvention accrualConvention = Unadjusted;
BusinessDayConvention paymentConvention = ModifiedFollowing;
Real redemption = 100.0;
Rate yields[] = { 0.03, 0.04, 0.05, 0.06, 0.07 };
Compounding compounding[] = { Compounded, Continuous };
for (Size i=0; i<LENGTH(issueMonths); i++) {
for (Size j=0; j<LENGTH(lengths); j++) {
for (Size k=0; k<LENGTH(coupons); k++) {
for (Size l=0; l<LENGTH(frequencies); l++) {
for (Size n=0; n<LENGTH(compounding); n++) {
Date dated = vars.calendar.advance(vars.today,
issueMonths[i], Months);
Date issue = dated;
Date maturity = vars.calendar.advance(issue,
lengths[j], Years);
Schedule sch(dated, maturity,
Period(frequencies[l]), vars.calendar,
accrualConvention, accrualConvention,
DateGeneration::Backward, false);
FixedRateBond bond(settlementDays, vars.faceAmount, sch,
std::vector<Rate>(1, coupons[k]),
bondDayCount, paymentConvention,
redemption, issue);
for (Size m=0; m<LENGTH(yields); m++) {
Real price = BondFunctions::cleanPrice(bond, yields[m],
bondDayCount,
compounding[n],
frequencies[l]);
Rate calculated = BondFunctions::yield(bond, price,
bondDayCount, compounding[n],
frequencies[l],
Date(),
tolerance, maxEvaluations);
if (std::fabs(yields[m]-calculated) > tolerance) {
// the difference might not matter
Real price2 = BondFunctions::cleanPrice(bond, calculated,
bondDayCount,
compounding[n],
frequencies[l]);
if (std::fabs(price-price2)/price > tolerance) {
BOOST_FAIL("\nyield recalculation failed:"
"\n issue: " << issue <<
"\n maturity: " << maturity <<
"\n coupon: " << io::rate(coupons[k]) <<
"\n frequency: " << frequencies[l] <<
"\n yield: " << io::rate(yields[m]) <<
(compounding[n] == Compounded ?
" compounded" : " continuous") <<
std::setprecision(7) <<
"\n price: " << price <<
"\n yield': " << io::rate(calculated) <<
"\n price': " << price2);
}
}
}
}
}
}
}
}
}
void BondTest::testAtmRate() {
BOOST_TEST_MESSAGE("Testing consistency of bond price/ATM rate calculation...");
CommonVars vars;
Real tolerance = 1.0e-7;
Integer issueMonths[] = { -24, -18, -12, -6, 0, 6, 12, 18, 24 };
Integer lengths[] = { 3, 5, 10, 15, 20 };
Natural settlementDays = 3;
Real coupons[] = { 0.02, 0.05, 0.08 };
Frequency frequencies[] = { Semiannual, Annual };
DayCounter bondDayCount = Thirty360();
BusinessDayConvention accrualConvention = Unadjusted;
BusinessDayConvention paymentConvention = ModifiedFollowing;
Real redemption = 100.0;
Handle<YieldTermStructure> disc(flatRate(vars.today,0.03,Actual360()));
shared_ptr<PricingEngine> bondEngine(new DiscountingBondEngine(disc));
for (Size i=0; i<LENGTH(issueMonths); i++) {
for (Size j=0; j<LENGTH(lengths); j++) {
for (Size k=0; k<LENGTH(coupons); k++) {
for (Size l=0; l<LENGTH(frequencies); l++) {
Date dated = vars.calendar.advance(vars.today,
issueMonths[i], Months);
Date issue = dated;
Date maturity = vars.calendar.advance(issue,
lengths[j], Years);
Schedule sch(dated, maturity,
Period(frequencies[l]), vars.calendar,
accrualConvention, accrualConvention,
DateGeneration::Backward, false);
FixedRateBond bond(settlementDays, vars.faceAmount, sch,
std::vector<Rate>(1, coupons[k]),
bondDayCount, paymentConvention,
redemption, issue);
bond.setPricingEngine(bondEngine);
Real price = bond.cleanPrice();
Rate calculated = BondFunctions::atmRate(bond,
**disc,
bond.settlementDate(),
price);
if (std::fabs(coupons[k]-calculated) > tolerance) {
BOOST_FAIL("\natm rate recalculation failed:"
"\n today: " << vars.today <<
"\n settlement date: " << bond.settlementDate() <<
"\n issue: " << issue <<
"\n maturity: " << maturity <<
"\n coupon: " << io::rate(coupons[k]) <<
"\n frequency: " << frequencies[l] <<
"\n clean price: " << price <<
"\n dirty price: " << price + bond.accruedAmount() <<
"\n atm rate: " << io::rate(calculated));
}
}
}
}
}
}
void BondTest::testZspread() {
BOOST_TEST_MESSAGE("Testing consistency of bond price/z-spread calculation...");
CommonVars vars;
Real tolerance = 1.0e-7;
Size maxEvaluations = 100;
Handle<YieldTermStructure> discountCurve(
flatRate(vars.today,0.03,Actual360()));
Integer issueMonths[] = { -24, -18, -12, -6, 0, 6, 12, 18, 24 };
Integer lengths[] = { 3, 5, 10, 15, 20 };
Natural settlementDays = 3;
Real coupons[] = { 0.02, 0.05, 0.08 };
Frequency frequencies[] = { Semiannual, Annual };
DayCounter bondDayCount = Thirty360();
BusinessDayConvention accrualConvention = Unadjusted;
BusinessDayConvention paymentConvention = ModifiedFollowing;
Real redemption = 100.0;
Spread spreads[] = { -0.01, -0.005, 0.0, 0.005, 0.01 };
Compounding compounding[] = { Compounded, Continuous };
for (Size i=0; i<LENGTH(issueMonths); i++) {
for (Size j=0; j<LENGTH(lengths); j++) {
for (Size k=0; k<LENGTH(coupons); k++) {
for (Size l=0; l<LENGTH(frequencies); l++) {
for (Size n=0; n<LENGTH(compounding); n++) {
Date dated = vars.calendar.advance(vars.today,
issueMonths[i], Months);
Date issue = dated;
Date maturity = vars.calendar.advance(issue,
lengths[j], Years);
Schedule sch(dated, maturity,
Period(frequencies[l]), vars.calendar,
accrualConvention, accrualConvention,
DateGeneration::Backward, false);
FixedRateBond bond(settlementDays, vars.faceAmount, sch,
std::vector<Rate>(1, coupons[k]),
bondDayCount, paymentConvention,
redemption, issue);
for (Size m=0; m<LENGTH(spreads); m++) {
Real price = BondFunctions::cleanPrice(bond, *discountCurve,
spreads[m],
bondDayCount,
compounding[n],
frequencies[l]);
Spread calculated = BondFunctions::zSpread(bond, price,
*discountCurve,
bondDayCount,
compounding[n],
frequencies[l],
Date(),
tolerance,
maxEvaluations);
if (std::fabs(spreads[m]-calculated) > tolerance) {
// the difference might not matter
Real price2 = BondFunctions::cleanPrice(bond, *discountCurve,
calculated,
bondDayCount,
compounding[n],
frequencies[l]);
if (std::fabs(price-price2)/price > tolerance) {
BOOST_FAIL("\nZ-spread recalculation failed:"
"\n issue: " << issue <<
"\n maturity: " << maturity <<
"\n coupon: " << io::rate(coupons[k]) <<
"\n frequency: " << frequencies[l] <<
"\n Z-spread: " << io::rate(spreads[m]) <<
(compounding[n] == Compounded ?
" compounded" : " continuous") <<
std::setprecision(7) <<
"\n price: " << price <<
"\n Z-spread': " << io::rate(calculated) <<
"\n price': " << price2);
}
}
}
}
}
}
}
}
}
void BondTest::testTheoretical() {
BOOST_TEST_MESSAGE("Testing theoretical bond price/yield calculation...");
CommonVars vars;
Real tolerance = 1.0e-7;
Size maxEvaluations = 100;
Size lengths[] = { 3, 5, 10, 15, 20 };
Natural settlementDays = 3;
Real coupons[] = { 0.02, 0.05, 0.08 };
Frequency frequencies[] = { Semiannual, Annual };
DayCounter bondDayCount = Actual360();
BusinessDayConvention accrualConvention = Unadjusted;
BusinessDayConvention paymentConvention = ModifiedFollowing;
Real redemption = 100.0;
Rate yields[] = { 0.03, 0.04, 0.05, 0.06, 0.07 };
for (Size j=0; j<LENGTH(lengths); j++) {
for (Size k=0; k<LENGTH(coupons); k++) {
for (Size l=0; l<LENGTH(frequencies); l++) {
Date dated = vars.today;
Date issue = dated;
Date maturity = vars.calendar.advance(issue, lengths[j], Years);
shared_ptr<SimpleQuote> rate(new SimpleQuote(0.0));
Handle<YieldTermStructure> discountCurve(flatRate(vars.today,
rate,
bondDayCount));
Schedule sch(dated, maturity,
Period(frequencies[l]), vars.calendar,
accrualConvention, accrualConvention,
DateGeneration::Backward, false);
FixedRateBond bond(settlementDays, vars.faceAmount, sch,
std::vector<Rate>(1, coupons[k]),
bondDayCount, paymentConvention,
redemption, issue);
shared_ptr<PricingEngine> bondEngine(
new DiscountingBondEngine(discountCurve));
bond.setPricingEngine(bondEngine);
for (Size m=0; m<LENGTH(yields); m++) {
rate->setValue(yields[m]);
Real price = BondFunctions::cleanPrice(bond, yields[m],
bondDayCount, Continuous,
frequencies[l]);
Real calculatedPrice = bond.cleanPrice();
if (std::fabs(price-calculatedPrice) > tolerance) {
BOOST_FAIL("price calculation failed:" <<
"\n issue: " << issue <<
"\n maturity: " << maturity <<
"\n coupon: " << io::rate(coupons[k]) <<
"\n frequency: " << frequencies[l] <<
"\n yield: " << io::rate(yields[m]) <<
std::setprecision(7) <<
"\n expected: " << price <<
"\n calculated': " << calculatedPrice <<
"\n error': " << price-calculatedPrice);
}
Rate calculatedYield = BondFunctions::yield(bond, calculatedPrice,
bondDayCount, Continuous, frequencies[l],
bond.settlementDate(),
tolerance, maxEvaluations);
if (std::fabs(yields[m]-calculatedYield) > tolerance) {
BOOST_FAIL("yield calculation failed:" <<
"\n issue: " << issue <<
"\n maturity: " << maturity <<
"\n coupon: " << io::rate(coupons[k]) <<
"\n frequency: " << frequencies[l] <<
"\n yield: " << io::rate(yields[m]) <<
std::setprecision(7) <<
"\n price: " << price <<
"\n yield': " << io::rate(calculatedYield));
}
}
}
}
}
}
void BondTest::testCached() {
BOOST_TEST_MESSAGE(
"Testing bond price/yield calculation against cached values...");
CommonVars vars;
// with implicit settlement calculation:
Date today(22, November, 2004);
Settings::instance().evaluationDate() = today;
Calendar bondCalendar = NullCalendar();
DayCounter bondDayCount = ActualActual(ActualActual::ISMA);
Natural settlementDays = 1;
Handle<YieldTermStructure> discountCurve(flatRate(today,0.03,Actual360()));
// actual market values from the evaluation date
Frequency freq = Semiannual;
Schedule sch1(Date(31, October, 2004),
Date(31, October, 2006), Period(freq), bondCalendar,
Unadjusted, Unadjusted, DateGeneration::Backward, false);
FixedRateBond bond1(settlementDays, vars.faceAmount, sch1,
std::vector<Rate>(1, 0.025),
bondDayCount, ModifiedFollowing,
100.0, Date(1, November, 2004));
shared_ptr<PricingEngine> bondEngine(
new DiscountingBondEngine(discountCurve));
bond1.setPricingEngine(bondEngine);
Real marketPrice1 = 99.203125;
Rate marketYield1 = 0.02925;
Schedule sch2(Date(15, November, 2004),
Date(15, November, 2009), Period(freq), bondCalendar,
Unadjusted, Unadjusted, DateGeneration::Backward, false);
FixedRateBond bond2(settlementDays, vars.faceAmount, sch2,
std::vector<Rate>(1, 0.035),
bondDayCount, ModifiedFollowing,
100.0, Date(15, November, 2004));
bond2.setPricingEngine(bondEngine);
Real marketPrice2 = 99.6875;
Rate marketYield2 = 0.03569;
// calculated values
Real cachedPrice1a = 99.204505, cachedPrice2a = 99.687192;
Real cachedPrice1b = 98.943393, cachedPrice2b = 101.986794;
Rate cachedYield1a = 0.029257, cachedYield2a = 0.035689;
Rate cachedYield1b = 0.029045, cachedYield2b = 0.035375;
Rate cachedYield1c = 0.030423, cachedYield2c = 0.030432;
// check
Real tolerance = 1.0e-6;
Real price, yield;
price = BondFunctions::cleanPrice(bond1, marketYield1,
bondDayCount, Compounded, freq);
if (std::fabs(price-cachedPrice1a) > tolerance) {
BOOST_FAIL("failed to reproduce cached price:"
<< QL_FIXED
<< "\n calculated: " << price
<< "\n expected: " << cachedPrice1a
<< "\n tolerance: " << tolerance
<< "\n error: " << price-cachedPrice1a);
}
price = bond1.cleanPrice();
if (std::fabs(price-cachedPrice1b) > tolerance) {
BOOST_FAIL("failed to reproduce cached price:"
<< QL_FIXED
<< "\n calculated: " << price
<< "\n expected: " << cachedPrice1b
<< "\n tolerance: " << tolerance
<< "\n error: " << price-cachedPrice1b);
}
yield = BondFunctions::yield(bond1, marketPrice1, bondDayCount, Compounded, freq);
if (std::fabs(yield-cachedYield1a) > tolerance) {
BOOST_FAIL("\nfailed to reproduce cached compounded yield:" <<
std::setprecision(4) <<
"\n calculated: " << io::rate(yield) <<
"\n expected: " << io::rate(cachedYield1a) <<
"\n tolerance: " << io::rate(tolerance) <<
"\n error: " << io::rate(yield-cachedYield1a));
}
yield = BondFunctions::yield(bond1, marketPrice1, bondDayCount, Continuous, freq);
if (std::fabs(yield-cachedYield1b) > tolerance) {
BOOST_FAIL("failed to reproduce cached continuous yield:"
<< std::setprecision(4)
<< "\n calculated: " << io::rate(yield)
<< "\n expected: " << io::rate(cachedYield1b)
<< "\n tolerance: " << io::rate(tolerance)
<< "\n error: " << io::rate(yield-cachedYield1b));
}
yield = BondFunctions::yield(bond1, bond1.cleanPrice(), bondDayCount, Continuous, freq, bond1.settlementDate());
if (std::fabs(yield-cachedYield1c) > tolerance) {
BOOST_FAIL("failed to reproduce cached continuous yield:"
<< std::setprecision(4)
<< "\n calculated: " << io::rate(yield)
<< "\n expected: " << io::rate(cachedYield1c)
<< "\n tolerance: " << io::rate(tolerance)
<< "\n error: " << io::rate(yield-cachedYield1c));
}
price = BondFunctions::cleanPrice(bond2, marketYield2, bondDayCount, Compounded, freq);
if (std::fabs(price-cachedPrice2a) > tolerance) {
BOOST_FAIL("failed to reproduce cached price:"
<< QL_FIXED
<< "\n calculated: " << price
<< "\n expected: " << cachedPrice2a
<< "\n tolerance: " << tolerance
<< "\n error: " << price-cachedPrice2a);
}
price = bond2.cleanPrice();
if (std::fabs(price-cachedPrice2b) > tolerance) {
BOOST_FAIL("failed to reproduce cached price:"
<< QL_FIXED
<< "\n calculated: " << price
<< "\n expected: " << cachedPrice2b
<< "\n tolerance: " << tolerance
<< "\n error: " << price-cachedPrice2b);
}
yield = BondFunctions::yield(bond2, marketPrice2, bondDayCount, Compounded, freq);
if (std::fabs(yield-cachedYield2a) > tolerance) {
BOOST_FAIL("failed to reproduce cached compounded yield:"
<< std::setprecision(4)
<< "\n calculated: " << io::rate(yield)
<< "\n expected: " << io::rate(cachedYield2a)
<< "\n tolerance: " << tolerance
<< "\n error: " << io::rate(yield-cachedYield2a));
}
yield = BondFunctions::yield(bond2, marketPrice2, bondDayCount, Continuous, freq);
if (std::fabs(yield-cachedYield2b) > tolerance) {
BOOST_FAIL("failed to reproduce cached continuous yield:"
<< std::setprecision(4)
<< "\n calculated: " << io::rate(yield)
<< "\n expected: " << io::rate(cachedYield2b)
<< "\n tolerance: " << tolerance
<< "\n error: " << io::rate(yield-cachedYield2b));
}
yield = BondFunctions::yield(bond2, bond2.cleanPrice(), bondDayCount, Continuous, freq, bond2.settlementDate());
if (std::fabs(yield-cachedYield2c) > tolerance) {
BOOST_FAIL("failed to reproduce cached continuous yield:"
<< std::setprecision(4)
<< "\n calculated: " << io::rate(yield)
<< "\n expected: " << io::rate(cachedYield2c)
<< "\n tolerance: " << tolerance
<< "\n error: " << io::rate(yield-cachedYield2c));
}
// with explicit settlement date:
Schedule sch3(Date(30,November,2004),
Date(30,November,2006), Period(freq),
UnitedStates(UnitedStates::GovernmentBond),
Unadjusted, Unadjusted, DateGeneration::Backward, false);
FixedRateBond bond3(settlementDays, vars.faceAmount, sch3,
std::vector<Rate>(1, 0.02875),
ActualActual(ActualActual::ISMA),
ModifiedFollowing,
100.0, Date(30,November,2004));
bond3.setPricingEngine(bondEngine);
Rate marketYield3 = 0.02997;
Date settlementDate = Date(30,November,2004);
Real cachedPrice3 = 99.764759;
price = BondFunctions::cleanPrice(bond3, marketYield3,
bondDayCount, Compounded, freq, settlementDate);
if (std::fabs(price-cachedPrice3) > tolerance) {
BOOST_FAIL("failed to reproduce cached price:"
<< QL_FIXED
<< "\n calculated: " << price << ""
<< "\n expected: " << cachedPrice3 << ""
<< "\n error: " << price-cachedPrice3);
}
// this should give the same result since the issue date is the
// earliest possible settlement date
Settings::instance().evaluationDate() = Date(22,November,2004);
price = BondFunctions::cleanPrice(bond3, marketYield3, bondDayCount, Compounded, freq);
if (std::fabs(price-cachedPrice3) > tolerance) {
BOOST_FAIL("failed to reproduce cached price:"
<< QL_FIXED
<< "\n calculated: " << price << ""
<< "\n expected: " << cachedPrice3 << ""
<< "\n error: " << price-cachedPrice3);
}
}
void BondTest::testCachedZero() {
BOOST_TEST_MESSAGE("Testing zero-coupon bond prices against cached values...");
CommonVars vars;
Date today(22,November,2004);
Settings::instance().evaluationDate() = today;
Natural settlementDays = 1;
Handle<YieldTermStructure> discountCurve(flatRate(today,0.03,Actual360()));
Real tolerance = 1.0e-6;
// plain
ZeroCouponBond bond1(settlementDays,
UnitedStates(UnitedStates::GovernmentBond),
vars.faceAmount,
Date(30,November,2008),
ModifiedFollowing,
100.0, Date(30,November,2004));
shared_ptr<PricingEngine> bondEngine(
new DiscountingBondEngine(discountCurve));
bond1.setPricingEngine(bondEngine);
Real cachedPrice1 = 88.551726;
Real price = bond1.cleanPrice();
if (std::fabs(price-cachedPrice1) > tolerance) {
BOOST_FAIL("failed to reproduce cached price:\n"
<< QL_FIXED
<< " calculated: " << price << "\n"
<< " expected: " << cachedPrice1 << "\n"
<< " error: " << price-cachedPrice1);
}
ZeroCouponBond bond2(settlementDays,
UnitedStates(UnitedStates::GovernmentBond),
vars.faceAmount,
Date(30,November,2007),
ModifiedFollowing,
100.0, Date(30,November,2004));
bond2.setPricingEngine(bondEngine);
Real cachedPrice2 = 91.278949;
price = bond2.cleanPrice();
if (std::fabs(price-cachedPrice2) > tolerance) {
BOOST_FAIL("failed to reproduce cached price:\n"
<< QL_FIXED
<< " calculated: " << price << "\n"
<< " expected: " << cachedPrice2 << "\n"
<< " error: " << price-cachedPrice2);
}
ZeroCouponBond bond3(settlementDays,
UnitedStates(UnitedStates::GovernmentBond),
vars.faceAmount,
Date(30,November,2006),
ModifiedFollowing,
100.0, Date(30,November,2004));
bond3.setPricingEngine(bondEngine);
Real cachedPrice3 = 94.098006;
price = bond3.cleanPrice();
if (std::fabs(price-cachedPrice3) > tolerance) {
BOOST_FAIL("failed to reproduce cached price:\n"
<< QL_FIXED
<< " calculated: " << price << "\n"
<< " expected: " << cachedPrice3 << "\n"
<< " error: " << price-cachedPrice3);
}
}
void BondTest::testCachedFixed() {
BOOST_TEST_MESSAGE("Testing fixed-coupon bond prices against cached values...");
CommonVars vars;
Date today(22,November,2004);
Settings::instance().evaluationDate() = today;
Natural settlementDays = 1;
Handle<YieldTermStructure> discountCurve(flatRate(today,0.03,Actual360()));
Real tolerance = 1.0e-6;
// plain
Schedule sch(Date(30,November,2004),
Date(30,November,2008), Period(Semiannual),
UnitedStates(UnitedStates::GovernmentBond),
Unadjusted, Unadjusted, DateGeneration::Backward, false);
FixedRateBond bond1(settlementDays, vars.faceAmount, sch,
std::vector<Rate>(1, 0.02875),
ActualActual(ActualActual::ISMA),
ModifiedFollowing,
100.0, Date(30,November,2004));
shared_ptr<PricingEngine> bondEngine(
new DiscountingBondEngine(discountCurve));
bond1.setPricingEngine(bondEngine);
Real cachedPrice1 = 99.298100;
Real price = bond1.cleanPrice();
if (std::fabs(price-cachedPrice1) > tolerance) {
BOOST_FAIL("failed to reproduce cached price:\n"
<< QL_FIXED
<< " calculated: " << price << "\n"
<< " expected: " << cachedPrice1 << "\n"
<< " error: " << price-cachedPrice1);
}
// varying coupons
std::vector<Rate> couponRates(4);
couponRates[0] = 0.02875;
couponRates[1] = 0.03;
couponRates[2] = 0.03125;
couponRates[3] = 0.0325;
FixedRateBond bond2(settlementDays, vars.faceAmount, sch,
couponRates,
ActualActual(ActualActual::ISMA),
ModifiedFollowing,
100.0, Date(30,November,2004));
bond2.setPricingEngine(bondEngine);
Real cachedPrice2 = 100.334149;
price = bond2.cleanPrice();
if (std::fabs(price-cachedPrice2) > tolerance) {
BOOST_FAIL("failed to reproduce cached price:\n"
<< QL_FIXED
<< " calculated: " << price << "\n"
<< " expected: " << cachedPrice2 << "\n"
<< " error: " << price-cachedPrice2);
}
// stub date
Schedule sch3(Date(30,November,2004),
Date(30,March,2009), Period(Semiannual),
UnitedStates(UnitedStates::GovernmentBond),
Unadjusted, Unadjusted, DateGeneration::Backward, false,
Date(), Date(30,November,2008));
FixedRateBond bond3(settlementDays, vars.faceAmount, sch3,
couponRates, ActualActual(ActualActual::ISMA),
ModifiedFollowing,
100.0, Date(30,November,2004));
bond3.setPricingEngine(bondEngine);
Real cachedPrice3 = 100.382794;
price = bond3.cleanPrice();
if (std::fabs(price-cachedPrice3) > tolerance) {
BOOST_FAIL("failed to reproduce cached price:\n"
<< QL_FIXED
<< " calculated: " << price << "\n"
<< " expected: " << cachedPrice3 << "\n"
<< " error: " << price-cachedPrice3);
}
}
void BondTest::testCachedFloating() {
BOOST_TEST_MESSAGE("Testing floating-rate bond prices against cached values...");
CommonVars vars;
Date today(22,November,2004);
Settings::instance().evaluationDate() = today;
Natural settlementDays = 1;
Handle<YieldTermStructure> riskFreeRate(flatRate(today,0.025,Actual360()));
Handle<YieldTermStructure> discountCurve(flatRate(today,0.03,Actual360()));
shared_ptr<IborIndex> index(new USDLibor(6*Months, riskFreeRate));
Natural fixingDays = 1;
Real tolerance = 1.0e-6;
shared_ptr<IborCouponPricer> pricer(new
BlackIborCouponPricer(Handle<OptionletVolatilityStructure>()));
// plain
Schedule sch(Date(30,November,2004),
Date(30,November,2008),
Period(Semiannual),
UnitedStates(UnitedStates::GovernmentBond),
ModifiedFollowing, ModifiedFollowing,
DateGeneration::Backward, false);
FloatingRateBond bond1(settlementDays, vars.faceAmount, sch,
index, ActualActual(ActualActual::ISMA),
ModifiedFollowing, fixingDays,
std::vector<Real>(), std::vector<Spread>(),
std::vector<Rate>(), std::vector<Rate>(),
false,
100.0, Date(30,November,2004));
shared_ptr<PricingEngine> bondEngine(
new DiscountingBondEngine(riskFreeRate));
bond1.setPricingEngine(bondEngine);
setCouponPricer(bond1.cashflows(),pricer);
#if defined(QL_USE_INDEXED_COUPON)
Real cachedPrice1 = 99.874645;
#else
Real cachedPrice1 = 99.874646;
#endif
Real price = bond1.cleanPrice();
if (std::fabs(price-cachedPrice1) > tolerance) {
BOOST_FAIL("failed to reproduce cached price:\n"
<< QL_FIXED
<< " calculated: " << price << "\n"
<< " expected: " << cachedPrice1 << "\n"
<< " error: " << price-cachedPrice1);
}
// different risk-free and discount curve
FloatingRateBond bond2(settlementDays, vars.faceAmount, sch,
index, ActualActual(ActualActual::ISMA),
ModifiedFollowing, fixingDays,
std::vector<Rate>(), std::vector<Spread>(),
std::vector<Rate>(), std::vector<Rate>(),
false,
100.0, Date(30,November,2004));
shared_ptr<PricingEngine> bondEngine2(
new DiscountingBondEngine(discountCurve));
bond2.setPricingEngine(bondEngine2);
setCouponPricer(bond2.cashflows(),pricer);
#if defined(QL_USE_INDEXED_COUPON)
Real cachedPrice2 = 97.955904;
#else
Real cachedPrice2 = 97.955904;
#endif
price = bond2.cleanPrice();
if (std::fabs(price-cachedPrice2) > tolerance) {
BOOST_FAIL("failed to reproduce cached price:\n"
<< QL_FIXED
<< " calculated: " << price << "\n"
<< " expected: " << cachedPrice2 << "\n"
<< " error: " << price-cachedPrice2);
}
// varying spread
std::vector<Rate> spreads(4);
spreads[0] = 0.001;
spreads[1] = 0.0012;
spreads[2] = 0.0014;
spreads[3] = 0.0016;
FloatingRateBond bond3(settlementDays, vars.faceAmount, sch,
index, ActualActual(ActualActual::ISMA),
ModifiedFollowing, fixingDays,
std::vector<Real>(), spreads,
std::vector<Rate>(), std::vector<Rate>(),
false,
100.0, Date(30,November,2004));
bond3.setPricingEngine(bondEngine2);
setCouponPricer(bond3.cashflows(),pricer);
#if defined(QL_USE_INDEXED_COUPON)
Real cachedPrice3 = 98.495458;
#else
Real cachedPrice3 = 98.495459;
#endif
price = bond3.cleanPrice();
if (std::fabs(price-cachedPrice3) > tolerance) {
BOOST_FAIL("failed to reproduce cached price:\n"
<< QL_FIXED
<< " calculated: " << price << "\n"
<< " expected: " << cachedPrice3 << "\n"
<< " error: " << price-cachedPrice3);
}
}
void BondTest::testBrazilianCached() {
BOOST_TEST_MESSAGE(
"Testing Brazilian public bond prices against Andima cached values...");
CommonVars vars;
Natural settlementDays = 1;
Real faceAmount = 1000.0;
Real redemption = 100.0;
Date today(6,June,2007);
Date issueDate(1,January,2007);
// The tolerance is high because Andima truncate yields
Real tolerance = 1.0e-4;
// Reset evaluation date
Settings::instance().evaluationDate() = today;
// NTN-F maturity dates
std::vector<Date> maturityDates(6);
maturityDates[0] = Date(1,January,2008);
maturityDates[1] = Date(1,January,2010);
maturityDates[2] = Date(1,July,2010);
maturityDates[3] = Date(1,January,2012);
maturityDates[4] = Date(1,January,2014);
maturityDates[5] = Date(1,January,2017);
// Andima NTN-F yields
std::vector<Rate> yields(6);
yields[0] = 0.114614;
yields[1] = 0.105726;
yields[2] = 0.105328;
yields[3] = 0.104283;
yields[4] = 0.103218;
yields[5] = 0.102948;
// Andima NTN-F prices
std::vector<Rate> prices(6);
prices[0] = 1034.63031372;
prices[1] = 1030.09919487;
prices[2] = 1029.98307160;
prices[3] = 1028.13585068;
prices[4] = 1028.33383817;
prices[5] = 1026.19716497;
std::vector<InterestRate> couponRates(1);
couponRates[0] = InterestRate(0.1, Thirty360(), Compounded,Annual);
for (Size bondIndex = 0; bondIndex < maturityDates.size(); bondIndex++) {
InterestRate yield(yields[bondIndex],
Business252(Brazil()),
Compounded, Annual);
Schedule schedule(Date(1,January,2007),
maturityDates[bondIndex], Period(Semiannual),
Brazil(Brazil::Settlement),
Unadjusted, Unadjusted,
DateGeneration::Backward, false);
FixedRateBond bond(settlementDays,
faceAmount,
schedule,
couponRates,
Following,
redemption,
issueDate);
Real cachedPrice = prices[bondIndex];
Real price = faceAmount *
(BondFunctions::cleanPrice(bond, yield.rate(), yield.dayCounter(),
yield.compounding(), yield.frequency(),
today) + bond.accruedAmount(today)) / 100.0;
if (std::fabs(price-cachedPrice) > tolerance) {
BOOST_ERROR("failed to reproduce Andima cached price:\n"
<< QL_FIXED
<< " calculated: " << price << "\n"
<< " expected: " << cachedPrice << "\n"
<< " error: " << price-cachedPrice << "\n"
);
}
}
}
void BondTest::testExCouponGilt() {
BOOST_TEST_MESSAGE(
"Testing ex-coupon UK Gilt price against market values...");
/* UK Gilts have an exCouponDate 7 business days before the coupon
is due (see <http://www.dmo.gov.uk/index.aspx?page=Gilts/Gilt_Faq>).
On the exCouponDate the bond still trades cum-coupon so we use
6 days below and UK calendar
Output verified with Bloomberg:
ISIN: GB0009997999
Issue Date: February 29th, 1996
Interest Accrue: February 29th, 1996
First Coupon: June 7th, 1996
Maturity: June 7th, 2021
coupon: 8
period: 6M
Settlement date: May 29th, 2013
Test Price : 103
Accrued : 38021.97802
NPV : 106.8021978
Yield : 7.495180593
Yield->NPV : 106.8021978
Yield->NPV->Price : 103
Mod duration : 5.676044458
Convexity : 0.4215314859
PV 0.01 : 0.0606214023
Settlement date: May 30th, 2013
Test Price : 103
Accrued : -1758.241758
NPV : 102.8241758
Yield : 7.496183543
Yield->NPV : 102.8241758
Yield->NPV->Price : 103
Mod duration : 5.892816328
Convexity : 0.4375621862
PV 0.01 : 0.06059239822
Settlement date: May 31st, 2013
Test Price : 103
Accrued : -1538.461538
NPV : 102.8461538
Yield : 7.495987492
Yield->NPV : 102.8461539
Yield->NPV->Price : 103
Mod duration : 5.890186028
Convexity : 0.4372394381
PV 0.01 : 0.06057829784
*/
struct test_case {
Date settlementDate;
Real testPrice;
Real accruedAmount;
Real NPV;
Rate yield;
Real duration;
Real convexity;
};
Calendar calendar = UnitedKingdom();
Natural settlementDays = 3;
Date issueDate(29, February, 1996);
Date startDate(29, February, 1996);
Date firstCouponDate(07, June, 1996);
Date maturityDate(07, June, 2021);
Rate coupon = 0.08;
Period tenor = 6*Months;
Period exCouponPeriod = 6*Days;
Compounding comp = Compounded;
Frequency freq = Semiannual;
DayCounter dc = ActualActual(ActualActual::ISMA);
FixedRateBond bond(settlementDays, 100.0,
Schedule(startDate, maturityDate, tenor,
NullCalendar(), Unadjusted, Unadjusted,
DateGeneration::Forward, true, firstCouponDate),
std::vector<Rate>(1, coupon),
dc, Unadjusted, 100.0,
issueDate, calendar, exCouponPeriod, calendar);
const Leg& leg = bond.cashflows();
test_case cases[] = {
{ Date(29,May,2013), 103.0,
3.8021978, 106.8021978, 0.0749518,
5.6760445, 42.1531486 },
{ Date(30,May,2013), 103.0,
-0.1758242, 102.8241758, 0.0749618,
5.8928163, 43.7562186 },
{ Date(31,May,2013), 103.0,
-0.1538462, 102.8461538, 0.0749599,
5.8901860, 43.7239438 }
};
for (Size i=0; i<LENGTH(cases); ++i) {
Real accrued = bond.accruedAmount(cases[i].settlementDate);
ASSERT_CLOSE("accrued amount", cases[i].settlementDate,
accrued, cases[i].accruedAmount, 1e-6);
Real npv = cases[i].testPrice + accrued;
ASSERT_CLOSE("NPV", cases[i].settlementDate,
npv, cases[i].NPV, 1e-6);
Rate yield = CashFlows::yield(leg, npv, dc, comp, freq,
false, cases[i].settlementDate);
ASSERT_CLOSE("yield", cases[i].settlementDate,
yield, cases[i].yield, 1e-6);
Time duration = CashFlows::duration(leg, yield, dc, comp, freq,
Duration::Modified, false,
cases[i].settlementDate);
ASSERT_CLOSE("duration", cases[i].settlementDate,
duration, cases[i].duration, 1e-6);
Real convexity = CashFlows::convexity(leg, yield, dc, comp, freq,
false, cases[i].settlementDate);
ASSERT_CLOSE("convexity", cases[i].settlementDate,
convexity, cases[i].convexity, 1e-6);
Real calcnpv = CashFlows::npv(leg, yield, dc, comp, freq,
false, cases[i].settlementDate);
ASSERT_CLOSE("NPV from yield", cases[i].settlementDate,
calcnpv, cases[i].NPV, 1e-6);
Real calcprice = calcnpv - accrued;
ASSERT_CLOSE("price from yield", cases[i].settlementDate,
calcprice, cases[i].testPrice, 1e-6);
}
}
void BondTest::testExCouponAustralianBond() {
BOOST_TEST_MESSAGE(
"Testing ex-coupon Australian bond price against market values...");
/* Australian Government Bonds have an exCouponDate 7 calendar
days before the coupon is due. On the exCouponDate the bond
trades ex-coupon so we use 7 days below and NullCalendar.
AGB accrued interest is rounded to 3dp.
Output verified with Bloomberg:
ISIN: AU300TB01208
Issue Date: June 10th, 2004
Interest Accrue: February 15th, 2004
First Coupon: August 15th, 2004
Maturity: February 15th, 2017
coupon: 6
period: 6M
Settlement date: August 7th, 2014
Test Price : 103
Accrued : 28670
NPV : 105.867
Yield : 4.723814867
Yield->NPV : 105.867
Yield->NPV->Price : 103
Mod duration : 2.262763296
Convexity : 0.0654870275
PV 0.01 : 0.02395519619
Settlement date: August 8th, 2014
Test Price : 103
Accrued : -1160
NPV : 102.884
Yield : 4.72354833
Yield->NPV : 102.884
Yield->NPV->Price : 103
Mod duration : 2.325360055
Convexity : 0.06725307785
PV 0.01 : 0.02392423439
Settlement date: August 11th, 2014
Test Price : 103
Accrued : -660
NPV : 102.934
Yield : 4.719277687
Yield->NPV : 102.934
Yield->NPV->Price : 103
Mod duration : 2.317320093
Convexity : 0.06684074058
PV 0.01 : 0.02385310264
*/
struct test_case {
Date settlementDate;
Real testPrice;
Real accruedAmount;
Real NPV;
Rate yield;
Real duration;
Real convexity;
};
Calendar calendar = Australia();
Natural settlementDays = 3;
Date issueDate(10, June, 2004);
Date startDate(15, February, 2004);
Date firstCouponDate(15, August, 2004);
Date maturityDate(15, February, 2017);
Rate coupon = 0.06;
Period tenor = 6*Months;
Period exCouponPeriod = 7*Days;
Compounding comp = Compounded;
Frequency freq = Semiannual;
DayCounter dc = ActualActual(ActualActual::ISMA);
FixedRateBond bond(settlementDays, 100.0,
Schedule(startDate, maturityDate, tenor,
NullCalendar(), Unadjusted, Unadjusted,
DateGeneration::Forward, true, firstCouponDate),
std::vector<Rate>(1, coupon),
dc, Unadjusted, 100.0,
issueDate, calendar, exCouponPeriod, NullCalendar());
const Leg& leg = bond.cashflows();
test_case cases[] = {
{ Date(7,August,2014), 103.0,
2.8670, 105.867, 0.04723,
2.26276, 6.54870 },
{ Date(8,August,2014), 103.0,
-0.1160, 102.884, 0.047235,
2.32536, 6.72531 },
{ Date(11,August,2014), 103.0,
-0.0660, 102.934, 0.04719,
2.31732, 6.68407 }
};
for (Size i=0; i<LENGTH(cases); ++i) {
Real accrued = bond.accruedAmount(cases[i].settlementDate);
ASSERT_CLOSE("accrued amount", cases[i].settlementDate,
accrued, cases[i].accruedAmount, 1e-3);
Real npv = cases[i].testPrice + accrued;
ASSERT_CLOSE("NPV", cases[i].settlementDate,
npv, cases[i].NPV, 1e-3);
Rate yield = CashFlows::yield(leg, npv, dc, comp, freq,
false, cases[i].settlementDate);
ASSERT_CLOSE("yield", cases[i].settlementDate,
yield, cases[i].yield, 1e-5);
Time duration = CashFlows::duration(leg, yield, dc, comp, freq,
Duration::Modified, false,
cases[i].settlementDate);
ASSERT_CLOSE("duration", cases[i].settlementDate,
duration, cases[i].duration, 1e-5);
Real convexity = CashFlows::convexity(leg, yield, dc, comp, freq,
false, cases[i].settlementDate);
ASSERT_CLOSE("convexity", cases[i].settlementDate,
convexity, cases[i].convexity, 1e-4);
Real calcnpv = CashFlows::npv(leg, yield, dc, comp, freq,
false, cases[i].settlementDate);
ASSERT_CLOSE("NPV from yield", cases[i].settlementDate,
calcnpv, cases[i].NPV, 1e-3);
Real calcprice = calcnpv - accrued;
ASSERT_CLOSE("price from yield", cases[i].settlementDate,
calcprice, cases[i].testPrice, 1e-3);
}
}
test_suite* BondTest::suite() {
test_suite* suite = BOOST_TEST_SUITE("Bond tests");
suite->add(QUANTLIB_TEST_CASE(&BondTest::testYield));
suite->add(QUANTLIB_TEST_CASE(&BondTest::testAtmRate));
suite->add(QUANTLIB_TEST_CASE(&BondTest::testZspread));
suite->add(QUANTLIB_TEST_CASE(&BondTest::testTheoretical));
suite->add(QUANTLIB_TEST_CASE(&BondTest::testCached));
suite->add(QUANTLIB_TEST_CASE(&BondTest::testCachedZero));
suite->add(QUANTLIB_TEST_CASE(&BondTest::testCachedFixed));
suite->add(QUANTLIB_TEST_CASE(&BondTest::testCachedFloating));
suite->add(QUANTLIB_TEST_CASE(&BondTest::testBrazilianCached));
suite->add(QUANTLIB_TEST_CASE(&BondTest::testExCouponGilt));
suite->add(QUANTLIB_TEST_CASE(&BondTest::testExCouponAustralianBond));
return suite;
}
|
/*************************************************************************/
/* animation_player_editor_plugin.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "animation_player_editor_plugin.h"
#include "io/resource_loader.h"
void AnimationPlayerEditor::_node_removed(Node *p_node) {
if (player && player == p_node) {
player=NULL;
hide();
set_process(false);
if (edit_anim->is_pressed()) {
editor->get_animation_editor()->set_animation(Ref<Animation>());
editor->get_animation_editor()->set_root(NULL);
editor->animation_editor_make_visible(false);
edit_anim->set_pressed(false);
}
}
}
void AnimationPlayerEditor::_input_event(InputEvent p_event) {
}
void AnimationPlayerEditor::_notification(int p_what) {
if (p_what==NOTIFICATION_PROCESS) {
if (!player)
return;
updating = true;
if (player->is_playing()) {
{
String animname=player->get_current_animation();
if (player->has_animation(animname)) {
Ref<Animation> anim = player->get_animation(animname);
if (!anim.is_null()) {
seek->set_max(anim->get_length());
}
}
}
seek->set_val(player->get_current_animation_pos());
if (edit_anim->is_pressed())
editor->get_animation_editor()->set_anim_pos(player->get_current_animation_pos());
EditorNode::get_singleton()->get_property_editor()->refresh();
} else if (last_active) {
//need the last frame after it stopped
seek->set_val(player->get_current_animation_pos());
}
last_active=player->is_playing();
//seek->set_val(player->get_pos());
updating = false;
}
if (p_what==NOTIFICATION_ENTER_TREE) {
editor->connect("hide_animation_player_editors",this,"_hide_anim_editors");
add_anim->set_icon( get_icon("New","EditorIcons") );
rename_anim->set_icon( get_icon("Rename","EditorIcons") );
duplicate_anim->set_icon( get_icon("Duplicate","EditorIcons") );
autoplay->set_icon( get_icon("AutoPlay","EditorIcons") );
load_anim->set_icon( get_icon("Folder","EditorIcons") );
remove_anim->set_icon( get_icon("Del","EditorIcons") );
edit_anim->set_icon( get_icon("Edit","EditorIcons") );
blend_anim->set_icon( get_icon("Blend","EditorIcons") );
play->set_icon( get_icon("Play","EditorIcons") );
autoplay_icon=get_icon("AutoPlay","EditorIcons");
stop->set_icon( get_icon("Stop","EditorIcons") );
resource_edit_anim->set_icon( get_icon("EditResource","EditorIcons") );
pin->set_normal_texture(get_icon("Pin","EditorIcons") );
pin->set_pressed_texture( get_icon("PinPressed","EditorIcons") );
blend_editor.next->connect("text_changed",this,"_blend_editor_next_changed");
/*
anim_editor_load->set_normal_texture( get_icon("AnimGet","EditorIcons"));
anim_editor_store->set_normal_texture( get_icon("AnimSet","EditorIcons"));
anim_editor_load->set_pressed_texture( get_icon("AnimGet","EditorIcons"));
anim_editor_store->set_pressed_texture( get_icon("AnimSet","EditorIcons"));
anim_editor_load->set_hover_texture( get_icon("AnimGetHl","EditorIcons"));
anim_editor_store->set_hover_texture( get_icon("AnimSetHl","EditorIcons"));
*/
}
if (p_what==NOTIFICATION_READY) {
get_tree()->connect("node_removed",this,"_node_removed");
}
if (p_what==NOTIFICATION_DRAW) {
}
}
void AnimationPlayerEditor::_autoplay_pressed() {
if (updating)
return;
if (animation->get_item_count()==0) {
return;
}
String current = animation->get_item_text( animation->get_selected() );
if (player->get_autoplay()==current) {
//unset
undo_redo->create_action("Toggle Autoplay");
undo_redo->add_do_method(player,"set_autoplay","");
undo_redo->add_undo_method(player,"set_autoplay",player->get_autoplay());
undo_redo->add_do_method(this,"_animation_player_changed",player);
undo_redo->add_undo_method(this,"_animation_player_changed",player);
undo_redo->commit_action();
} else {
//set
undo_redo->create_action("Toggle Autoplay");
undo_redo->add_do_method(player,"set_autoplay",current);
undo_redo->add_undo_method(player,"set_autoplay",player->get_autoplay());
undo_redo->add_do_method(this,"_animation_player_changed",player);
undo_redo->add_undo_method(this,"_animation_player_changed",player);
undo_redo->commit_action();
}
}
void AnimationPlayerEditor::_play_pressed() {
String current;
if (animation->get_selected()>=0 && animation->get_selected()<animation->get_item_count()) {
current = animation->get_item_text( animation->get_selected() );
}
if (current!="") {
if (current==player->get_current_animation())
player->stop(); //so it wont blend with itself
player->play(current );
}
//unstop
stop->set_pressed(false);
//unpause
//pause->set_pressed(false);
}
void AnimationPlayerEditor::_stop_pressed() {
player->stop();
play->set_pressed(false);
stop->set_pressed(true);
//pause->set_pressed(false);
//player->set_pause(false);
}
void AnimationPlayerEditor::_pause_pressed() {
//player->set_pause( pause->is_pressed() );
}
void AnimationPlayerEditor::_animation_selected(int p_which) {
if (updating)
return;
// when selecting an animation, the idea is that the only interesting behavior
// ui-wise is that it should play/blend the next one if currently playing
String current;
if (animation->get_selected()>=0 && animation->get_selected()<animation->get_item_count()) {
current = animation->get_item_text( animation->get_selected() );
}
if (current!="") {
player->set_current_animation( current );
Ref<Animation> anim = player->get_animation(current);
if (edit_anim->is_pressed()) {
Ref<Animation> anim = player->get_animation(current);
editor->get_animation_editor()->set_animation(anim);
Node *root = player->get_node(player->get_root());
if (root) {
editor->get_animation_editor()->set_root(root);
}
}
seek->set_max(anim->get_length());
} else {
if (edit_anim->is_pressed()) {
editor->get_animation_editor()->set_animation(Ref<Animation>());
editor->get_animation_editor()->set_root(NULL);
}
}
autoplay->set_pressed(current==player->get_autoplay());
}
void AnimationPlayerEditor::_animation_new() {
renaming=false;
name_title->set_text("New Animation Name:");
int count=1;
String base="New Anim";
while(true) {
String attempt = base;
if (count>1)
attempt+=" ("+itos(count)+")";
if (player->has_animation(attempt)) {
count++;
continue;
}
base=attempt;
break;
}
name->set_text(base);
name_dialog->popup_centered(Size2(300,90));
name->select_all();
name->grab_focus();
}
void AnimationPlayerEditor::_animation_rename() {
if (animation->get_item_count()==0)
return;
int selected = animation->get_selected();
String selected_name = animation->get_item_text(selected);
name_title->set_text("Change Animation Name:");
name->set_text(selected_name);
renaming=true;
name_dialog->popup_centered(Size2(300,90));
name->select_all();
name->grab_focus();
}
void AnimationPlayerEditor::_animation_load() {
ERR_FAIL_COND(!player);
file->set_mode( FileDialog::MODE_OPEN_FILE );
file->clear_filters();
List<String> extensions;
ResourceLoader::get_recognized_extensions_for_type("Animation",&extensions);
for (List<String>::Element *E=extensions.front();E;E=E->next()) {
file->add_filter("*."+E->get()+" ; "+E->get().to_upper() );
}
file->popup_centered_ratio();
}
void AnimationPlayerEditor::_animation_remove() {
if (animation->get_item_count()==0)
return;
String current = animation->get_item_text(animation->get_selected());
Ref<Animation> anim = player->get_animation(current);
undo_redo->create_action("Remove Animation");
undo_redo->add_do_method(player,"remove_animation",current);
undo_redo->add_undo_method(player,"add_animation",current,anim);
undo_redo->add_do_method(this,"_animation_player_changed",player);
undo_redo->add_undo_method(this,"_animation_player_changed",player);
undo_redo->commit_action();
}
void AnimationPlayerEditor::_select_anim_by_name(const String& p_anim) {
int idx=-1;
for(int i=0;i<animation->get_item_count();i++) {
if (animation->get_item_text(i)==p_anim) {
idx=i;
break;
}
}
ERR_FAIL_COND(idx==-1);
animation->select(idx);
_animation_selected(idx);
}
void AnimationPlayerEditor::_animation_name_edited() {
player->stop();
String new_name = name->get_text();
if (new_name=="" || new_name.find(":")!=-1 || new_name.find("/")!=-1) {
error_dialog->set_text("ERROR: Invalid animation name!");
error_dialog->popup_centered(Size2(300,70));
return;
}
if (renaming && animation->get_item_count()>0 && animation->get_item_text(animation->get_selected())==new_name) {
name_dialog->hide();
return;
}
if (player->has_animation(new_name)) {
error_dialog->set_text("ERROR: Animation Name Already Exists!");
error_dialog->popup_centered(Size2(300,70));
return;
}
if (renaming) {
String current = animation->get_item_text(animation->get_selected());
Ref<Animation> anim = player->get_animation(current);
undo_redo->create_action("Rename Animation");
undo_redo->add_do_method(player,"rename_animation",current,new_name);
undo_redo->add_do_method(anim.ptr(),"set_name",new_name);
undo_redo->add_undo_method(player,"rename_animation",new_name,current);
undo_redo->add_undo_method(anim.ptr(),"set_name",current);
undo_redo->add_do_method(this,"_animation_player_changed",player);
undo_redo->add_undo_method(this,"_animation_player_changed",player);
undo_redo->commit_action();
_select_anim_by_name(new_name);
} else {
Ref<Animation> new_anim = Ref<Animation>(memnew( Animation ));
new_anim->set_name(new_name);
undo_redo->create_action("Add Animation");
undo_redo->add_do_method(player,"add_animation",new_name,new_anim);
undo_redo->add_undo_method(player,"remove_animation",new_name);
undo_redo->add_do_method(this,"_animation_player_changed",player);
undo_redo->add_undo_method(this,"_animation_player_changed",player);
undo_redo->commit_action();
_select_anim_by_name(new_name);
}
name_dialog->hide();
}
void AnimationPlayerEditor::_blend_editor_next_changed(const String& p_string) {
if (animation->get_item_count()==0)
return;
String current = animation->get_item_text(animation->get_selected());
player->animation_set_next(current,p_string);
}
void AnimationPlayerEditor::_animation_blend() {
if (updating_blends)
return;
blend_editor.tree->clear();
if (animation->get_item_count()==0)
return;
String current = animation->get_item_text(animation->get_selected());
blend_editor.dialog->popup_centered(Size2(400,400));
blend_editor.tree->set_hide_root(true);
blend_editor.tree->set_column_min_width(0,10);
blend_editor.tree->set_column_min_width(1,3);
List<StringName> anims;
player->get_animation_list(&anims);
TreeItem *root = blend_editor.tree->create_item();
updating_blends=true;
for(List<StringName>::Element *E=anims.front();E;E=E->next()) {
String to=E->get();
TreeItem *blend=blend_editor.tree->create_item(root);
blend->set_editable(0,false);
blend->set_editable(1,true);
blend->set_text(0,to);
blend->set_cell_mode(1,TreeItem::CELL_MODE_RANGE);
blend->set_range_config(1,0,3600,0.001);
blend->set_range(1,player->get_blend_time(current,to));
}
blend_editor.next->set_text( player->animation_get_next(current) );
updating_blends=false;
}
void AnimationPlayerEditor::_blend_edited() {
if (updating_blends)
return;
if (animation->get_item_count()==0)
return;
String current = animation->get_item_text(animation->get_selected());
TreeItem *selected = blend_editor.tree->get_edited();
if (!selected)
return;
updating_blends=true;
String to=selected->get_text(0);
float blend_time = selected->get_range(1);
float prev_blend_time = player->get_blend_time(current,to);
undo_redo->create_action("Change Blend Time");
undo_redo->add_do_method(player,"set_blend_time",current,to,blend_time);
undo_redo->add_undo_method(player,"set_blend_time",current,to,prev_blend_time);
undo_redo->add_do_method(this,"_animation_player_changed",player);
undo_redo->add_undo_method(this,"_animation_player_changed",player);
undo_redo->commit_action();
updating_blends=false;
}
void AnimationPlayerEditor::ensure_visibility() {
_animation_edit();
}
void AnimationPlayerEditor::_animation_resource_edit() {
if (animation->get_item_count()) {
String current = animation->get_item_text(animation->get_selected());
Ref<Animation> anim = player->get_animation(current);
editor->edit_resource(anim);
}
}
void AnimationPlayerEditor::_animation_edit() {
// if (animation->get_item_count()==0)
// return;
if (edit_anim->is_pressed()) {
editor->animation_editor_make_visible(true);
//editor->get_animation_editor()->set_root(player->get_roo); - get root pending
if (animation->get_item_count()) {
String current = animation->get_item_text(animation->get_selected());
Ref<Animation> anim = player->get_animation(current);
editor->get_animation_editor()->set_animation(anim);
Node *root = player->get_node(player->get_root());
if (root) {
editor->get_animation_editor()->set_root(root);
}
} else {
editor->get_animation_editor()->set_animation(Ref<Animation>());
editor->get_animation_editor()->set_root(NULL);
}
} else {
editor->animation_editor_make_visible(false);
editor->get_animation_editor()->set_animation(Ref<Animation>());
editor->get_animation_editor()->set_root(NULL);
}
//get_scene()->get_root_node()->call("_resource_selected",anim,"");
}
void AnimationPlayerEditor::_file_selected(String p_file) {
ERR_FAIL_COND(!player);
Ref<Resource> res = ResourceLoader::load(p_file,"Animation");
ERR_FAIL_COND(res.is_null());
ERR_FAIL_COND( !res->is_type("Animation") );
if (p_file.find_last("/")!=-1) {
p_file=p_file.substr( p_file.find_last("/")+1, p_file.length() );
}
if (p_file.find_last("\\")!=-1) {
p_file=p_file.substr( p_file.find_last("\\")+1, p_file.length() );
}
if (p_file.find(".")!=-1)
p_file=p_file.substr(0,p_file.find("."));
undo_redo->create_action("Load Animation");
undo_redo->add_do_method(player,"add_animation",p_file,res);
undo_redo->add_undo_method(player,"remove_animation",p_file);
if (player->has_animation(p_file)) {
undo_redo->add_undo_method(player,"add_animation",p_file,player->get_animation(p_file));
}
undo_redo->add_do_method(this,"_animation_player_changed",player);
undo_redo->add_undo_method(this,"_animation_player_changed",player);
undo_redo->commit_action();
}
void AnimationPlayerEditor::_scale_changed(const String& p_scale) {
player->set_speed(p_scale.to_double());
}
void AnimationPlayerEditor::_update_animation() {
// the purpose of _update_animation is to reflect the current state
// of the animation player in the current editor..
updating=true;
if (player->is_playing()) {
play->set_pressed(true);
stop->set_pressed(false);
} else {
play->set_pressed(false);
stop->set_pressed(true);
}
scale->set_text( String::num(player->get_speed(),2) );
String current=player->get_current_animation();
for (int i=0;i<animation->get_item_count();i++) {
if (animation->get_item_text(i)==current) {
animation->select(i);
break;
}
}
updating=false;
}
void AnimationPlayerEditor::_update_player() {
if (!player)
return;
updating=true;
List<StringName> animlist;
player->get_animation_list(&animlist);
animation->clear();
nodename->set_text(player->get_name());
stop->set_disabled(animlist.size()==0);
play->set_disabled(animlist.size()==0);
autoplay->set_disabled(animlist.size()==0);
duplicate_anim->set_disabled(animlist.size()==0);
rename_anim->set_disabled(animlist.size()==0);
blend_anim->set_disabled(animlist.size()==0);
remove_anim->set_disabled(animlist.size()==0);
resource_edit_anim->set_disabled(animlist.size()==0);
int active_idx=-1;
for (List<StringName>::Element *E=animlist.front();E;E=E->next()) {
if (player->get_autoplay()==E->get())
animation->add_icon_item(autoplay_icon,E->get());
else
animation->add_item(E->get());
if (player->get_current_animation()==E->get())
active_idx=animation->get_item_count()-1;
}
updating=false;
if (active_idx!=-1) {
animation->select(active_idx);
autoplay->set_pressed(animation->get_item_text(active_idx)==player->get_autoplay());
_animation_selected(active_idx);
} else if (animation->get_item_count()>0){
animation->select(0);
autoplay->set_pressed(animation->get_item_text(0)==player->get_autoplay());
_animation_selected(0);
}
//pause->set_pressed(player->is_paused());
if (edit_anim->is_pressed()) {
if (animation->get_item_count()) {
String current = animation->get_item_text(animation->get_selected());
Ref<Animation> anim = player->get_animation(current);
editor->get_animation_editor()->set_animation(anim);
Node *root = player->get_node(player->get_root());
if (root) {
editor->get_animation_editor()->set_root(root);
}
}
}
_update_animation();
}
void AnimationPlayerEditor::edit(AnimationPlayer *p_player) {
if (player && pin->is_pressed())
return; //ignore, pinned
player=p_player;
if (player)
_update_player();
else {
// hide();
}
}
void AnimationPlayerEditor::_animation_duplicate() {
if (!animation->get_item_count())
return;
String current = animation->get_item_text(animation->get_selected());
Ref<Animation> anim = player->get_animation(current);
if (!anim.is_valid())
return;
Ref<Animation> new_anim = memnew( Animation );
List<PropertyInfo> plist;
anim->get_property_list(&plist);
for (List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) {
if (E->get().usage&PROPERTY_USAGE_STORAGE) {
new_anim->set(E->get().name, anim->get(E->get().name));
}
}
new_anim->set_path("");
String new_name = current;
while(player->has_animation(new_name)) {
new_name=new_name+" (copy)";
}
undo_redo->create_action("Duplicate Animation");
undo_redo->add_do_method(player,"add_animation",new_name,new_anim);
undo_redo->add_undo_method(player,"remove_animation",new_name);
undo_redo->add_do_method(this,"_animation_player_changed",player);
undo_redo->add_undo_method(this,"_animation_player_changed",player);
undo_redo->commit_action();
for(int i=0;i<animation->get_item_count();i++) {
if (animation->get_item_text(i)==new_name) {
animation->select(i);
_animation_selected(i);
return;
}
}
}
void AnimationPlayerEditor::_seek_value_changed(float p_value) {
if (updating || !player || player->is_playing()) {
return;
};
updating=true;
String current=player->get_current_animation(); //animation->get_item_text( animation->get_selected() );
if (current == "" || !player->has_animation(current)) {
updating=false;
current="";
return;
};
Ref<Animation> anim;
anim=player->get_animation(current);
float pos = anim->get_length() * (p_value / seek->get_max());
if (player->is_valid()) {
float cpos = player->get_current_animation_pos();
player->seek_delta(pos,pos-cpos);
} else {
player->seek(pos,true);
}
if (edit_anim->is_pressed())
editor->get_animation_editor()->set_anim_pos(pos);
updating=true;
};
void AnimationPlayerEditor::_animation_player_changed(Object *p_pl) {
if (player==p_pl && is_visible()) {
_update_player();
if (blend_editor.dialog->is_visible())
_animation_blend(); //update
}
}
void AnimationPlayerEditor::_list_changed() {
if(is_visible())
_update_player();
}
#if 0
void AnimationPlayerEditor::_editor_store() {
if (animation->get_item_count()==0)
return;
String current = animation->get_item_text(animation->get_selected());
Ref<Animation> anim = player->get_animation(current);
if (editor->get_animation_editor()->get_current_animation()==anim)
return; //already there
undo_redo->create_action("Store anim in editor");
undo_redo->add_do_method(editor->get_animation_editor(),"set_animation",anim);
undo_redo->add_undo_method(editor->get_animation_editor(),"remove_animation",anim);
undo_redo->commit_action();
}
void AnimationPlayerEditor::_editor_load(){
Ref<Animation> anim = editor->get_animation_editor()->get_current_animation();
if (anim.is_null())
return;
String existing = player->find_animation(anim);
if (existing!="") {
_select_anim_by_name(existing);
return; //already has
}
int count=1;
String base=anim->get_name();
bool noname=false;
if (base=="") {
base="New Anim";
noname=true;
}
while(true) {
String attempt = base;
if (count>1)
attempt+=" ("+itos(count)+")";
if (player->has_animation(attempt)) {
count++;
continue;
}
base=attempt;
break;
}
if (noname)
anim->set_name(base);
undo_redo->create_action("Add Animation From Editor");
undo_redo->add_do_method(player,"add_animation",base,anim);
undo_redo->add_undo_method(player,"remove_animation",base);
undo_redo->add_do_method(this,"_animation_player_changed",player);
undo_redo->add_undo_method(this,"_animation_player_changed",player);
undo_redo->commit_action();
_select_anim_by_name(base);
}
#endif
void AnimationPlayerEditor::_animation_key_editor_anim_len_changed(float p_len) {
seek->set_max(p_len);
}
void AnimationPlayerEditor::_animation_key_editor_seek(float p_pos) {
if (!is_visible())
return;
if (!player)
return;
if (player->is_playing() )
return;
seek->set_val(p_pos);
EditorNode::get_singleton()->get_property_editor()->refresh();
//seekit
}
void AnimationPlayerEditor::_hide_anim_editors() {
player=NULL;
hide();
set_process(false);
if (edit_anim->is_pressed()) {
editor->get_animation_editor()->set_animation(Ref<Animation>());
editor->get_animation_editor()->set_root(NULL);
editor->animation_editor_make_visible(false);
edit_anim->set_pressed(false);
}
}
void AnimationPlayerEditor::_bind_methods() {
ObjectTypeDB::bind_method(_MD("_input_event"),&AnimationPlayerEditor::_input_event);
ObjectTypeDB::bind_method(_MD("_node_removed"),&AnimationPlayerEditor::_node_removed);
ObjectTypeDB::bind_method(_MD("_play_pressed"),&AnimationPlayerEditor::_play_pressed);
ObjectTypeDB::bind_method(_MD("_stop_pressed"),&AnimationPlayerEditor::_stop_pressed);
ObjectTypeDB::bind_method(_MD("_autoplay_pressed"),&AnimationPlayerEditor::_autoplay_pressed);
ObjectTypeDB::bind_method(_MD("_pause_pressed"),&AnimationPlayerEditor::_pause_pressed);
ObjectTypeDB::bind_method(_MD("_animation_selected"),&AnimationPlayerEditor::_animation_selected);
ObjectTypeDB::bind_method(_MD("_animation_name_edited"),&AnimationPlayerEditor::_animation_name_edited);
ObjectTypeDB::bind_method(_MD("_animation_new"),&AnimationPlayerEditor::_animation_new);
ObjectTypeDB::bind_method(_MD("_animation_rename"),&AnimationPlayerEditor::_animation_rename);
ObjectTypeDB::bind_method(_MD("_animation_load"),&AnimationPlayerEditor::_animation_load);
ObjectTypeDB::bind_method(_MD("_animation_remove"),&AnimationPlayerEditor::_animation_remove);
ObjectTypeDB::bind_method(_MD("_animation_blend"),&AnimationPlayerEditor::_animation_blend);
ObjectTypeDB::bind_method(_MD("_animation_edit"),&AnimationPlayerEditor::_animation_edit);
ObjectTypeDB::bind_method(_MD("_animation_resource_edit"),&AnimationPlayerEditor::_animation_resource_edit);
ObjectTypeDB::bind_method(_MD("_file_selected"),&AnimationPlayerEditor::_file_selected);
ObjectTypeDB::bind_method(_MD("_seek_value_changed"),&AnimationPlayerEditor::_seek_value_changed);
ObjectTypeDB::bind_method(_MD("_animation_player_changed"),&AnimationPlayerEditor::_animation_player_changed);
ObjectTypeDB::bind_method(_MD("_blend_edited"),&AnimationPlayerEditor::_blend_edited);
// ObjectTypeDB::bind_method(_MD("_seek_frame_changed"),&AnimationPlayerEditor::_seek_frame_changed);
ObjectTypeDB::bind_method(_MD("_scale_changed"),&AnimationPlayerEditor::_scale_changed);
//ObjectTypeDB::bind_method(_MD("_editor_store_all"),&AnimationPlayerEditor::_editor_store_all);
///jectTypeDB::bind_method(_MD("_editor_load_all"),&AnimationPlayerEditor::_editor_load_all);
ObjectTypeDB::bind_method(_MD("_list_changed"),&AnimationPlayerEditor::_list_changed);
ObjectTypeDB::bind_method(_MD("_animation_key_editor_seek"),&AnimationPlayerEditor::_animation_key_editor_seek);
ObjectTypeDB::bind_method(_MD("_animation_key_editor_anim_len_changed"),&AnimationPlayerEditor::_animation_key_editor_anim_len_changed);
ObjectTypeDB::bind_method(_MD("_hide_anim_editors"),&AnimationPlayerEditor::_hide_anim_editors);
ObjectTypeDB::bind_method(_MD("_animation_duplicate"),&AnimationPlayerEditor::_animation_duplicate);
ObjectTypeDB::bind_method(_MD("_blend_editor_next_changed"),&AnimationPlayerEditor::_blend_editor_next_changed);
}
AnimationPlayerEditor::AnimationPlayerEditor(EditorNode *p_editor) {
editor=p_editor;
updating=false;
set_focus_mode(FOCUS_ALL);
player=NULL;
add_style_override("panel", get_stylebox("panel","Panel"));
Label * l;
/*l= memnew( Label );
l->set_text("Animation Player:");
add_child(l);*/
HBoxContainer *hb = memnew( HBoxContainer );
add_child(hb);
add_anim = memnew( Button );
add_anim->set_tooltip("Create new animation in player.");
hb->add_child(add_anim);
load_anim = memnew( Button );
load_anim->set_tooltip("Load an animation from disk.");
hb->add_child(load_anim);
duplicate_anim = memnew( Button );
hb->add_child(duplicate_anim);
duplicate_anim->set_tooltip("Duplicate Animation");
animation = memnew( OptionButton );
hb->add_child(animation);
animation->set_h_size_flags(SIZE_EXPAND_FILL);
animation->set_tooltip("Display list of animations in player.");
autoplay = memnew( Button );
hb->add_child(autoplay);
autoplay->set_tooltip("Autoplay On Load");
rename_anim = memnew( Button );
hb->add_child(rename_anim);
rename_anim->set_tooltip("Rename Animation");
remove_anim = memnew( Button );
hb->add_child(remove_anim);
remove_anim->set_tooltip("Remove Animation");
blend_anim = memnew( Button );
hb->add_child(blend_anim);
blend_anim->set_tooltip("Edit Target Blend Times");
edit_anim = memnew( Button );
edit_anim->set_toggle_mode(true);
hb->add_child(edit_anim);
edit_anim->set_tooltip("Open animation editor.\nProperty editor will displays all editable keys too.");
hb = memnew (HBoxContainer);
add_child(hb);
play = memnew( Button );
play->set_tooltip("Play selected animation.");
hb->add_child(play);
stop = memnew( Button );
stop->set_toggle_mode(true);
hb->add_child(stop);
play->set_tooltip("Stop animation playback.");
//pause = memnew( Button );
//pause->set_toggle_mode(true);
//hb->add_child(pause);
seek = memnew( HSlider );
seek->set_val(0);
seek->set_step(0.01);
hb->add_child(seek);
seek->set_h_size_flags(SIZE_EXPAND_FILL);
seek->set_stretch_ratio(8);
seek->set_tooltip("Seek animation (when stopped).");
frame = memnew( SpinBox );
hb->add_child(frame);
frame->set_h_size_flags(SIZE_EXPAND_FILL);
frame->set_stretch_ratio(2);
frame->set_tooltip("Animation position (in seconds).");
seek->share(frame);
scale = memnew( LineEdit );
hb->add_child(scale);
scale->set_h_size_flags(SIZE_EXPAND_FILL);
scale->set_stretch_ratio(1);
scale->set_tooltip("Scale animation playback globally for the node.");
scale->hide();
resource_edit_anim= memnew( Button );
hb->add_child(resource_edit_anim);
file = memnew(FileDialog);
add_child(file);
name_dialog = memnew( ConfirmationDialog );
name_dialog->set_hide_on_ok(false);
add_child(name_dialog);
name = memnew( LineEdit );
name_dialog->add_child(name);
name->set_pos(Point2(18,30));
name->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END,10);
name_dialog->register_text_enter(name);
l = memnew( Label );
l->set_text("Animation Name:");
l->set_pos( Point2(10,10) );
name_dialog->add_child(l);
name_title=l;
error_dialog = memnew( ConfirmationDialog );
error_dialog->get_ok()->set_text("Close");
//error_dialog->get_cancel()->set_text("Close");
error_dialog->set_text("Error!");
add_child(error_dialog);
name_dialog->connect("confirmed", this,"_animation_name_edited");
blend_editor.dialog = memnew( AcceptDialog );
add_child(blend_editor.dialog);
blend_editor.dialog->get_ok()->set_text("Close");
blend_editor.dialog->set_hide_on_ok(true);
VBoxContainer *blend_vb = memnew( VBoxContainer);
blend_editor.dialog->add_child(blend_vb);
blend_editor.dialog->set_child_rect(blend_vb);
blend_editor.tree = memnew( Tree );
blend_editor.tree->set_columns(2);
blend_vb->add_margin_child("Blend Times: ",blend_editor.tree,true);
blend_editor.next = memnew( LineEdit );
blend_vb->add_margin_child("Next (Auto Queue):",blend_editor.next);
blend_editor.dialog->set_title("Cross-Animation Blend Times");
updating_blends=false;
blend_editor.tree->connect("item_edited",this,"_blend_edited");
autoplay->connect("pressed", this,"_autoplay_pressed");
autoplay->set_toggle_mode(true);
play->connect("pressed", this,"_play_pressed");
stop->connect("pressed", this,"_stop_pressed");
//pause->connect("pressed", this,"_pause_pressed");
add_anim->connect("pressed", this,"_animation_new");
rename_anim->connect("pressed", this,"_animation_rename");
load_anim->connect("pressed", this,"_animation_load");
duplicate_anim->connect("pressed", this,"_animation_duplicate");
//frame->connect("text_entered", this,"_seek_frame_changed");
edit_anim->connect("pressed", this,"_animation_edit");
blend_anim->connect("pressed", this,"_animation_blend");
remove_anim->connect("pressed", this,"_animation_remove");
animation->connect("item_selected", this,"_animation_selected",Vector<Variant>(),true);
resource_edit_anim->connect("pressed", this,"_animation_resource_edit");
file->connect("file_selected", this,"_file_selected");
seek->connect("value_changed", this, "_seek_value_changed",Vector<Variant>(),true);
scale->connect("text_entered", this, "_scale_changed",Vector<Variant>(),true);
editor->get_animation_editor()->connect("timeline_changed",this,"_animation_key_editor_seek");
editor->get_animation_editor()->connect("animation_len_changed",this,"_animation_key_editor_anim_len_changed");
HBoxContainer *ahb = editor->get_animation_panel_hb();
nodename = memnew( Label );
ahb->add_child(nodename);
nodename->set_h_size_flags(SIZE_EXPAND_FILL);
nodename->set_opacity(0.5);
pin = memnew( TextureButton );
pin->set_toggle_mode(true);
ahb->add_child(pin);
renaming=false;
last_active=false;
}
void AnimationPlayerEditorPlugin::edit(Object *p_object) {
anim_editor->set_undo_redo(&get_undo_redo());
if (!p_object)
return;
anim_editor->edit(p_object->cast_to<AnimationPlayer>());
}
bool AnimationPlayerEditorPlugin::handles(Object *p_object) const {
return p_object->is_type("AnimationPlayer");
}
void AnimationPlayerEditorPlugin::make_visible(bool p_visible) {
if (p_visible) {
anim_editor->show();
anim_editor->set_process(true);
anim_editor->ensure_visibility();
editor->animation_panel_make_visible(true);
} else {
// anim_editor->hide();
// anim_editor->set_idle_process(false);
}
}
AnimationPlayerEditorPlugin::AnimationPlayerEditorPlugin(EditorNode *p_node) {
editor=p_node;
anim_editor = memnew( AnimationPlayerEditor(editor) );
editor->get_animation_panel()->add_child(anim_editor);
/*
editor->get_viewport()->add_child(anim_editor);
anim_editor->set_area_as_parent_rect();
anim_editor->set_anchor( MARGIN_TOP, Control::ANCHOR_END);
anim_editor->set_margin( MARGIN_TOP, 75 );
anim_editor->set_anchor( MARGIN_RIGHT, Control::ANCHOR_END);
anim_editor->set_margin( MARGIN_RIGHT, 0 );*/
anim_editor->hide();
}
AnimationPlayerEditorPlugin::~AnimationPlayerEditorPlugin()
{
}
|
// C11 standard
// created by cicek on Feb 06, 2021 3:09 PM
#include <iostream>
#include <string>
using namespace std;
class Mother {
public:
Mother() {};
void sayHi() {
cout << "Hi";
}
};
// This syntax derives the Daughter class from the Mother class.
class Daughter : public Mother {
public:
Daughter() {};
};
/*
* The Base class is specified using a colon and an access specifier public means,
* that all public members of the base class are public in the derived class.
* In other words, all public members of the Mother class become public members of the Daughter class.
*/
/*
* A derived class inherits all base class methods with the following exceptions:
- Constructors, destructors
- Overloaded operators
- The friend functions
*/
/*
* A class can be derived from multiple classes by specifying the base classes in a comma-separated list.
* For example: class Daughter: public Mother, public Father
*/
int main(int argc, char **argv) {
/*
* Inheritance allows us to define a class based on another class.
* This facilitates greater ease in creating and maintaining an application.
The class whose properties are inherited by another class is called the Base class.
The class which inherits the properties is called the Derived class. For example,
the Daughter class (derived) can be inherited from the Mother class (base).
The derived class inherits all feature from the base class, and can have its own additional features.
The idea of inheritance implements the is a relationship.
For example, mammal IS-A animal, dog IS-A mammal, hence dog IS-A animal as well.
*/
Daughter d;
d.sayHi();
return 0;
}
|
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include <algorithm>
#include <atomic>
#include <fstream>
#include <iostream>
#include <iterator>
#include <memory>
#include <folly/Demangle.h>
#include <folly/Format.h>
#include <folly/Hash.h>
#include <folly/Memory.h>
#include <folly/Singleton.h>
#include <folly/String.h>
#include <folly/container/F14Map.h>
#include <folly/container/F14Set.h>
#include <boost/program_options.hpp>
#include <boost/variant.hpp>
#include <tbb/concurrent_unordered_map.h>
#include <tbb/concurrent_vector.h>
#include "hphp/tools/debug-parser/debug-parser.h"
#include "hphp/util/assertions.h"
#include "hphp/util/file.h"
#include "hphp/util/type-scan.h"
/*
* Program responsible for taking the parsed debug-information from TypeParser,
* analyzing it (along with user-provided annotations), and generating C++ code
* for GC type-scanners. These type-scanners will then be compiled into a shared
* object which can be loaded at start-up if GC is enabled.
*
* Some general concepts:
*
* - "Scanner". A scanner is responsible for reporting pointer information about
* a set of types to the GC. Generally it will report a list of pointers to
* other potentially interesting types, as well as address ranges that should
* be conservatively scanned.
*
* - "Collectable". A type is collectable if MarkCollectable<> or
* MarkScannableCollectable<> is instantiated on it. Type-scanners are never
* generated for collectable types, it is assumed their scanners will be
* hand-written. The exception is if MarkScannableCollectable<> is used, in
* which case they'll be scanned if explicitly requested. The point of the
* type-scanners is to determine how to find pointers to collectable types
* from other types. Collectable types correspond to the set of types in HHVM
* which are explicitly managed by the GC.
*
* - "Indexed". An indexed type is a combination of a type and an action. These
* occur from an instantiation of Indexer<>. Any particular type can be part
* of multiple indexed types but with different actions. Every indexed type
* receives a unique type-index and will have a scanner generated for
* it. Belonging to an indexed type generally marks that the type is allocated
* on the req-heap (with one exception). The action influences the behavior of
* that particular scanner. They are:
*
* (*) Ignore -- Scanner is trivial.
* (*) Auto -- The default. Attempt to generate scanner automatically.
* (*) Conservative<T...> -- If any of T... is "interesting" (see below),
* conservative scan. Otherwise, ignore.
* If T... is an empty list, always
* conservative scan.
* (*) WithSuffix<T> -- Attempt to generate scanner for type as normal.
* However, any allocation of the type only contains
* one instance of that type. Any remaining
* allocated memory is assumed to be filled with
* instances of T. So, a scanner for T will be
* generated as well.
* (*) ForScan -- Similar to Auto, but this type should not be marked as
* "pointer followable" (see below) if this is the only
* indexed type for the type. (This is a marker that the
* type is never actually req-heap allocated).
*
* - "Interesting". A type is interesting if the scanner generated for it would
* be non-trivial. IE, it would have at least one action. Interesting
* types either contain interesting types, pointers to "pointer
* followable" types, or have some custom action defined on it.
*
* - "Pointer followable". A type is pointer followable if it is a collectable
* type, it has a collectable type as a base, or if it is a member of at least
* one indexed type which has an action which is not "ForScan" and is
* interesting. By these conditions, a pointer followable type is one which is
* known to be allocated out of the request heap, and transitively leads to a
* collectable type via some chain of pointers. Pointers to pointer followable
* types are enqueued inside scanners. Pointers to non-pointer followable
* types are ignored. All base classes of pointer followable object types are
* also pointer followable (to handle polymorphism).
*
* - "Layout". Abstract description of a scanner. A layout contains a list of
* offsets and actions to perform at those offsets. Since many types have
* similar structure, multiple types can share the same layout.
*
* The goal of the scanner generator is find the maximal set of pointer
* followable types, use those to compute the layout of each indexed type, then
* output those layouts in the form of C++ code.
*
* Note: this entire scheme assumes that all pointer followable types can be
* reached via some indexed type. If not, that pointer followable type is a
* root, and must be dealt with specially by the GC.
*/
namespace {
// fast_map/set maps to F14{Value,Vector}Map/Set depending on K+V size.
// Entries are moved (if possible) or copied (if necessary) on rehash & erase.
template<class K, class V, class H=std::hash<K>, class C=std::equal_to<K>>
using fast_map = folly::F14FastMap<K,V,H,C>;
template<class T, class H=std::hash<T>, class C=std::equal_to<T>>
using fast_set = folly::F14FastSet<T,H,C>;
// node_map/set allocate K+V separately like std::unordered_map; K+V don't
// move during rehash. Saves memory compared to fast_map/set when when K+V
// is large.
template<class K, class V, class H=std::hash<K>, class C=std::equal_to<K>>
using node_map = folly::F14NodeMap<K,V,H,C>;
template<class T, class H=std::hash<T>, class C=std::equal_to<T>>
using node_set = folly::F14NodeSet<T,H,C>;
////////////////////////////////////////////////////////////////////////////////
using namespace debug_parser;
struct Generator {
private:
struct IndexedType;
struct Layout;
struct LayoutError;
// Action is a description of any special behavior an object type needs when
// generating a scanner for it. It abstracts away how this behavior is
// communicated within the generator.
struct Action {
// Ignore everything, a trivial scanner
bool ignore_all = false;
// Conservative scan everything (not including bases)
bool conservative_all = false;
// Conservative scan all bases
bool conservative_all_bases = false;
// This type should be ignored (used for system types we can't modify). This
// is different from ignore_all where ignore_all will still process base
// classes as normal, but whitelisted will not process anything, even base
// classes.
bool whitelisted = false;
// This type is a template which should not be instantiated on any req
// allocated types.
bool forbidden_template = false;
// Symbol of the custom scanner function which handles the entire type. If
// present, but empty, the scanner does not have linkage (which is an
// error).
folly::Optional<std::string> custom_all;
// Symbol of the custom scanner function which handles scanning base
// classes. If present, but empty, the scanner does not have linkage (which
// is an error).
folly::Optional<std::string> custom_bases_scanner;
// If non-empty, the name of the field in the object which is a "flexible
// array" member (a trailing array of unbound size). Each object can only
// have one of these.
std::string flexible_array_field;
// If a custom scanner for the object type is specified, it will only be
// invoked if any of the types in the custom guards list is interesting. If
// the list is empty, the custom scanner is always invoked.
fast_set<const Type*> custom_guards;
// List of fields in the object which should be ignored.
fast_set<std::string> ignore_fields;
// List of fields in the object which should always be conservative scanned.
fast_set<std::string> conservative_fields;
// Map of field names to symbols of custom scanners for that field.
fast_map<std::string, std::string> custom_fields;
// List of immediate base classes which should be ignored.
fast_set<const Object*> ignored_bases;
// List of immediate bases which the "forbidden template" check should not
// be applied to. Mainly used internally.
fast_set<const Object*> silenced_bases;
// If a custom scanner function for bases is specified, the list of
// immediate bases which the scanner applies to.
fast_set<const Object*> custom_bases;
// For certain actions it can immediately be known that its associated
// object will always be interesting. Therefore, any indexed type with such
// an action can immediately be marked as pointer followable, which helps us
// reach a fixed point faster. This is only an optimization, so the criteria
// does not need to be exact.
bool isAlwaysNonTrivial() const {
return !ignore_all && !whitelisted && (
conservative_all || conservative_all_bases ||
(custom_all && custom_guards.empty()) ||
(custom_bases_scanner && !custom_bases.empty()) ||
!conservative_fields.empty() || !custom_fields.empty());
}
};
struct ObjectNameHasher {
size_t operator()(const ObjectTypeName& name) const {
return folly::Hash()(name.name, name.linkage);
}
};
struct ObjectNameEquals {
bool operator()(const ObjectTypeName& n1,
const ObjectTypeName& n2) const {
return std::tie(n1.name, n1.linkage) ==
std::tie(n2.name, n2.linkage);
}
};
// For initializing type indices, we can use either the symbol name of the
// Indexer<> instantiation (preferred), or its raw memory address. We have to
// use the raw memory address for Indexer<> instantiations which do not have
// external linkage.
using Address = boost::variant<std::string, uintptr_t>;
public:
// Parse out all the debug information out of the specified file and do the
// analysis generating the layouts.
explicit Generator(const std::string&, bool skip);
// Turn the layouts into C++ code, writing to the specified ostream.
void operator()(std::ostream&) const;
private:
static bool isTemplateName(const std::string& candidate,
const std::string& name);
static bool isMarkCollectableName(const std::string&);
static bool isMarkScannableCollectableName(const std::string&);
static bool isIndexerName(const std::string&);
static bool isConservativeActionName(const std::string&);
static bool isWithSuffixActionName(const std::string&);
static std::string splitFieldName(const std::string& input,
const std::string& prefix);
static const Type& stripModifiers(const Type&);
static int compareTypes(const Type&, const Type&);
static int compareIndexedTypes(const IndexedType&,
const IndexedType&,
bool for_merge = false);
static void sanityCheckTemplateParams(const Object&);
bool findMemberHelper(const std::string& field, const Object &a_object) const;
void genAllLayouts();
void checkForLayoutErrors() const;
void assignUniqueLayouts();
template <typename T, typename F, typename C> T extractFromMarkers(
const C&, F&&
) const;
size_t determineSize(const Type&) const;
const Object& getObject(const ObjectType&) const;
const Object& getMarkedCollectable(const Object&) const;
void genLayout(const Type&, Layout&, size_t,
bool conservative_everything = false) const;
void genLayout(const Object&, Layout&, size_t,
bool do_forbidden_check = true,
bool conservative_everything = false) const;
bool checkMemberSpecialAction(const Object& base_object,
const Object::Member& member,
const Action& action,
Layout& layout,
size_t base_obj_offset,
size_t offset) const;
IndexedType getIndexedType(const Object&) const;
template <typename C>
std::vector<IndexedType> getIndexedTypes(const C&) const;
std::vector<IndexedType> mergeDupIndexedTypes(
std::vector<Generator::IndexedType>
) const;
bool hasCollectableBase(const Object& object) const;
bool forbiddenTemplateCheck(const Type& type) const;
bool forbiddenTemplateCheck(const Object& object) const;
bool hasEmptyLayout(const Type& type) const;
bool hasEmptyLayout(const Object& object) const;
bool isPtrFollowable(const Type& type) const;
bool isPtrFollowable(const Object& object) const {
return m_ptr_followable.find(&object) != m_ptr_followable.end();
}
void makePtrFollowable(const Type& type);
void makePtrFollowable(const Object& object);
const Action& getAction(const Object& object,
bool conservative_everything = false) const;
Action inferAction(const Object& object,
bool conservative_everything = false) const;
void genMetrics(std::ostream&) const;
void genForwardDecls(std::ostream&) const;
void genDataTable(std::ostream&) const;
void genIndexInit(std::ostream&) const;
void genScannerFuncs(std::ostream&) const;
void genBuiltinScannerFuncs(std::ostream&) const;
void genScannerFunc(std::ostream&,
const Layout&,
size_t begin_offset = 0) const;
std::unique_ptr<TypeParser> m_parser;
/*
* Maps manipulated by getObject(). These index the known object types in
* various ways to allow for the proper lookup of an object type according to
* its linkage. They also allow that getObject() will always return the same
* Object& for the same type, even if the object types' keys are different,
* which means we can use pointer equality to compare types.
*
* They are marked mutable so that getObject() can remain const.
*/
mutable tbb::concurrent_unordered_map<
ObjectTypeName,
tbb::concurrent_vector<ObjectTypeKey>,
ObjectNameHasher,
ObjectNameEquals
> m_objects_by_name;
mutable node_map<
std::string,
Object
> m_external_objects;
mutable node_map<
CompileUnitId,
node_map<
std::string,
Object
>
> m_internal_objects;
mutable node_map<
ObjectTypeId,
Object
> m_unique_objects;
// Mapping of object types to their computed actions. We could compute the
// action everytime we needed it, but they're stored in this table for
// memoization. This table is mutable as well since its a cache.
mutable node_map<const Object*, Action> m_actions; // XXX must be node
// List of all indexed types in the debug information.
std::vector<IndexedType> m_indexed_types;
// Set of all types which are currently known to be pointer followable or
// collectable. The collectable set is set once, and should never change,
// while the pointer followable set can grow as more pointer followable types
// are discovered (it must grow monotonically, never removing anything).
fast_set<const Object*> m_ptr_followable;
fast_set<const Object*> m_collectable;
fast_set<const Object*> m_scannable_collectable;
// List of all layouts. Once computed, the indexed types will have an index
// into this table for its associated layout.
std::vector<Layout> m_layouts;
// Set of objects whose layout is currently being generated. Used to detect
// possible infinite recursion.
mutable fast_set<const Object*> m_layout_being_generated;
// Static strings used to identify certain special types in the debug info,
// which serve as markers for special actions. These strings should stay in
// sync with the types in type-scan.h.
static constexpr const char* const s_mark_collectable_name =
"HPHP::type_scan::MarkCollectable";
static constexpr const char* const s_mark_scannable_collectable_name =
"HPHP::type_scan::MarkScannableCollectable";
static constexpr const char* const s_indexer_name =
"HPHP::type_scan::detail::Indexer";
static constexpr const char* const s_auto_action_name =
"HPHP::type_scan::Action::Auto";
static constexpr const char* const s_scan_action_name =
"HPHP::type_scan::detail::ScanAction";
static constexpr const char* const s_with_suffix_action_name =
"HPHP::type_scan::Action::WithSuffix";
static constexpr const char* const s_ignore_action_name =
"HPHP::type_scan::Action::Ignore";
static constexpr const char* const s_conservative_action_name =
"HPHP::type_scan::Action::Conservative";
static constexpr const char* const s_scanner_name =
"HPHP::type_scan::Scanner";
};
/*
* As stated above, layout is a description of a particular scanner. It is a
* list of offsets, along with a certain action to perform at that
* offset. Computing layouts for indexed types is the purpose of the scanner
* generator. A layout is not inherently tied to any particular type, as many
* different types can share the same layout (this is especially common for
* templated types, like req::ptr<>).
*
* A layout can currently contain three different types of actions. The first is
* to report the value of a pointer at a certain offset. The second is to
* conservative scan a range given by a start offset and a length. The last is
* to invoke a custom function (with a certain symbol), passing a pointer formed
* by the offset as the first parameter (which serves as the this pointer).
*
* A layout can also have a suffix layout. Normally, for a given block of
* memory, the layout will be applied contiguously until the entire block is
* processed. However, if the layout has a suffix layout, the base layout is
* only applied once on the beginning of the block. The suffix layout will be
* applied contiguously on the remaining portion of the block. This is to handle
* object types with "flexible array members".
*/
struct Generator::Layout {
struct Ptr {
size_t offset;
bool operator==(const Ptr& other) const {
return offset == other.offset;
}
bool operator!=(const Ptr& other) const {
return !(*this == other);
}
bool operator<(const Ptr& other) const {
return offset < other.offset;
}
};
struct Conservative {
size_t offset;
size_t size;
bool operator==(const Conservative& other) const {
return std::tie(offset, size) == std::tie(other.offset, other.size);
}
bool operator!=(const Conservative& other) const {
return !(*this == other);
}
bool operator<(const Conservative& other) const {
return std::tie(offset, size) < std::tie(other.offset, other.size);
}
};
struct Custom {
size_t offset;
std::string linkage_name;
bool operator==(const Custom& other) const {
return std::tie(offset, linkage_name) ==
std::tie(other.offset, other.linkage_name);
}
bool operator!=(const Custom& other) const {
return !(*this == other);
}
bool operator<(const Custom& other) const {
return std::tie(offset, linkage_name) <
std::tie(other.offset, other.linkage_name);
}
};
explicit Layout(size_t size) : size{size} {}
Layout(const Layout& other);
Layout(Layout&&) = default;
Layout& operator=(const Layout& other);
Layout& operator=(Layout&&) = default;
void addPtr(size_t offset) {
ptrs.emplace_back(Ptr{offset});
}
void addConservative(size_t offset, size_t size);
void addCustom(size_t offset, std::string linkage) {
custom.emplace_back(Custom{offset, linkage});
}
// A sub-layout is used to insert a layout into another layout N times. Used
// for arrays, where we compute the layout once, but want to insert it for the
// number of elements in the array.
void addSubLayout(size_t offset,
size_t count,
const Layout& layout) {
for (size_t i = 0; i < count; ++i) {
merge(layout, offset + i*layout.size);
}
}
void setSuffix(Layout other) {
suffix = std::make_unique<Layout>(std::move(other));
}
void merge(const Layout& other, size_t offset);
bool isEmpty() const {
return ptrs.empty() && conservative.empty() &&
custom.empty() && (!suffix || suffix->isEmpty());
}
// Is this layout made up of nothing but conservative scans?
bool isAllConservative() const;
void clear();
size_t totalCount() const;
bool operator==(const Layout& other) const;
bool operator!=(const Layout& other) const { return !(*this == other); }
bool operator<(const Layout& other) const;
size_t size;
std::vector<Ptr> ptrs;
std::vector<Conservative> conservative;
std::vector<Custom> custom;
std::unique_ptr<Layout> suffix;
// Offset where the suffix begins. This may be different than the size because
// of flexible array members (which sometimes start within the object).
size_t suffix_begin = size;
};
/*
* If the generator cannot automatically create a layout, it will throw
* LayoutError. These LayoutErrors are gathered and reported together at the end
* of processing. They include context about why and where the error occurred.
*/
struct Generator::LayoutError {
explicit LayoutError(std::string reason): reason{std::move(reason)} {}
void addContext(std::string str) {
context.emplace_back(std::move(str));
}
std::string reason;
std::vector<std::string> context;
};
/*
* An indexed type is a combination of a type and a set of actions associated
* with. Every indexed type is associated a layout (hence a scanner), but a
* given type can be part of multiple indexed types. Type-indices are handed out
* on a per indexed type basis.
*
* Its important to distinguish the actions that are inherent to a type
* (embodied in the Action class), with the actions assigned inside an indexed
* type. The actions inherent to the type are used when automatically generating
* a scanner for that type, while the actions here override those. However,
* since indexed types are keyed by a type index, they are only applied on
* specific instances of the type with that type index at runtime. So, for
* example, a type T can have an automatically generated scanner for some
* instances of T, but a conservative scanner for others depending on which type
* index the instance has.
*/
struct Generator::IndexedType {
IndexedType(const Type& type, size_t type_size, Address address)
: type{&type}
, layout{type_size} { addresses.emplace_back(address); }
// Underlying type
const Type* type;
// List of addresses for all the associated Indexer<> instances.
std::vector<Address> addresses;
// Marker that instances of the type with this type index do not represent
// actual heap allocations (we only want the scanner).
bool scan = false;
// Ignore instances of the type with this type index. If this is true, and
// conservative is true as well, it means that the conservative scan is still
// conditional.
bool ignore = false;
// Conservative scan instances of the type with this type index.
bool conservative = false;
// If conservative is true, only actually conservative scan if any of these
// types are interesting. If not, ignore. If the list is empty, always
// conservative scan.
std::vector<const Type*> conservative_guards;
// A suffix type is used as the basis for a suffix layout as described above.
const Type* suffix_type = nullptr;
// Generated layout. This is used when generating layouts, but after that,
// layout_index will index into the layout table for the actual layout to use.
Layout layout;
// Index into the layout table for the assigned layout.
size_t layout_index = 0;
// If there was an error while automatically generating the layout for this
// underlying type, it is stored here until they are all reported.
folly::Optional<LayoutError> errors;
};
size_t NumThreads = 24;
Generator::Generator(const std::string& filename, bool skip) {
// Either this platform has no support for parsing debug information, or the
// preprocessor symbol to enable actually building scanner isn't
// enabled. Either way, just bail out. Everything will get a conservative
// scanner by default if someone actually tries to use the scanners at
// runtime.
if (skip) return;
m_parser = TypeParser::make(filename, NumThreads);
tbb::concurrent_vector<ObjectType> indexer_types;
tbb::concurrent_vector<ObjectType> collectable_markers;
tbb::concurrent_vector<ObjectType> scannable_collectable_markers;
// Iterate through all the objects the debug info parser found, storing the
// MarkCollectable<> markers, and the Indexer<> instances. For everything,
// store in the appropriate getObject() maps, which will allow us to do
// getObject() lookups afterwards.
//
// There can be a lot of objects to iterate over, so do it concurrently.
{
auto const block_count = m_parser->getObjectBlockCount();
std::atomic<size_t> next_block{0};
auto const run = [&]{
while (true) {
auto const block = next_block++;
if (block >= block_count) break;
m_parser->forEachObjectInBlock(
block,
[&](const ObjectType& type) {
if (isIndexerName(type.name.name)) {
indexer_types.push_back(type);
} else if (isMarkCollectableName(type.name.name)) {
collectable_markers.push_back(type);
} else if (isMarkScannableCollectableName(type.name.name)) {
collectable_markers.push_back(type);
scannable_collectable_markers.push_back(type);
}
// Incomplete types are useless for our purposes, so just ignore
// them.
if (type.incomplete) return;
m_objects_by_name[type.name].push_back(type.key);
}
);
}
};
std::vector<std::thread> threads;
// No point in creating more threads than there are blocks.
for (auto i = size_t{0}; i < std::min(block_count, NumThreads); ++i) {
threads.emplace_back(std::thread(run));
}
for (auto& t : threads) t.join();
}
// Complain if it looks like we don't have any debug info enabled.
// (falls back to conservative scanning for everything)
if (collectable_markers.empty() && indexer_types.empty()) {
std::cerr << "gen-type-scanners: warning: "
"No collectable or indexed types found. "
"Is debug-info enabled?" << std::endl;
}
// Extract all the types that Mark[Scannable]Collectable<> was instantiated on
// to obtain all the types which are collectable. Since all collectable types
// are automatically pointer followable, mark them as such.
m_collectable = extractFromMarkers<decltype(m_collectable)>(
collectable_markers,
[&](const Object& o) { return &getMarkedCollectable(o); }
);
m_scannable_collectable =
extractFromMarkers<decltype(m_scannable_collectable)>(
scannable_collectable_markers,
[&](const Object& o) { return &getMarkedCollectable(o); }
);
for (const auto* obj : m_collectable) {
makePtrFollowable(*obj);
}
// Extract all the IndexedType information out of the Indexer<>
// instantiations.
m_indexed_types = getIndexedTypes(indexer_types);
// Before beginning the actual layout generation, we can speed things up a bit
// by marking any types which we know are always pointer followable. This will
// let us reach the fixed point in fewer iterations.
for (const auto& indexed : m_indexed_types) {
// Indexed types just for scanning are never pointer followable (because
// they're not actually heap allocated).
if (indexed.scan) continue;
// If the underlying type is an object type, and its associated action is
// always non-trivial, or if the object type has a collectable type as a
// base class, then the object type is always pointer followable. Same logic
// for any suffix type.
if (const auto* obj = stripModifiers(*indexed.type).asObject()) {
const auto& object = getObject(*obj);
if (getAction(object).isAlwaysNonTrivial() ||
hasCollectableBase(object)) {
makePtrFollowable(object);
}
}
if (indexed.suffix_type) {
const auto& suffix_type = stripModifiers(*indexed.suffix_type);
if (const auto* obj = suffix_type.asObject()) {
const auto& object = getObject(*obj);
if (getAction(object).isAlwaysNonTrivial()) {
makePtrFollowable(*indexed.type);
}
}
}
// If this indexed type is always going to be a complete conservative scan,
// than we're always going to have a non-trivial action for its scanner, so
// it's always pointer followable.
if (indexed.conservative && indexed.conservative_guards.empty()) {
makePtrFollowable(*indexed.type);
}
}
genAllLayouts();
checkForLayoutErrors();
assignUniqueLayouts();
}
// Helper function. Match a name against another name, ignoring the template
// parameter portion.
bool Generator::isTemplateName(const std::string& candidate,
const std::string& name) {
auto index = candidate.find(name);
if (index != 0) return false;
if (name.size() >= candidate.size()) return false;
if (candidate[name.size()] != '<') return false;
if (candidate.rfind('>') == std::string::npos) return false;
return true;
}
// Helper functions to check if an object type's name is that of a special
// marker type:
bool Generator::isMarkCollectableName(const std::string& name) {
return isTemplateName(name, s_mark_collectable_name);
}
bool Generator::isMarkScannableCollectableName(const std::string& name) {
return isTemplateName(name, s_mark_scannable_collectable_name);
}
bool Generator::isIndexerName(const std::string& name) {
return isTemplateName(name, s_indexer_name);
}
bool Generator::isConservativeActionName(const std::string& name) {
return isTemplateName(name, s_conservative_action_name);
}
bool Generator::isWithSuffixActionName(const std::string& name) {
return isTemplateName(name, s_with_suffix_action_name);
}
// Split a member function of the form "[prefix][suffix]_" into just "suffix"
// and return it. Returns the empty string if the input doesn't match that
// format.
std::string Generator::splitFieldName(const std::string& input,
const std::string& prefix) {
auto index = input.find(prefix);
if (index != 0) return std::string{};
if (prefix.size()+1 >= input.size()) return std::string{};
if (input[input.size()-1] != '_') return std::string{};
return input.substr(prefix.size(), input.size()-prefix.size()-1);
}
// Helper function to remove any cv (and restrict) qualifiers from a type.
const Type& Generator::stripModifiers(const Type& type) {
if (auto modifier = type.asConst()) {
return stripModifiers(modifier->modified);
} else if (auto modifier = type.asVolatile()) {
return stripModifiers(modifier->modified);
} else if (auto modifier = type.asRestrict()) {
return stripModifiers(modifier->modified);
} else {
return type;
}
}
// Compare two types, return -1 if t1 < t2, 1 if t1 > t2, and 0 if they are
// equal. Type doesn't have a builtin comparison operator because the ordering
// is rather arbitrary and application dependent.
int Generator::compareTypes(const Type& t1, const Type& t2) {
// First order types according to what category of type they are, using the
// below arbitrary ranking.
const auto rank = [](const Type& t) {
return t.match<int>(
[](const ObjectType*) { return 0; },
[](const PtrType*) { return 1; },
[](const RefType*) { return 2; },
[](const RValueRefType*) { return 3; },
[](const ArrType*) { return 4; },
[](const ConstType*) { return 5; },
[](const VolatileType*) { return 6; },
[](const RestrictType*) { return 7; },
[](const FuncType*) { return 8; },
[](const MemberType*) { return 9; },
[](const VoidType*) { return 10; }
);
};
const auto rank1 = rank(t1);
const auto rank2 = rank(t2);
if (rank1 < rank2) return -1;
else if (rank1 > rank2) return 1;
// At this point, both t1 and t2 are of the same type category. We can now do
// member-wise comparison of the types within these types.
return t1.match<int>(
[&](const ObjectType* t) {
const auto* other = t2.asObject();
if (t->name.name < other->name.name) return -1;
else if (t->name.name > other->name.name) return 1;
if (t->incomplete < other->incomplete) return -1;
else if (t->incomplete > other->incomplete) return 1;
if (t->name.linkage < other->name.linkage) return -1;
else if (t->name.linkage > other->name.linkage) return 1;
// The two object types have the same linkage and same name, so now
// examine which linkage that actually is to determine how to check for
// object equality.
switch (t->name.linkage) {
case ObjectTypeName::Linkage::external:
case ObjectTypeName::Linkage::pseudo:
// Same name and external linkage means they're the same.
return 0;
case ObjectTypeName::Linkage::internal:
// Objects types with internal linkage with the same name are only the
// same if they're in the same compile unit.
if (t->key.compile_unit_id < other->key.compile_unit_id) return -1;
if (t->key.compile_unit_id > other->key.compile_unit_id) return 1;
return 0;
case ObjectTypeName::Linkage::none: {
// Object types with no linkage are only the same if they have
// identical keys.
const auto& tie1 = std::tie(
t->key.compile_unit_id,
t->key.object_id
);
const auto& tie2 = std::tie(
other->key.compile_unit_id,
other->key.object_id
);
if (tie1 < tie2) return -1;
if (tie1 > tie2) return 1;
return 0;
}
}
return 0;
},
[&](const PtrType* t) {
return compareTypes(t->pointee, t2.asPtr()->pointee);
},
[&](const RefType* t) {
return compareTypes(t->referenced, t2.asRef()->referenced);
},
[&](const RValueRefType* t) {
return compareTypes(t->referenced, t2.asRValueRef()->referenced);
},
[&](const ArrType* t) {
const auto* other = t2.asArr();
const auto cmp = compareTypes(t->element, other->element);
if (cmp != 0) return cmp;
if (t->count < other->count) return -1;
if (t->count > other->count) return 1;
return 0;
},
[&](const ConstType* t) {
return compareTypes(t->modified, t2.asConst()->modified);
},
[&](const VolatileType* t) {
return compareTypes(t->modified, t2.asVolatile()->modified);
},
[&](const RestrictType* t) {
return compareTypes(t->modified, t2.asRestrict()->modified);
},
[&](const FuncType* t) {
const auto* other = t2.asFunc();
const auto cmp = compareTypes(t->ret, other->ret);
if (cmp != 0) return cmp;
if (t->args.size() < other->args.size()) return -1;
if (t->args.size() > other->args.size()) return 1;
for (size_t i = 0; i < t->args.size(); ++i) {
const auto cmp = compareTypes(t->args[i], other->args[i]);
if (cmp != 0) return cmp;
}
return 0;
},
[&](const MemberType* t) {
const auto* other = t2.asMember();
const auto cmp = compareTypes(t->obj, other->obj);
if (cmp != 0) return cmp;
return compareTypes(t->member, other->member);
},
[&](const VoidType*) { return 0; }
);
}
// Compare two indexed types, return -1 if t1 < t2, 1 if t1 > t2, and 0 if
// equal. If this comparison is for the purpose of trying to merge two indexed
// type together (see below), skip comparing certain fields.
int Generator::compareIndexedTypes(const IndexedType& t1,
const IndexedType& t2,
bool for_merge) {
const auto cmp = compareTypes(*t1.type, *t2.type);
if (cmp != 0) return cmp;
if (t1.ignore < t2.ignore) return -1;
else if (t1.ignore > t2.ignore) return 1;
if (t1.conservative < t2.conservative) return -1;
else if (t1.conservative > t2.conservative) return 1;
const auto compare_guards = [](const IndexedType& type1,
const IndexedType& type2) {
return std::lexicographical_compare(
type1.conservative_guards.begin(),
type1.conservative_guards.end(),
type2.conservative_guards.begin(),
type2.conservative_guards.end(),
[](const Type* tp1, const Type* tp2) {
return compareTypes(*tp1, *tp2) < 0;
}
);
};
if (compare_guards(t1, t2)) return -1;
else if (compare_guards(t2, t1)) return 1;
if (!t1.suffix_type) {
if (t2.suffix_type) return -1;
} else if (!t2.suffix_type) {
if (t1.suffix_type) return 1;
} else {
const auto cmp = compareTypes(*t1.suffix_type, *t2.suffix_type);
if (cmp != 0) return cmp;
}
// The whole point of merging two indexed types together are to coalesce
// Indexer<> addresses and to combine a "scan-only" one with a non-scan-only
// one, so don't compare these fields when checking for equality.
if (!for_merge) {
// This ordering is important! We want indexed types with scan set to false
// to come first. We always merge right into left, so scan-only should be
// merged into no-scan-only.
if (t1.scan < t2.scan) return -1;
else if (t1.scan > t2.scan) return 1;
if (t1.addresses < t2.addresses) return -1;
else if (t1.addresses > t2.addresses) return 1;
}
return 0;
}
// Helper function to extract types that markers are instantiated on from the
// markers. Given a list of a specific marker object type, apply the given
// callable f to it (which should extract the marked type out of it), sort and
// uniquify the resultant list, and return it.
template <typename T, typename F, typename C>
T Generator::extractFromMarkers(const C& types, F&& f) const {
std::vector<const Object*> objects;
std::transform(
types.begin(),
types.end(),
std::back_inserter(objects),
[&](const ObjectType& t){ return &getObject(t); }
);
std::sort(objects.begin(), objects.end());
T out;
auto ins = std::inserter(out, out.end());
std::string msg;
std::for_each(
objects.begin(),
std::unique(objects.begin(), objects.end()),
[&](const Object* o) {
try {
ins = f(*o);
} catch (Exception& e) {
folly::format(&msg, " => {}\n", e.what());
}
}
);
if (!msg.empty()) throw Exception(msg);
return out;
}
// Given a list of Indexer<> instantiation types, extract the marked types, and
// create the appropriate IndexedType struct for them, merging duplicates
// together.
template <typename C>
std::vector<Generator::IndexedType> Generator::getIndexedTypes(
const C& indexers
) const {
auto indexed = extractFromMarkers<std::vector<IndexedType>>(
indexers,
[&](const Object& o) { return getIndexedType(o); }
);
return mergeDupIndexedTypes(std::move(indexed));
}
// Merge "duplicate" indexed types together using some definition of duplicate,
// returning the merged types.
std::vector<Generator::IndexedType> Generator::mergeDupIndexedTypes(
std::vector<Generator::IndexedType> indexed
) const {
// First sort the types. The ordering has been set up so that indexed types
// that are identical except for the "scan" field will have the indexed types
// with scan set to false first.
std::sort(
indexed.begin(),
indexed.end(),
[](const IndexedType& t1, const IndexedType& t2)
{ return compareIndexedTypes(t1, t2) < 0; }
);
// Only insert an indexed type into the unique vector if its not equal (for
// the purposes of merging) as the last indexed type in the vector. If they
// are equal, merge their addresses and their scan field anded together. Since
// indexed types with scan set to false come first, this will ensure that
// false is kept over true.
std::vector<IndexedType> unique;
for (const auto& i : indexed) {
if (unique.empty() || compareIndexedTypes(unique.back(), i, true) != 0) {
unique.emplace_back(std::move(i));
} else {
auto& back = unique.back();
back.scan &= i.scan;
back.addresses.insert(
back.addresses.end(),
i.addresses.begin(),
i.addresses.end()
);
}
}
return unique;
}
/*
* Certain compilers (usually Clang) will emit debug information for template
* instantiations, but fail to emit information about the template
* parameters. This usually happens if it thinks the template isn't "used". This
* is bad for marker types like Conservative<...> because it will be interpreted
* as an empty type list (which implies always conservative scan). Unfortunately
* we cannot always detect this, but we can for certain cases.
*
* If we know a-priori that an object-type is a template, and the debug
* information indicates the object type has no template parameters, do a hacky
* check on the object type's name. Look for the name to end with "<>",
* indicating an empty parameter list. If not, the template actually has
* parameters but is failing to emit them.
*
* Unfortunately there's not much that can be done about this, but we want to
* catch it quickly so that we can try to work around it.
*/
void Generator::sanityCheckTemplateParams(const Object& object) {
if (!object.template_params.empty()) return;
const auto index = object.name.name.rfind("<>");
if (index == std::string::npos ||
index != object.name.name.size()-2) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) is reported as having "
"no template parameters, but its name indicates "
"otherwise. This usually indicates the compiler "
"is not generating complete enough debug information.",
object.name.name,
object.key.object_id,
object.key.compile_unit_id
)
};
}
}
// Given a Mark[Scannable]CollectiblCollectable<> marker instantiation, extract
// the object-type its marking. Actually very simple, but do a lot of sanity
// checking on the result.
const Object& Generator::getMarkedCollectable(const Object& mark) const {
if (mark.incomplete) {
throw Exception{
folly::sformat(
"Collectable marker '{}' at ({},{}) is an incomplete type",
mark.name.name,
mark.key.object_id,
mark.key.compile_unit_id
)
};
}
if (mark.kind != Object::Kind::k_class) {
throw Exception{
folly::sformat(
"Collectable marker '{}' at ({},{}) isn't a class type",
mark.name.name,
mark.key.object_id,
mark.key.compile_unit_id
)
};
}
if (!mark.bases.empty()) {
throw Exception{
folly::sformat(
"Collectable marker '{}' at ({},{}) has base classes",
mark.name.name,
mark.key.object_id,
mark.key.compile_unit_id
)
};
}
if (!mark.members.empty()) {
throw Exception{
folly::sformat(
"Collectable marker '{}' at ({},{}) has members",
mark.name.name,
mark.key.object_id,
mark.key.compile_unit_id
)
};
}
if (mark.name.linkage != ObjectTypeName::Linkage::external) {
throw Exception{
folly::sformat(
"Collectable marker '{}' at ({},{}) does not have external linkage",
mark.name.name,
mark.key.object_id,
mark.key.compile_unit_id
)
};
}
if (mark.template_params.size() != 1) {
throw Exception{
folly::sformat(
"Collectable marker '{}' at ({},{}) does not have exactly "
"one template parameter",
mark.name.name,
mark.key.object_id,
mark.key.compile_unit_id
)
};
}
const auto& type = mark.template_params[0].type;
const auto* obj_type = stripModifiers(type).asObject();
if (!obj_type) {
throw Exception{
folly::sformat(
"Collectable marker '{}' at ({},{}) is instantiated on type '{}', "
"which is not an object",
mark.name.name,
mark.key.object_id,
mark.key.compile_unit_id,
type.toString()
)
};
}
if (obj_type->name.linkage != ObjectTypeName::Linkage::external) {
throw Exception{
folly::sformat(
"Collectable marker '{}' at ({},{}) is instantiated on object type '{}'"
" at ({}, {}), which does not have external linkage",
mark.name.name,
mark.key.object_id,
mark.key.compile_unit_id,
obj_type->name.name,
obj_type->key.object_id,
obj_type->key.compile_unit_id
)
};
}
const auto& obj = getObject(*obj_type);
if (obj.incomplete) {
throw Exception{
folly::sformat(
"Collectable marker '{}' at ({},{}) is instantiated on object type '{}'"
" at ({}, {}), which is an incomplete type",
mark.name.name,
mark.key.object_id,
mark.key.compile_unit_id,
obj_type->name.name,
obj_type->key.object_id,
obj_type->key.compile_unit_id
)
};
}
if (obj.kind != Object::Kind::k_class) {
throw Exception{
folly::sformat(
"Collectable marker '{}' at ({},{}) is instantiated on object type '{}'"
" at ({}, {}), which is not a class type",
mark.name.name,
mark.key.object_id,
mark.key.compile_unit_id,
obj_type->name.name,
obj_type->key.object_id,
obj_type->key.compile_unit_id
)
};
}
return obj;
}
// Given an Indexer<> marker instantiation, extract the type and action the
// marker refers to, returning the appropriate IndexedType instance. Do a lot of
// sanity checking on the result.
Generator::IndexedType Generator::getIndexedType(const Object& indexer) const {
if (indexer.incomplete) {
throw Exception{
folly::sformat(
"Indexer '{}' at ({},{}) is an incomplete type",
indexer.name.name,
indexer.key.object_id,
indexer.key.compile_unit_id
)
};
}
if (indexer.kind != Object::Kind::k_class) {
throw Exception{
folly::sformat(
"Indexer '{}' at ({},{}) is not a class type",
indexer.name.name,
indexer.key.object_id,
indexer.key.compile_unit_id
)
};
}
if (!indexer.bases.empty()) {
throw Exception{
folly::sformat(
"Indexer '{}' at ({},{}) has base classes",
indexer.name.name,
indexer.key.object_id,
indexer.key.compile_unit_id
)
};
}
if (indexer.members.size() != 2) {
throw Exception{
folly::sformat(
"Indexer '{}' at ({},{}) does not have exactly two members ({})",
indexer.name.name,
indexer.key.object_id,
indexer.key.compile_unit_id,
indexer.members.size()
)
};
}
if (indexer.template_params.size() != 2) {
throw Exception{
folly::sformat(
"Indexer '{}' at ({},{}) does not have exactly two "
"template parameters ({})",
indexer.name.name,
indexer.key.object_id,
indexer.key.compile_unit_id,
indexer.template_params.size()
)
};
}
const auto index_iter = std::find_if(
indexer.members.begin(),
indexer.members.end(),
[](const Object::Member& m) { return m.name == "s_index"; }
);
if (index_iter == indexer.members.end()) {
throw Exception{
folly::sformat(
"Indexer '{}' at ({},{}) does not a s_index member",
indexer.name.name,
indexer.key.object_id,
indexer.key.compile_unit_id
)
};
}
const auto& index_member = *index_iter;
if (index_member.offset) {
throw Exception{
folly::sformat(
"Indexer '{}' at ({},{}) has a non-static s_index member",
indexer.name.name,
indexer.key.object_id,
indexer.key.compile_unit_id
)
};
}
// Since we want to put the assigned type index into Indexer<>::s_index, it
// had better either have a symbol (preferred), or an absolute address.
if (!index_member.address && index_member.linkage_name.empty()) {
throw Exception{
folly::sformat(
"Indexer '{}' at ({},{}) has a s_index member which "
"has neither a linkage name, nor an address",
indexer.name.name,
indexer.key.object_id,
indexer.key.compile_unit_id
)
};
}
// Extract the underlying type from the Indexer<>, doing sanity checking on
// the type.
const auto* type = [&] {
/*
* The type we want is just the first template parameter of Indexer<>, but
* we want to do sanity checking on it, which involves walking the type
* chain.
*
* To avoid recursion, use a loop instead. Each invocation of the match
* method returns the next type to check, returning nullptr if there's no
* more types to check. This works because each type category only has at
* most one sub-type to check.
*/
const auto* current = &indexer.template_params[0].type;
while (current) {
current = current->match<const Type*>(
[&](const ObjectType* t) -> const Type* {
if (t->name.linkage == ObjectTypeName::Linkage::pseudo) {
throw Exception{
folly::sformat(
"Indexer '{}' at ({},{}) is instantiated on "
"object type '{}' which is the pseudo-type",
indexer.name.name,
indexer.key.object_id,
indexer.key.compile_unit_id,
current->toString()
)
};
}
const auto& obj = getObject(*t);
if (obj.incomplete) {
throw Exception{
folly::sformat(
"Indexer '{}' at ({},{}) is instantiated on "
"object type '{}' which is an incomplete type",
indexer.name.name,
indexer.key.object_id,
indexer.key.compile_unit_id,
current->toString()
)
};
}
if (obj.kind == Object::Kind::k_other) {
throw Exception{
folly::sformat(
"Indexer '{}' at ({},{}) is instantiated on "
"object type '{}' which has an 'other' kind",
indexer.name.name,
indexer.key.object_id,
indexer.key.compile_unit_id,
current->toString()
)
};
}
return nullptr;
},
[&](const PtrType*) -> const Type* { return nullptr; },
[&](const RefType*) -> const Type* { return nullptr; },
[&](const RValueRefType*) -> const Type* { return nullptr; },
[&](const ArrType* t) {
if (!t->count) {
throw Exception{
folly::sformat(
"Indexer '{}' at ({},{}) is instantiated on "
"unbounded array type '{}'",
indexer.name.name,
indexer.key.object_id,
indexer.key.compile_unit_id,
current->toString()
)
};
}
return &t->element;
},
[&](const ConstType* t) { return &t->modified; },
[&](const VolatileType* t) { return &t->modified; },
[&](const RestrictType* t) { return &t->modified; },
[&](const FuncType*) -> const Type* {
throw Exception{
folly::sformat(
"Indexer '{}' at ({},{}) is instantiated on function type '{}'",
indexer.name.name,
indexer.key.object_id,
indexer.key.compile_unit_id,
current->toString()
)
};
return nullptr;
},
[&](const MemberType*) -> const Type* {
throw Exception{
folly::sformat(
"Indexer '{}' at ({},{}) is instantiated on member type '{}'",
indexer.name.name,
indexer.key.object_id,
indexer.key.compile_unit_id,
current->toString()
)
};
return nullptr;
},
[&](const VoidType*) -> const Type* {
throw Exception{
folly::sformat(
"Indexer '{}' at ({},{}) is instantiated on void type",
indexer.name.name,
indexer.key.object_id,
indexer.key.compile_unit_id
)
};
return nullptr;
}
);
}
return &stripModifiers(indexer.template_params[0].type);
}();
IndexedType indexed_type{
*type,
determineSize(*type),
index_member.linkage_name.empty() ?
Address{*index_member.address} :
Address{index_member.linkage_name}
};
// Now examine the action component:
const auto* action_type =
stripModifiers(indexer.template_params[1].type).asObject();
if (!action_type) {
throw Exception{
folly::sformat(
"Indexer '{}' at ({},{}) action type '{}' isn't an object type",
indexer.name.name,
indexer.key.object_id,
indexer.key.compile_unit_id,
indexer.template_params[1].type.toString()
)
};
}
const auto& action = getObject(*action_type);
if (action.incomplete) {
throw Exception{
folly::sformat(
"Indexer '{}' at ({},{}) action type '{}' at ({},{}) is incomplete",
indexer.name.name,
indexer.key.object_id,
indexer.key.compile_unit_id,
action.name.name,
action.key.object_id,
action.key.compile_unit_id
)
};
}
// Use the name of the action to determine what it is:
if (action.name.name == s_auto_action_name) {
// Nothing
} else if (action.name.name == s_scan_action_name) {
indexed_type.scan = true;
} else if (action.name.name == s_ignore_action_name) {
indexed_type.ignore = true;
} else if (isConservativeActionName(action.name.name)) {
indexed_type.conservative = true;
// Conservative<> is a variadic template, so we'd better sanity check the
// template parameters.
sanityCheckTemplateParams(action);
if (!action.template_params.empty()) {
// If it has template parameters, the conservative scan is
// conditional. Indicate this fact by setting ignore to true as well. Once
// the guards have been evaluated, ignore will either be cleared (if any
// guards pass), or conservative will be cleared (if none pass).
indexed_type.ignore = true;
for (const auto& param : action.template_params) {
indexed_type.conservative_guards.emplace_back(
&stripModifiers(param.type)
);
}
}
} else if (isWithSuffixActionName(action.name.name)) {
if (action.template_params.size() != 1) {
throw Exception{
folly::sformat(
"Indexer '{}' at ({},{}) action type '{}' at ({},{}) does not "
"have exactly one template parameter",
indexer.name.name,
indexer.key.object_id,
indexer.key.compile_unit_id,
action.name.name,
action.key.object_id,
action.key.compile_unit_id
)
};
}
indexed_type.suffix_type = &stripModifiers(action.template_params[0].type);
} else {
throw Exception{
folly::sformat(
"Indexer '{}' at ({},{}) action type '{}' at ({},{}) is unknown",
indexer.name.name,
indexer.key.object_id,
indexer.key.compile_unit_id,
action.name.name,
action.key.object_id,
action.key.compile_unit_id
)
};
}
return indexed_type;
}
// Retrieve the action associated with the given object type, computing a new
// one if it isn't already present.
const Generator::Action& Generator::getAction(const Object& object,
bool conservative) const {
auto iter = m_actions.find(&object);
if (iter != m_actions.end()) return iter->second;
return m_actions.emplace(
&object,
inferAction(object, conservative)
).first->second;
}
bool Generator::findMemberHelper(const std::string& field,
const Object &a_object) const {
return std::any_of(
a_object.members.begin(),
a_object.members.end(),
[&](const Object::Member& m) {
if (m.type.isObject()) {
const Object &inner_object = getObject(*m.type.asObject());
if (inner_object.kind == Object::Kind::k_union) {
return findMemberHelper(field, inner_object);
}
}
return m.offset && m.name == field;
}
);
}
// Given an object type, examine it to infer all the needed actions for that
// type. The actions are inferred by looking for member functions with special
// names, and static members with special names.
Generator::Action Generator::inferAction(const Object& object,
bool conservative_everything) const {
if (object.incomplete) {
throw Exception{
folly::sformat(
"Trying to infer actions on object type '{}' at ({},{}) "
"which is incomplete",
object.name.name,
object.key.object_id,
object.key.compile_unit_id
)
};
}
Action action;
if (conservative_everything) {
action.conservative_all = true;
action.conservative_all_bases = true;
return action;
}
// White-listing and forbidden templates are determined by just checking the
// name against explicit lists.
if (HPHP::type_scan::detail::isIgnoredType(object.name.name)) {
action.whitelisted = true;
return action;
}
if (HPHP::type_scan::detail::isForbiddenTemplate(object.name.name)) {
sanityCheckTemplateParams(object);
action.forbidden_template = true;
return action;
}
if (HPHP::type_scan::detail::isForcedConservativeTemplate(object.name.name)) {
sanityCheckTemplateParams(object);
action.conservative_all = true;
action.conservative_all_bases = true;
return action;
}
const auto find_member = [&](const std::string& field) {
return findMemberHelper(field, object);
};
const auto find_base = [&](const Object& base) {
return std::any_of(
object.bases.begin(),
object.bases.end(),
[&](const Object::Base& b) { return &getObject(b.type) == &base; }
);
};
for (const auto& fun : object.functions) {
// Sanity check special member function. All the functions should take a
// const pointer to the contained object type as the first parameter (the
// this pointer), and a non-const reference to HPHP::type_scan::Scanner as
// the second (and nothing else). The return type should be void.
auto verify_func = [&](const Object::Function& func) {
if (func.kind != Object::Function::Kind::k_member) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains scanner func '{}' "
"which is not a non-static, non-virtual member",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
func.name
)
};
}
if (!func.ret_type.isVoid()) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains scanner func '{}' "
"which does not have a void return type",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
func.name
)
};
}
if (func.arg_types.size() != 2) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains scanner func '{}' "
"which does not take exactly two parameter ({})",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
func.name,
func.arg_types.size()
)
};
}
const auto& this_arg = func.arg_types[0];
const auto* this_ptr_arg = this_arg.asPtr();
if (!this_ptr_arg) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains scanner func '{}' "
"whose first parameter isn't a pointer type '{}'",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
func.name,
this_arg.toString()
)
};
}
const auto* this_const_arg = this_ptr_arg->pointee.asConst();
if (!this_const_arg) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains scanner func '{}' "
"whose first parameter isn't a const pointer type '{}'",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
func.name,
this_arg.toString()
)
};
}
const auto* this_obj_arg = this_const_arg->modified.asObject();
if (!this_obj_arg) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains scanner func '{}' "
"whose first parameter isn't a pointer type to object type '{}'",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
func.name,
this_arg.toString()
)
};
}
if (&getObject(*this_obj_arg) != &object) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains scanner func '{}' "
"whose first parameter isn't a valid this pointer '{}'",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
func.name,
this_arg.toString()
)
};
}
const auto& scanner_arg = func.arg_types[1];
const auto* scanner_ref_arg = scanner_arg.asRef();
if (!scanner_ref_arg) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains scanner func '{}' "
"whose second parameter isn't a reference '{}'",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
func.name,
scanner_arg.toString()
)
};
}
const auto* scanner_obj_arg = scanner_ref_arg->referenced.asObject();
if (!scanner_obj_arg) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains scanner func '{}' "
"whose second parameter isn't a reference to object-type '{}'",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
func.name,
scanner_arg.toString()
)
};
}
const auto& scanner_obj = getObject(*scanner_obj_arg);
if (scanner_obj.name.name != s_scanner_name) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains scanner func '{}' "
"whose second parameter isn't a reference to "
"{} '{}'",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
func.name,
std::string{s_scanner_name},
scanner_arg.toString()
)
};
}
};
// Custom scanner for particular field.
auto custom_field = splitFieldName(
fun.name,
HPHP::type_scan::detail::kCustomFieldName
);
if (!custom_field.empty()) {
verify_func(fun);
if (!find_member(custom_field)) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains custom field marker "
"referring to unknown non-static field '{}'",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
custom_field
)
};
}
action.custom_fields.emplace(
std::move(custom_field),
fun.linkage_name
);
}
// Custom scanner for entire object.
if (fun.name == HPHP::type_scan::detail::kCustomName) {
verify_func(fun);
action.custom_all = fun.linkage_name;
continue;
}
// Custom scanner for base classes.
if (fun.name == HPHP::type_scan::detail::kCustomBasesScannerName) {
verify_func(fun);
action.custom_bases_scanner = fun.linkage_name;
continue;
}
}
for (const auto& member : object.members) {
// All special member markers should be static, so ignore anything that's
// not.
if (member.offset) continue;
// Ignore a field.
auto ignore_field = splitFieldName(
member.name,
HPHP::type_scan::detail::kIgnoreFieldName
);
if (!ignore_field.empty()) {
if (!find_member(ignore_field)) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains ignore field marker "
"referring to unknown non-static field '{}'",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
ignore_field
)
};
}
action.ignore_fields.emplace(std::move(ignore_field));
continue;
}
// Scan field conservatively.
auto conservative_field = splitFieldName(
member.name,
HPHP::type_scan::detail::kConservativeFieldName
);
if (!conservative_field.empty()) {
if (!find_member(conservative_field)) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains conservative field marker "
"referring to unknown non-static field '{}'",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
conservative_field
)
};
}
action.conservative_fields.emplace(std::move(conservative_field));
continue;
}
// Marks flexible array field. There can only be one of these per object
// type.
auto flexible_array_field = splitFieldName(
member.name,
HPHP::type_scan::detail::kFlexibleArrayFieldName
);
if (!flexible_array_field.empty()) {
if (!action.flexible_array_field.empty()) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains more than one flexible "
"array field marker",
object.name.name,
object.key.object_id,
object.key.compile_unit_id
)
};
}
if (!find_member(flexible_array_field)) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains flexible array field marker "
"referring to unknown non-static field '{}'",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
flexible_array_field
)
};
}
action.flexible_array_field = std::move(flexible_array_field);
}
// Ignore entire object.
if (member.name == HPHP::type_scan::detail::kIgnoreName) {
action.ignore_all = true;
continue;
}
// Conservative scan entire object.
if (member.name == HPHP::type_scan::detail::kConservativeName) {
action.conservative_all = true;
continue;
}
// Ignore specific base.
if (member.name == HPHP::type_scan::detail::kIgnoreBaseName) {
const auto* ignore_type = stripModifiers(member.type).asObject();
if (!ignore_type) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains an ignore base marker "
"for a non-object type '{}'",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
member.type.toString()
)
};
}
const auto& ignore = getObject(*ignore_type);
// This is a variadic template, so sanity check it.
sanityCheckTemplateParams(ignore);
for (const auto& param : ignore.template_params) {
const auto* ignored_type = stripModifiers(param.type).asObject();
if (!ignored_type) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains an ignore base marker "
"instantiated on non-object type '{}'",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
param.type.toString()
)
};
}
const auto& ignored = getObject(*ignored_type);
if (!find_base(ignored)) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains an ignore base marker "
"instantiated on object-type '{}' which isn't a base class",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
ignored.name.name
)
};
}
action.ignored_bases.emplace(&ignored);
}
continue;
}
// Don't complain about a particular base class violating a forbidden
// template check.
if (member.name == HPHP::type_scan::detail::kSilenceForbiddenBaseName) {
const auto* silence_type = stripModifiers(member.type).asObject();
if (!silence_type) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains a silence base marker "
"for a non-object type '{}'",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
member.type.toString()
)
};
}
const auto& silence = getObject(*silence_type);
// This is a variadic template, so sanity check it.
sanityCheckTemplateParams(silence);
for (const auto& param : silence.template_params) {
const auto* silenced_type = stripModifiers(param.type).asObject();
if (!silenced_type) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains a silence base marker "
"instantiated on non-object type '{}'",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
param.type.toString()
)
};
}
const auto& silenced = getObject(*silenced_type);
if (!find_base(silenced)) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains a silence base marker "
"instantiated on object-type '{}' which isn't a base class",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
silenced.name.name
)
};
}
action.silenced_bases.emplace(&silenced);
}
continue;
}
// List of base classes to apply the custom bases scan to.
if (action.custom_bases_scanner &&
member.name == HPHP::type_scan::detail::kCustomBasesName) {
const auto* custom_list_type = stripModifiers(member.type).asObject();
if (!custom_list_type) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains a custom base marker "
"for a non-object type '{}'",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
member.type.toString()
)
};
}
const auto& custom_list = getObject(*custom_list_type);
// This is a variadic template, so sanity check it.
sanityCheckTemplateParams(custom_list);
for (const auto& param : custom_list.template_params) {
const auto* custom_type = stripModifiers(param.type).asObject();
if (!custom_type) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains a custom base marker "
"instantiated on non-object type '{}'",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
param.type.toString()
)
};
}
const auto& custom = getObject(*custom_type);
if (!find_base(custom)) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains a custom base marker "
"instantiated on object-type '{}' which isn't a base class",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
custom.name.name
)
};
}
action.custom_bases.emplace(&custom);
}
continue;
}
// If there's a custom scanner for the entire object, list of types to guard
// on.
if (action.custom_all &&
member.name == HPHP::type_scan::detail::kCustomGuardName) {
const auto* guard_type = stripModifiers(member.type).asObject();
if (!guard_type) {
throw Exception{
folly::sformat(
"Object type '{}' at ({},{}) contains a custom guard marker "
"instantiated on non-object type '{}'",
object.name.name,
object.key.object_id,
object.key.compile_unit_id,
member.type.toString()
)
};
}
const auto& guard = getObject(*guard_type);
// This is a variadic template, so sanity check it.
sanityCheckTemplateParams(guard);
for (const auto& param : guard.template_params) {
action.custom_guards.emplace(¶m.type);
}
continue;
}
}
return action;
}
// Given an object type, return the matching Object representation. Even for
// object types with different keys, if the underlying object type is the "same"
// (according to the linkage rules), the same Object representation will be
// returned. This means that one can then use pointer equality to check for
// equality between two object types.
const Object& Generator::getObject(const ObjectType& type) const {
// First attempt to lookup the Object in our internal maps. Use the
// appropriate map according to the object type's linkage. This ensures that
// object types that represent the same underlying object always returns the
// same Object&.
switch (type.name.linkage) {
case ObjectTypeName::Linkage::external: {
auto iter = m_external_objects.find(type.name.name);
if (iter != m_external_objects.end()) return iter->second;
break;
}
case ObjectTypeName::Linkage::internal: {
auto cu_iter = m_internal_objects.find(type.key.compile_unit_id);
if (cu_iter != m_internal_objects.end()) {
auto iter = cu_iter->second.find(type.name.name);
if (iter != cu_iter->second.end()) return iter->second;
}
break;
}
case ObjectTypeName::Linkage::none:
case ObjectTypeName::Linkage::pseudo: {
auto iter = m_unique_objects.find(type.key.object_id);
if (iter != m_unique_objects.end()) return iter->second;
break;
}
}
const auto insert = [&](Object object) -> const Object& {
switch (object.name.linkage) {
case ObjectTypeName::Linkage::external: {
return m_external_objects.emplace(
type.name.name,
std::move(object)
).first->second;
}
case ObjectTypeName::Linkage::internal: {
return m_internal_objects[type.key.compile_unit_id].emplace(
type.name.name,
std::move(object)
).first->second;
}
case ObjectTypeName::Linkage::none:
case ObjectTypeName::Linkage::pseudo: {
return m_unique_objects.emplace(
type.key.object_id,
std::move(object)
).first->second;
}
}
not_reached();
};
// No direct matches in our internal maps, so we need to retrieve it from the
// type parser. If the type is complete we can just retrieve it and use it
// directly. If this type has no linkage or pseudo-linkage, it matches nothing
// else, so just retrieve it. Store it in our maps for later lookup.
if (!type.incomplete ||
type.name.linkage == ObjectTypeName::Linkage::none ||
type.name.linkage == ObjectTypeName::Linkage::pseudo) {
return insert(m_parser->getObject(type.key));
}
// The object type is incomplete, but has internal or external linkage. We
// only want to return an incomplete object as a last resort, so let's look
// for any possible definitions of this type elsewhere.
auto const name_iter = m_objects_by_name.find(type.name);
if (name_iter != m_objects_by_name.end()) {
auto const& keys = name_iter->second;
// First look for a type with the same name in the same compilation unit. If
// there's one that's a complete definition, use that.
for (auto const& key : keys) {
if (key.object_id == type.key.object_id) continue;
if (key.compile_unit_id != type.key.compile_unit_id) continue;
auto other = m_parser->getObject(key);
if (other.incomplete) continue;
return insert(std::move(other));
}
// Otherwise if the type has external linkage, look for any type in any
// compilation unit (with external linkage) with the same name and having a
// complete definition.
if (type.name.linkage == ObjectTypeName::Linkage::internal) {
// Newer clang seems to split some types into different units,
// or at least we are not able to tell that they are the same.
std::cerr << "gen-type-scanners: warning: "
"No matching type found for internal linkage type " <<
type.name.name << " in same compile unit. "
"Trying other compile units." << std::endl;
}
for (auto const& key : keys) {
if (key.object_id == type.key.object_id) continue;
auto other = m_parser->getObject(key);
if (other.incomplete) continue;
return insert(std::move(other));
}
}
// There doesn't appear to be a complete definition of this type anywhere, so
// just return the incomplete object representation. This will probably error
// elsewhere, but there's nothing we can do.
return insert(m_parser->getObject(type.key));
}
// Given a type, fill the given layout (starting at the specified offset)
// appropriate for that type. LayoutError will be thrown if an ambiguous
// construct is encountered.
void Generator::genLayout(const Type& type,
Layout& layout,
size_t offset,
bool conservative_everything) const {
return type.match<void>(
[&](const ObjectType* t) {
genLayout(getObject(*t), layout, offset, true, conservative_everything);
},
[&](const PtrType* t) {
// Don't care about pointers to non-pointer followable types.
if (!isPtrFollowable(type)) return;
if (t->pointee.isVoid()) {
throw LayoutError{
"Generic pointer to void. Add annotation to disambiguate."
};
}
layout.addPtr(offset);
},
[&](const RefType* t) {
// Don't care about pointers to non-pointer followable types.
if (!isPtrFollowable(type)) return;
if (t->referenced.isVoid()) {
throw LayoutError{
"Generic pointer to void. Add annotation to disambiguate."
};
}
layout.addPtr(offset);
},
[&](const RValueRefType* t) {
// Don't care about pointers to non-pointer followable types.
if (!isPtrFollowable(type)) return;
if (t->referenced.isVoid()) {
throw LayoutError{
"Generic pointer to void. Add annotation to disambiguate."
};
}
layout.addPtr(offset);
},
[&](const ArrType* t) {
if (!t->count) {
throw LayoutError{
"Array of indeterminate size. Add annotation to disambiguate."
};
}
Layout sublayout{determineSize(t->element)};
genLayout(t->element, sublayout, 0, conservative_everything);
layout.addSubLayout(
offset,
*t->count,
sublayout
);
},
[&](const ConstType* t) {
genLayout(t->modified, layout, offset, conservative_everything);
},
[&](const VolatileType* t) {
genLayout(t->modified, layout, offset, conservative_everything);
},
[&](const RestrictType* t) {
genLayout(t->modified, layout, offset, conservative_everything);
},
[&](const FuncType*) {},
[&](const MemberType*) {},
[&](const VoidType*) {}
);
}
// Check if the given object member is associated with a special action,
// recording it into the given Layout as needed. Unnamed unions are recursed
// into with their members being treated as members of the enclosing
// object. Returns true if the layout was modified, false otherwise.
bool Generator::checkMemberSpecialAction(const Object& base_object,
const Object::Member& member,
const Action& action,
Layout& layout,
size_t base_obj_offset,
size_t offset) const {
if (member.type.isObject()) {
auto const& object = getObject(*member.type.asObject());
// Treat members of an unnamed union as members
// of the enclosing struct.
if (object.kind == Object::Kind::k_union) {
for (auto const& obj_member : object.members) {
if (!obj_member.offset) continue;
// Recurse: the unions themselves might contain unnamed unions.
if (checkMemberSpecialAction(base_object, obj_member, action,
layout, base_obj_offset,
offset + *obj_member.offset)) {
return true;
}
}
}
}
// The sole purpose of marking the flexible array member is so we know
// where the suffix begins. The suffix usually begins at the end of the
// object, but sometimes within it.
if (member.type.isArr() && action.flexible_array_field == member.name) {
layout.suffix_begin = offset;
return true;
}
if (action.ignore_fields.count(member.name) > 0) return true;
if (action.conservative_fields.count(member.name) > 0) {
layout.addConservative(offset, determineSize(member.type));
return true;
}
auto custom_iter = action.custom_fields.find(member.name);
if (custom_iter != action.custom_fields.end()) {
if (custom_iter->second.empty()) {
throw LayoutError{
folly::sformat(
"'{}' needs to have external linkage (not in unnamed namespace)"
" to use custom field scanner. If a template, template parameters"
" must have external linkage as well.",
base_object.name.name
)
};
}
layout.addCustom(base_obj_offset, custom_iter->second);
return true;
}
return false;
}
// Given an object type representation, fill the given Layout (starting at
// specified offset) with the appropriate layout for that object
// type. LayoutError will be thrown if an ambiguous construct is encountered.
void Generator::genLayout(const Object& object,
Layout& layout,
size_t offset,
bool do_forbidden_check,
bool conservative_everything) const {
// Never generate layout for collectable types, unless it was marked as
// scannable.
if (m_collectable.count(&object) > 0 &&
!m_scannable_collectable.count(&object)) {
return;
}
if (!m_layout_being_generated.emplace(&object).second) {
throw LayoutError{
folly::sformat(
"'{}' is contained within a recursive definition. "
"This can only happen with invalid debug information "
"or a type-scanner generator bug.",
object.name.name
)
};
}
SCOPE_EXIT { m_layout_being_generated.erase(&object); };
const auto& action = getAction(object, conservative_everything);
// A whitelisted type should be ignored entirely.
if (action.whitelisted) return;
// If this is a forbidden template (and forbidden template checking has been
// enabled), check if any of the template's type parameters are
// interesting. If so, this is an error, as the user shouldn't be using such
// types in this template.
if (do_forbidden_check &&
action.forbidden_template &&
forbiddenTemplateCheck(object)) {
throw LayoutError{
folly::sformat(
"'{}' shouldn't be used with potentially req-heap "
"allocated objects. Use req:: equivalents instead or add "
"annotations.",
object.name.name
)
};
}
// Process the base classes first to maintain rough offset ordering.
for (const auto& base : object.bases) {
try {
const auto& obj = getObject(base.type);
if (action.ignored_bases.count(&obj)) continue;
// Any base which has been included with the custom base scanner should be
// ignored here, as we'll do one call to the custom scanner.
if (action.custom_bases_scanner && action.custom_bases.count(&obj)) {
continue;
}
// Virtual inheritance. The generator doesn't know how to get the base
// class from the derived (though in theory this could be inferred from
// the debug information), so punt and make the user specify a custom base
// scanner.
if (!base.offset) {
throw LayoutError{
"Base is inherited virtually. "
"Add annotations to convert manually."
};
}
// Recursively generate layout for the base.
genLayout(
obj,
layout,
offset + *base.offset,
!action.silenced_bases.count(&obj),
action.conservative_all_bases
);
} catch (LayoutError& exn) {
exn.addContext(
folly::sformat(
"from base class '{}'",
base.type.name.name
)
);
throw;
}
}
// Do the single call to the custom bases scanner if there is one.
if (action.custom_bases_scanner && !action.custom_bases.empty()) {
if (action.custom_bases_scanner->empty()) {
throw LayoutError{
folly::sformat(
"'{}' needs to have external linkage (not in unnamed namespace)"
" to use custom base scanner. If a template, template parameters"
" must have external linkage as well.",
object.name.name
)
};
}
layout.addCustom(offset, *action.custom_bases_scanner);
}
if (action.ignore_all) return;
if (action.custom_all) {
// We'll use the custom scanner if there's no guards, or if at least one of
// the guards is interesting.
if (action.custom_guards.empty() ||
std::any_of(
action.custom_guards.begin(),
action.custom_guards.end(),
[this](const Type* guard) { return !hasEmptyLayout(*guard); }
)
) {
// Ooops, the custom scanner function doesn't have a symbol, which
// probably means it doesn't have external linkage. We can't reliably call
// such things, so error out.
if (action.custom_all->empty()) {
throw LayoutError{
folly::sformat(
"'{}' needs to have external linkage (not in unnamed namespace)"
" to use custom scanner. If a template, template parameters must"
" have external linkage as well.",
object.name.name
)
};
}
layout.addCustom(offset, *action.custom_all);
}
return;
}
if (action.conservative_all) {
// Determine the begin and end offsets of this type and set up a
// conservative scan for that range. We can't simply use (0, object size)
// because we do not want to include base classes, nor padding which we know
// can't contain any fields.
size_t begin = std::numeric_limits<size_t>::max();
size_t end = std::numeric_limits<size_t>::min();
for (const auto& member : object.members) {
if (!member.offset) continue;
begin = std::min(begin, *member.offset);
end = std::max(end, *member.offset + determineSize(member.type));
}
if (begin < end) {
layout.addConservative(begin + offset, end - begin);
}
return;
}
// Unions are special. If all the members of the union have the same layout,
// we can just use that. If not, its a LayoutError, as a custom scanner is
// needed to disambiguate it.
if (object.kind == Object::Kind::k_union) {
Layout first_layout{object.size};
bool first = true;
for (const auto& member : object.members) {
if (!member.offset) continue;
if (first) {
genLayout(member.type, first_layout, 0, conservative_everything);
first = false;
} else {
Layout other_layout{object.size};
genLayout(member.type, other_layout, 0, conservative_everything);
if (first_layout != other_layout) {
throw LayoutError{
folly::sformat(
"'{}' is a union containing potentially req-heap allocated "
"objects with different layouts. Add annotation to disambiguate "
"contents. (Conflicting members: '{}' and '{}')",
object.name.name,
object.members.front().name,
member.name
)
};
}
}
}
layout.merge(first_layout, offset);
return;
}
for (const auto& member : object.members) {
// Only non-static members.
if (!member.offset) continue;
// Check if this member has a special action. If it does, we're done
// processing it.
if (checkMemberSpecialAction(object, member, action,
layout, offset,
offset + *member.offset)) {
continue;
}
// Otherwise generate its layout recursively.
try {
genLayout(
member.type,
layout,
offset + *member.offset,
conservative_everything
);
} catch (LayoutError& exn) {
exn.addContext(
folly::sformat(
"from member '{}' of type '{}'",
member.name,
member.type.toString()
)
);
throw;
}
}
}
// Given a type, determine if it is pointer followable. Only object types (which
// are recorded as being pointer followable) pass, as do void pointers (though
// we cannot generate layout for them).
bool Generator::isPtrFollowable(const Type& type) const {
return type.match<bool>(
[&](const ObjectType* t) { return isPtrFollowable(getObject(*t)); },
[&](const PtrType* t) {
if (t->pointee.isVoid()) return true;
return isPtrFollowable(t->pointee);
},
[&](const RefType* t) {
if (t->referenced.isVoid()) return true;
return isPtrFollowable(t->referenced);
},
[&](const RValueRefType* t) {
if (t->referenced.isVoid()) return true;
return isPtrFollowable(t->referenced);
},
[&](const ArrType* t) { return isPtrFollowable(t->element); },
[&](const ConstType* t) { return isPtrFollowable(t->modified); },
[&](const VolatileType* t) { return isPtrFollowable(t->modified); },
[&](const RestrictType* t) { return isPtrFollowable(t->modified); },
[&](const FuncType*) { return false; },
[&](const MemberType*) { return false; },
[&](const VoidType*) { return false; }
);
}
// Make a given type pointer followable. This just walks the type hierarchy,
// marking the contained object type (if any) as being pointer followable.
void Generator::makePtrFollowable(const Type& type) {
return type.match<void>(
[&](const ObjectType* t) { makePtrFollowable(getObject(*t)); },
[&](const PtrType*) {},
[&](const RefType*) {},
[&](const RValueRefType*) {},
[&](const ArrType* t) { makePtrFollowable(t->element); },
[&](const ConstType* t) { makePtrFollowable(t->modified); },
[&](const VolatileType* t) { makePtrFollowable(t->modified); },
[&](const RestrictType* t) { makePtrFollowable(t->modified); },
[&](const FuncType*) {},
[&](const MemberType*) {},
[&](const VoidType*) {}
);
}
// Mark a given object type pointer followable. If an object type is marked
// pointer followable, all its bases must be as well (because a pointer to a
// base could be pointing towards this object type).
void Generator::makePtrFollowable(const Object& obj) {
m_ptr_followable.emplace(&obj);
for (const auto& base : obj.bases) {
makePtrFollowable(getObject(base.type));
}
}
// Recursive function to check if a given object has a collectable base
// somewhere in its type hierarchy.
bool Generator::hasCollectableBase(const Object& object) const {
if (m_collectable.count(&object)) return true;
return std::any_of(
object.bases.begin(),
object.bases.end(),
[this](const Object::Base& b) {
return hasCollectableBase(getObject(b.type));
}
);
}
// Given a type, check if this is an object type with any template parameters
// being a pointer followable type.
bool Generator::forbiddenTemplateCheck(const Type& type) const {
return type.match<bool>(
[&](const ObjectType* t) { return forbiddenTemplateCheck(getObject(*t)); },
[&](const PtrType* t) { return forbiddenTemplateCheck(t->pointee); },
[&](const RefType* t) { return forbiddenTemplateCheck(t->referenced); },
[&](const RValueRefType* t) {
return forbiddenTemplateCheck(t->referenced);
},
[&](const ArrType* t) { return forbiddenTemplateCheck(t->element); },
[&](const ConstType* t) { return forbiddenTemplateCheck(t->modified); },
[&](const VolatileType* t) {
return forbiddenTemplateCheck(t->modified);
},
[&](const RestrictType* t) {
return forbiddenTemplateCheck(t->modified);
},
[&](const FuncType*) { return false; },
[&](const MemberType*) { return false; },
[&](const VoidType*) { return false; }
);
}
// Given an object type, check if any template parameters are a pointer
// followable type.
bool Generator::forbiddenTemplateCheck(const Object& object) const {
if (isPtrFollowable(object)) return true;
for (const auto& param : object.template_params) {
if (forbiddenTemplateCheck(param.type)) return true;
}
return false;
}
// Given a type, determine if it is non-interesting, IE, its generated layout is
// empty.
bool Generator::hasEmptyLayout(const Type& type) const {
try {
Layout layout{determineSize(type)};
genLayout(type, layout, 0);
return layout.isEmpty();
} catch (const LayoutError&) {
return false;
}
}
// Given an object type, determine if it is non-interesting, IE, its generated
// layout is empty.
bool Generator::hasEmptyLayout(const Object& object) const {
try {
Layout layout{object.size};
genLayout(object, layout, 0);
return layout.isEmpty();
} catch (const LayoutError&) {
return false;
}
}
// Given a type, determine how many bytes an instance of that type occupies.
size_t Generator::determineSize(const Type& type) const {
return type.match<size_t>(
[&](const ObjectType* t) { return getObject(*t).size; },
// This is valid because we run on architectures where all pointers are the
// same size, and we always generate the heap scanners at the same time
// we're building everything else.
[&](const PtrType*) { return sizeof(void*); },
[&](const RefType*) { return sizeof(void*); },
[&](const RValueRefType*) { return sizeof(void*); },
[&](const ArrType* t) {
if (!t->count) return size_t{0};
return determineSize(t->element) * *t->count;
},
[&](const ConstType* t) { return determineSize(t->modified); },
[&](const VolatileType* t) { return determineSize(t->modified); },
[&](const RestrictType* t) { return determineSize(t->modified); },
// These are somewhat dubious, and shouldn't really occur:
[&](const FuncType*) { return size_t{0}; },
[&](const MemberType*) { return size_t{0}; },
[&](const VoidType*) { return size_t{0}; }
);
}
/*
* Generate layouts for all indexed types. This is an iterative method since the
* layout depends on which types are pointer followable, and what types are
* pointer followable depends on which types are interesting, and what types are
* interesting depends on their layout.
*
* For every indexed type, we generate its layout. If the type was previously
* uninteresting, but the new layout makes it interesting, mark it as pointer
* followable. Continue this process until we take a full pass through the
* indexed type list without computing a different layout for all types.
*/
void Generator::genAllLayouts() {
bool changed;
do {
changed = false;
for (auto& indexed : m_indexed_types) {
try {
// No point in continuing with this one if we already have a
// LayoutError.
if (indexed.errors) continue;
// If this indexed type's action is conservative, examine guards (if
// any) to see if we want to ignore or conserative scan it.
if (indexed.conservative) {
// If ignore isn't set, the issue has already been decided
// (conservative scan).
if (!indexed.ignore) continue;
// Otherwise, iterate over all the conservative guards, seeing if any
// are interesting.
for (const auto* guard : indexed.conservative_guards) {
if (!hasEmptyLayout(*guard)) {
indexed.ignore = false;
makePtrFollowable(*indexed.type);
changed = true;
break;
}
}
continue;
}
if (indexed.ignore) continue;
// Generate the new layout for this type, including any suffix.
Layout new_layout{determineSize(*indexed.type)};
genLayout(*indexed.type, new_layout, 0);
if (indexed.suffix_type) {
Layout suffix_layout{determineSize(*indexed.suffix_type)};
genLayout(*indexed.suffix_type, suffix_layout, 0);
new_layout.setSuffix(std::move(suffix_layout));
}
if (indexed.layout != new_layout) {
// This new layout is different. If this isn't a "scan-only" indexed
// type (which can't be pointer followable), and the type was
// previously un-interesting, make this pointer followable.
if (!indexed.scan && indexed.layout.isEmpty()) {
makePtrFollowable(*indexed.type);
}
changed = true;
indexed.layout = std::move(new_layout);
}
} catch (LayoutError& exn) {
indexed.errors = std::move(exn);
}
}
} while (changed);
}
// At this point, the layouts in the indexed types are correct. However, some of
// the indexed types may have the same layout. Put all the unique and sorted
// layouts into the m_layouts list. Assign each indexed type its appropriate
// index into the list.
void Generator::assignUniqueLayouts() {
// First fix up some of the indexed types so that they're in a consistent
// state. These transformations are safe to perform as we know the layouts at
// maximal.
for (auto& indexed : m_indexed_types) {
// At this point, we definitely know which types will be conservative
// scanned or not, so we do not need the guards anymore. Clearing these lets
// us merge together more duplicates.
indexed.conservative_guards.clear();
if (indexed.ignore) {
// If the indexed type is still marked as ignored, it cannot be
// conservative scanned.
indexed.conservative = false;
continue;
}
if (indexed.conservative) {
// Likewise, if the indexed type is still marked for conservative
// scanning, it cannot be ignored.
indexed.ignore = false;
continue;
}
if (indexed.layout.isEmpty()) {
// If this type isn't interesting, mark it as if it was explicitly
// ignored.
indexed.ignore = true;
indexed.layout.clear();
continue;
}
if (indexed.layout.isAllConservative()) {
// If the layout contains nothing but conservative scans, mark it as if it
// was explicitly marked for conservative scans.
indexed.conservative = true;
indexed.layout.clear();
continue;
}
// Finally, if there's a suffix layout, and the suffix begins at offset 0,
// than the suffix layout can completely subsume the original layout.
if (indexed.layout.suffix && indexed.layout.suffix_begin == 0) {
// avoid indeterminate evaluation order by moving indexed.layout.suffix
// to a temp before overwriting indexed.layout
auto suffix = std::move(*indexed.layout.suffix);
indexed.layout = std::move(suffix);
}
}
// Now that the indexed types are fixed up to be more consistent, merge
// duplicates together.
m_indexed_types = mergeDupIndexedTypes(std::move(m_indexed_types));
// Record all generated layouts in m_layouts (ignoring ignored or conservative
// ones since those have hard-coded scanners).
for (const auto& indexed : m_indexed_types) {
if (indexed.ignore || indexed.conservative) continue;
m_layouts.emplace_back(indexed.layout);
}
// Sort them and make them unique.
std::sort(m_layouts.begin(), m_layouts.end());
m_layouts.erase(
std::unique(m_layouts.begin(), m_layouts.end()),
m_layouts.end()
);
// Record the appropriate offset into m_layouts for each indexed type to refer
// to its layout.
for (auto& indexed : m_indexed_types) {
if (indexed.ignore || indexed.conservative) continue;
auto result = std::equal_range(
m_layouts.begin(),
m_layouts.end(),
indexed.layout
);
assert(result.first != result.second);
indexed.layout_index = std::distance(m_layouts.begin(), result.first);
}
}
// Check for any errors while generating layouts. We don't want to report these
// errors immediately, as we want to gather them up and report them all at the
// end. This is helpful when there's several things wrong at once.
void Generator::checkForLayoutErrors() const {
std::ostringstream oss;
size_t error_count = 0;
for (const auto& indexed : m_indexed_types) {
if (indexed.errors) {
// Don't go overboard....
if (++error_count > 15) break;
const auto& errors = *indexed.errors;
oss << "error: " << errors.reason << "\n";
for (const auto& context : errors.context) {
oss << "\t- " << context << "\n";
}
oss << "\t- from type '" << *indexed.type << "'\n\n";
}
// Error if an indexed type had internal linkage.
for (const auto& address : indexed.addresses) {
HPHP::match<void>(address,
[&](const std::string&) { /* ok */ },
[&](uintptr_t) {
++error_count;
oss << "error: type " << *indexed.type << " has internal linkage.\n"
" Indexed types need external linkage.\n";
}
);
}
}
if (error_count > 0) throw Exception{oss.str()};
}
/*
* C++ code generation functions:
*/
/*
* Output all the needed C++ forward declarations. Any called custom scanners
* need to forward declared, as well as any Indexer<>::s_index static instances
* which have a symbol. Normally to forward declare these, we would have to
* forward declare a lot of other types, but we employ a dirty trick to avoid
* this. We forward declare the mangled names, wrapped in an extern C block.
*/
void Generator::genForwardDecls(std::ostream& os) const {
std::set<std::string> decls;
for (const auto& layout : m_layouts) {
for (const auto& custom : layout.custom) {
decls.emplace(custom.linkage_name);
}
if (layout.suffix) {
for (const auto& custom : layout.suffix->custom) {
decls.emplace(custom.linkage_name);
}
}
}
for (const auto& decl : decls) {
os << "/* " << folly::demangle(decl.c_str()) << " */\n"
<< "extern \"C\" void " << decl << "(const void*, Scanner&);\n";
}
os << "\n";
decls.clear();
for (const auto& indexed : m_indexed_types) {
for (const auto& addr : indexed.addresses) {
if (auto* decl = boost::get<std::string>(&addr)) {
decls.emplace(*decl);
}
}
}
for (const auto& decl : decls) {
os << "/* " << folly::demangle(decl.c_str()) << " */\n"
<< "extern \"C\" Index " << decl << ";\n";
}
os << "\n";
}
// Output the initialization of the metadata table mapping the type indices to
// the type name and scanner.
void Generator::genDataTable(std::ostream& os) const {
os << "const HPHP::type_scan::detail::Metadata g_table[] = {\n";
os << " {\"(UNKNOWN)\", scanner_conservative},\n";
os << " {\"(UNKNOWN NO-PTRS)\", scanner_noptrs},\n";
for (const auto& indexed : m_indexed_types) {
const auto get_scanner_name = [&]() -> std::string {
if (indexed.ignore) return "scanner_noptrs";
if (indexed.conservative) return "scanner_conservative";
return folly::sformat("scanner_{}", indexed.layout_index);
};
os << " {\"" << *indexed.type << "\", "
<< get_scanner_name() << "},\n";
}
os << "};\n\n";
}
// Output the initialization function which inserts the type indices to the
// appropriate Indexer<>::s_index static instances.
void Generator::genIndexInit(std::ostream& os) const {
os << "void init_indices() {\n";
size_t index = 2;
for (const auto& indexed : m_indexed_types) {
os << " /* " << *indexed.type << " */\n";
for (const auto& address : indexed.addresses) {
HPHP::match<void>(address,
[&](const std::string& s) {
os << " " << s << " = " << index << ";\n";
},
[&](uintptr_t /*p*/) {
os << " *reinterpret_cast<Index*>(0x" << std::hex
<< address << std::dec << ") = " << index << ";\n";
});
}
++index;
}
os << "\n static_assert(" << index-1
<< " <= std::numeric_limits<Index>::max(), "
<< "\"type_scan::Index is too small for all types\");\n";
os << "}\n\n";
}
void Generator::genBuiltinScannerFuncs(std::ostream& os) const {
os << "void scanner_conservative(Scanner& scanner, "
<< "const void* ptr, size_t size) {\n"
<< " scanner.m_conservative.emplace_back(ptr, size);\n"
<< "}\n\n";
os << "void scanner_noptrs(Scanner& scanner, "
<< "const void* ptr, size_t size) {\n"
<< "}\n\n";
}
void Generator::genScannerFuncs(std::ostream& os) const {
genBuiltinScannerFuncs(os);
std::vector<std::vector<std::string>> types(m_layouts.size());
for (const auto& indexed : m_indexed_types) {
if (indexed.ignore || indexed.conservative) continue;
types[indexed.layout_index].push_back(indexed.type->toString());
}
for (size_t i = 0; i < m_layouts.size(); ++i) {
auto& type_list = types[i];
std::sort(type_list.begin(), type_list.end());
for (auto& t : type_list) {
os << "// " << t << "\n";
}
os << "void scanner_" << i << "(Scanner& scanner, "
<< "const void* ptr, size_t size) {\n";
genScannerFunc(os, m_layouts[i]);
os << "}\n\n";
}
}
// For a given layout, output the matching C++ code to implement the scanner.
void Generator::genScannerFunc(std::ostream& os,
const Layout& layout,
size_t begin_offset) const {
// Assert that the size passed into the scanner is a multiple of the type
// size.
if (layout.size > 0) {
if (begin_offset > 0) {
os << " assert((size - " << begin_offset << ") % "
<< layout.size << " == 0);\n";
} else if (!layout.suffix) {
os << " assert(size % " << layout.size << " == 0);\n";
}
}
// If there's no suffix, the scanner is wrapped within a for loop which loops
// over the entire allocation given by the size parameter.
if (!layout.suffix) {
os << " for (size_t offset = "
<< begin_offset << "; offset < size; offset += "
<< layout.size << ") {\n";
}
// Ident appropriately depending on whether we're inside a for loop or not.
auto indent = [&](int level = 0) -> std::ostream& {
if (!layout.suffix) level += 2;
for (size_t i = 0; i < level; ++i) {
os << " ";
}
return os;
};
// If we're in a for loop, the offsets need to be biased by the loop
// iteration.
const auto* offset_str = layout.suffix ? "" : "+offset";
// First generate calls to the scanner to record all the pointers. We use the
// version of insert() which takes an initializator list because it is more
// efficient.
if (layout.ptrs.size() == 1) {
indent(2) << "scanner.m_addrs.emplace_back(\n";
const auto& ptr = layout.ptrs.back();
indent(4) << "((const void**)(uintptr_t(ptr)"
<< offset_str << "+" << ptr.offset << "))\n";
indent(2) << ");\n";
} else if (!layout.ptrs.empty()) {
indent(2) << "scanner.m_addrs.insert(scanner.m_addrs.end(), {\n";
for (const auto& ptr : layout.ptrs) {
indent(4) << "((const void**)(uintptr_t(ptr)"
<< offset_str << "+" << ptr.offset
<< ((&ptr == &layout.ptrs.back()) ? "))\n" : ")),\n");
}
indent(2) << "});\n";
}
// In a similar manner, insert conservative ranges.
if (layout.conservative.size() == 1) {
indent(2) << "scanner.m_conservative.emplace_back(\n";
const auto& conservative = layout.conservative.back();
indent(4) << "(const void*)(uintptr_t(ptr)"
<< offset_str << "+" << conservative.offset << "), "
<< conservative.size << "\n";
indent(2) << ");\n";
} else if (!layout.conservative.empty()) {
indent(2) << "scanner.m_conservative.insert(scanner.m_conservative.end(), "
<< "{\n";
for (const auto& conservative : layout.conservative) {
indent(4) << "{(const void*)(uintptr_t(ptr)"
<< offset_str << "+" << conservative.offset << "), "
<< conservative.size
<< ((&conservative == &layout.conservative.back()) ?
"}\n" : "},\n");
}
indent(2) << "});\n";
}
// Finally generate calls to all custom functions. Use the current offset to
// form the this pointer for the method call.
for (const auto& custom : layout.custom) {
indent(2) << custom.linkage_name << "((const void*)(uintptr_t(ptr)"
<< offset_str << "+" << custom.offset << "), scanner);\n";
}
if (!layout.suffix) {
os << " }\n";
} else {
// If we have a suffix, we didn't generate a for loop, just straightline
// code. Now generate code for the suffix portion.
genScannerFunc(os, *layout.suffix, layout.suffix_begin);
}
}
void Generator::genMetrics(std::ostream& os) const {
os << "// type_scan Metrics:\n";
os << "// unique layouts: " << m_layouts.size() << std::endl;
os << "// indexed types: " << m_indexed_types.size() << std::endl;
os << "// pointer followable types: " << m_ptr_followable.size() << std::endl;
os << "// collectable types: " << m_collectable.size() << std::endl;
os << "// scannable collectable types: " << m_scannable_collectable.size()
<< std::endl;
size_t conservative_fields{0};
size_t conservative_types{0};
size_t custom_fields{0};
size_t custom_types{0};
size_t custom_bases{0};
size_t ignored_fields{0};
size_t ignored_types{0};
size_t whitelisted_types{0};
size_t forbidden_templates{0};
size_t flexible_arrays{0};
for (auto& e : m_actions) {
auto& action = e.second;
if (action.ignore_all) ignored_types++;
if (action.conservative_all) conservative_types++;
if (action.whitelisted) whitelisted_types++;
if (action.forbidden_template) forbidden_templates++;
if (action.custom_all) custom_types++;
if (!action.flexible_array_field.empty()) flexible_arrays++;
// count custom guards?
ignored_fields += action.ignore_fields.size();
conservative_fields += action.conservative_fields.size();
custom_fields += action.custom_fields.size();
custom_bases += action.custom_bases.size();
}
os << "// object types: " << m_actions.size() << std::endl;
os << "// conservative-scanned types: " << conservative_types << std::endl;
os << "// conservative-scanned fields: " << conservative_fields << std::endl;
os << "// custom-scanned types: " << custom_types << std::endl;
os << "// custom-scanned fields: " << custom_fields << std::endl;
os << "// custom-scanned bases: " << custom_bases << std::endl;
os << "// ignored types: " << ignored_types << std::endl;
os << "// ignored fields: " << ignored_fields << std::endl;
os << "// whitelisted types: " << whitelisted_types << std::endl;
os << "// forbidden templates: " << forbidden_templates << std::endl;
os << "// flexible arrays: " << flexible_arrays << std::endl;
os << std::endl;
}
// Generate the entire C++ file.
void Generator::operator()(std::ostream& os) const {
os << "#include <limits>\n\n";
os << "#include \"hphp/util/assertions.h\"\n";
os << "#include \"hphp/util/portability.h\"\n";
os << "#include \"hphp/util/type-scan.h\"\n\n";
os << "using namespace HPHP::type_scan;\n";
os << "using namespace HPHP::type_scan::detail;\n\n";
genMetrics(os);
genForwardDecls(os);
os << "namespace {\n\n";
genScannerFuncs(os);
genDataTable(os);
genIndexInit(os);
os << "}\n\n";
os << "extern \"C\" {\n\n"
<< "EXTERNALLY_VISIBLE const Metadata* "
<< HPHP::type_scan::detail::kInitFuncName
<< "(size_t& table_size) {\n"
<< " init_indices();\n"
<< " table_size = " << m_indexed_types.size()+2 << ";\n"
<< " return g_table;\n"
<< "}\n\n"
<< "}" << std::endl;
}
Generator::Layout::Layout(const Layout& other)
: size{other.size}
, ptrs{other.ptrs}
, conservative{other.conservative}
, custom{other.custom}
, suffix{other.suffix ? std::make_unique<Layout>(*other.suffix) : nullptr}
, suffix_begin{other.suffix_begin}
{
}
Generator::Layout& Generator::Layout::operator=(const Layout& other) {
size = other.size;
ptrs = other.ptrs;
conservative = other.conservative;
custom = other.custom;
suffix = other.suffix ? std::make_unique<Layout>(*other.suffix) : nullptr;
suffix_begin = other.suffix_begin;
return *this;
}
void Generator::Layout::addConservative(size_t offset, size_t size) {
if (!size) return;
// Eagerly coalesce adjacent conservative ranges.
if (!conservative.empty()) {
auto& back = conservative.back();
if (back.offset + back.size == offset) {
back.size += size;
return;
}
}
conservative.emplace_back(Conservative{offset, size});
}
bool Generator::Layout::isAllConservative() const {
if (!ptrs.empty() || !custom.empty()) return false;
if (conservative.size() != 1) return false;
if (suffix && !suffix->isAllConservative()) return false;
const auto& back = conservative.back();
return back.offset == 0 && back.size == size;
}
void Generator::Layout::clear() {
ptrs.clear();
conservative.clear();
custom.clear();
suffix.reset();
suffix_begin = 0;
}
size_t Generator::Layout::totalCount() const {
return ptrs.size() +
conservative.size() +
custom.size() +
(suffix ? suffix->totalCount() : 0);
}
void Generator::Layout::merge(const Layout& other, size_t offset) {
for (const auto& entry : other.ptrs) {
addPtr(offset + entry.offset);
}
for (const auto& entry : other.conservative) {
addConservative(offset + entry.offset, entry.size);
}
for (const auto& entry : other.custom) {
addCustom(offset + entry.offset, entry.linkage_name);
}
}
bool Generator::Layout::operator==(const Layout& other) const {
if (std::tie(size, ptrs, conservative,
custom, suffix_begin) !=
std::tie(other.size, other.ptrs, other.conservative,
other.custom, other.suffix_begin)) {
return false;
}
if (!suffix) return !other.suffix;
if (!other.suffix) return !suffix;
return *suffix == *other.suffix;
}
// Arbitrary ordering of layouts. This ordering was chosen to satisfy my
// aesthetics of having "simpler" scanners come first.
bool Generator::Layout::operator<(const Layout& other) const {
const auto count1 = totalCount();
const auto count2 = other.totalCount();
if (count1 != count2) return count1 < count2;
if (ptrs.size() != other.ptrs.size()) {
return ptrs.size() < other.ptrs.size();
}
if (conservative.size() != other.conservative.size()) {
return conservative.size() < other.conservative.size();
}
if (custom.size() != other.custom.size()) {
return custom.size() < other.custom.size();
}
if (ptrs != other.ptrs) return ptrs < other.ptrs;
if (conservative != other.conservative) {
return conservative < other.conservative;
}
if (custom != other.custom) return custom < other.custom;
if (size != other.size) return size < other.size;
if (suffix) {
if (!other.suffix) return false;
if (*suffix != *other.suffix) return *suffix < *other.suffix;
return suffix_begin < other.suffix_begin;
} else {
return static_cast<bool>(other.suffix);
}
}
const std::string kProgramDescription =
"Generate type-scanners from debug-info";
////////////////////////////////////////////////////////////////////////////////
}
int main(int argc, char** argv) {
folly::SingletonVault::singleton()->registrationComplete();
namespace po = boost::program_options;
po::options_description desc{"Allowed options"};
desc.add_options()
("help", "produce help message")
("install_dir",
po::value<std::string>(),
"directory to put generated scanners")
("fbcode_dir", po::value<std::string>(), "ignored")
("source_file",
po::value<std::string>()->required(),
"filename to read debug-info from")
("output_file",
po::value<std::string>()->required(),
"filename of generated scanners")
("skip", "do not scan dwarf, generate conservative scanners")
("num_threads", po::value<int>(), "number of parallel threads")
("print", "dump the dwarf to stdout")
;
try {
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
if (vm.count("help")) {
std::cout << kProgramDescription << "\n\n"
<< desc << std::endl;
return 1;
}
#if defined(__clang__) && !defined(CLANG_STANDALONE_DEBUG)
// Doesn't work with older Clang that don't support attribute used
// in member functions of template classes.
// Fixed in https://reviews.llvm.org/D56928
// Doesn't work with Clang without -fstandalone-debug
auto skip = true;
#else
auto skip = vm.count("skip") || getenv("HHVM_DISABLE_TYPE_SCANNERS");
#endif
po::notify(vm);
auto const print = vm.count("print") != 0;
const auto output_filename =
vm.count("install_dir") ?
folly::sformat(
"{}{}{}",
vm["install_dir"].as<std::string>(),
HPHP::FileUtil::getDirSeparator(),
vm["output_file"].as<std::string>()
) :
vm["output_file"].as<std::string>();
if (vm.count("num_threads")) {
auto n = vm["num_threads"].as<int>();
if (n > 0) {
NumThreads = n;
} else {
std::cerr << "\nIllegal num_threads=" << n << "\n";
return 1;
}
}
try {
const auto source_executable = vm["source_file"].as<std::string>();
if (print) {
auto const printer = debug_parser::Printer::make(source_executable);
(*printer)(std::cout);
}
Generator generator{source_executable, skip};
std::ofstream output_file{output_filename};
generator(output_file);
} catch (const debug_parser::Exception& exn) {
std::cerr << "\nError generating type scanners:\n"
<< exn.what() << std::endl << std::endl;
return 1;
}
} catch (const po::error& e) {
std::cerr << e.what() << "\n\n"
<< kProgramDescription << "\n\n"
<< desc << std::endl;
return 1;
}
return 0;
}
|
//-----------------------------------------------------------------------------
// Copyright (c) 2020 The Platinum Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "TrampolineGenerator.h"
#include <MBExtender/CodeStream.h>
#include <udis86/udis86.h>
namespace {
const size_t JumpSize = 5;
}
void *TrampolineGenerator::createTrampoline(void *src, size_t minSize, size_t &resultCodeSize) {
// Need to allocate space for overwritten instructions + a jump
auto codeSize = getCodeSize(src, minSize);
auto trampolineSize = codeSize + JumpSize;
// Allocate code for the trampoline
auto trampoline = allocator_->allocate(trampolineSize);
if (!trampoline)
return nullptr;
// Copy overwritten instructions from the source function to the trampoline
MBX::CodeStream stream(trampoline, trampolineSize);
stream.write(src, codeSize);
// Write a jump back to the code following the overwritten instructions
auto originalCode = static_cast<uint8_t *>(src) + codeSize;
stream.writeRel32Jump(originalCode);
resultCodeSize = codeSize;
return trampoline;
}
size_t TrampolineGenerator::getCodeSize(void *src, size_t minSize) {
ud_t ud;
ud_init(&ud);
ud_set_mode(&ud, 32);
ud_set_input_buffer(&ud, static_cast<uint8_t *>(src), static_cast<size_t>(-1));
ud_set_pc(&ud, reinterpret_cast<uint64_t>(src));
size_t size = 0;
while (size < minSize) {
// TODO: Relative offset relocation
auto len = ud_disassemble(&ud);
if (!len)
break;
size += len;
}
return size;
}
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#define STB_IMAGE_IMPLEMENTATION
#define STBI_ONLY_PNG
#include <stb/stb_image.h>
#include "simple_png.h"
#include "ColorSpaceTransform.h"
#include "AssetTexture.h"
#include "AssetUtil.h"
#include "ImageViewEngine.h"
#define INVALID_TEXTURE_ID 0xFFFFFFFF
AssetTexture::AssetTexture(const std::string& name) :
name_(name), p3Id_(INVALID_TEXTURE_ID), sRGBId_(INVALID_TEXTURE_ID),
valid_(false), dispColorSpace_(DISPLAY_COLORSPACE::INVALID)
{
}
AssetTexture::~AssetTexture() {
if (valid_) {
glDeleteTextures(1, &p3Id_);
glDeleteTextures(1, &sRGBId_);
valid_ = false;
p3Id_ = INVALID_TEXTURE_ID;
sRGBId_ = INVALID_TEXTURE_ID;
}
}
void AssetTexture::ColorSpace(enum DISPLAY_COLORSPACE space) {
ASSERT(space != DISPLAY_COLORSPACE::INVALID, "invalid dispColorSpace_");
// should release all of the previous valid textures...
dispColorSpace_ = space;
}
DISPLAY_COLORSPACE AssetTexture::ColorSpace(void) {
return dispColorSpace_;
}
bool AssetTexture::IsValid(void) {
return valid_;
}
GLuint AssetTexture::P3TexId() {
ASSERT(valid_, "Texture has not created");
return p3Id_;
}
GLuint AssetTexture::SRGBATexId() {
ASSERT(valid_, "texture has not been created");
return sRGBId_;
}
/*
* CreateGLTexture()
* Create textures with regard to current display_ color space.
* For P3 image, one texture is created with original image; the second
* texture is created from:
* original image --> sRGB color Space --> display_ color space
* during the process, colors outside sRGB are clamped.
*/
bool AssetTexture::CreateGLTextures(AAssetManager *mgr) {
ASSERT(mgr, "Asset Manager is not valid");
ASSERT(dispColorSpace_ != DISPLAY_COLORSPACE::INVALID, "eglContext_ color space not set");
if (valid_) {
glDeleteTextures(1, &p3Id_);
glDeleteTextures(1, &sRGBId_);
valid_ = false;
p3Id_ = INVALID_TEXTURE_ID;
sRGBId_ = INVALID_TEXTURE_ID;
}
glGenTextures(1, &p3Id_);
glBindTexture(GL_TEXTURE_2D, p3Id_);
std::vector<uint8_t> fileData;
AssetReadFile(mgr, name_, fileData);
uint32_t imgWidth, imgHeight, n;
uint8_t* imageData = stbi_load_from_memory(
fileData.data(), fileData.size(), reinterpret_cast<int*>(&imgWidth),
reinterpret_cast<int*>(&imgHeight), reinterpret_cast<int*>(&n), 4);
uint8_t* imgBits = imageData;
std::vector<uint8_t> staging;
if (dispColorSpace_ == DISPLAY_COLORSPACE::SRGB) {
staging.resize(imgWidth * imgHeight * 4 * sizeof(uint8_t));
IMAGE_FORMAT src {
.buf_ = imageData,
.width_ = imgWidth,
.height_ = imgHeight,
.gamma_ = DEFAULT_P3_IMAGE_GAMMA,
.npm_ = GetTransformNPM(NPM_TYPE::P3_D65),
};
IMAGE_FORMAT dst {
.buf_ = staging.data(),
.width_ = imgWidth,
.height_ = imgHeight,
.gamma_ = DEFAULT_DISPLAY_GAMMA,
.npm_ = GetTransformNPM(NPM_TYPE::SRGB_D65_INV),
};
TransformColorSpace(dst, src);
imgBits = staging.data();
}
glTexImage2D(GL_TEXTURE_2D, 0, // mip level
GL_RGBA,
imgWidth, imgHeight,
0, // border color
GL_RGBA, GL_UNSIGNED_BYTE, imgBits);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
// Generate sRGB view texture
glGenTextures(1, &sRGBId_);
glBindTexture(GL_TEXTURE_2D, sRGBId_);
if(dispColorSpace_ == DISPLAY_COLORSPACE::P3) {
IMAGE_FORMAT src {
.buf_ = imageData,
.width_ = imgWidth,
.height_ = imgHeight,
.gamma_ = DEFAULT_P3_IMAGE_GAMMA,
.npm_ = GetTransformNPM(NPM_TYPE::P3_D65),
};
std::vector<uint8_t> srgbImg(imgWidth * imgHeight * 4 * sizeof(uint8_t));
IMAGE_FORMAT dst{
.buf_ = srgbImg.data(),
.width_ = imgWidth,
.height_ = imgHeight,
.gamma_ = 0.0f, // intermediate image stays in linear space
.npm_ = GetTransformNPM(NPM_TYPE::SRGB_D65_INV),
};
TransformColorSpace(dst, src);
// sRGB back to P3 so we could display_ it correctly on P3 device mode
staging.resize(imgWidth * imgHeight * 4 * sizeof(uint8_t));
IMAGE_FORMAT tmp = src;
src = dst; // intermediate gamma is 0.0f
dst = tmp; // original src's gamma is preserved
src.npm_ = GetTransformNPM(NPM_TYPE::SRGB_D65);
dst.buf_ = staging.data();
dst.npm_ = GetTransformNPM(NPM_TYPE::P3_D65_INV);
dst.gamma_ = DEFAULT_DISPLAY_GAMMA,
TransformColorSpace(dst, src);
imgBits = staging.data();
}
glTexImage2D(GL_TEXTURE_2D, 0, // mip level
GL_RGBA,
imgWidth, imgHeight,
0, // border color
GL_RGBA, GL_UNSIGNED_BYTE, imgBits);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
glBindTexture(GL_TEXTURE_2D, 0);
stbi_image_free(imageData);
valid_ = true;
return true;
}
std::string& AssetTexture::Name(void) {
return name_;
}
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while(t--){
unsigned long long n, k;
cin >> n >> k;
if(k == 0){
cout << k << " " << n << endl;
}
else{
cout << n / k << " " << n % k << endl;
}
}
}
|
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/string_to_hash_bucket_ali_op.h"
#include "tensorflow/core/lib/hash/hash.h"
#include "tensorflow/core/platform/fingerprint.h"
#include "tensorflow/core/platform/strong_hash.h"
namespace tensorflow {
// StringToHashBucket is deprecated in favor of StringToHashBucketFast/Strong.
REGISTER_KERNEL_BUILDER(Name("StringToHashBucketFast").Device(DEVICE_CPU),
StringToHashBucketBatchAliOp<Fingerprint64>);
REGISTER_KERNEL_BUILDER(Name("StringToHashBucketStrong").Device(DEVICE_CPU),
StringToKeyedHashBucketAliOp<StrongKeyedHash>);
REGISTER_KERNEL_BUILDER(Name("StringToHash64").Device(DEVICE_CPU),
StringToHash64Op<Fingerprint64>);
} // namespace tensorflow
|
/**********************************************************************
** Copyright (C) 2000 Trolltech AS. All rights reserved.
**
** This file is part of Qt Designer.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
** information about Qt Commercial License Agreements.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
/*
This file is a self-contained interactive indenter for C++ and Qt
Script.
The general problem of indenting a C++ program is ill posed. On the
one hand, an indenter has to analyze programs written in a
free-form formal language that is best described in terms of
tokens, not characters, not lines. On the other hand, indentation
applies to lines and white space characters matter, and otherwise
the programs to indent are formally invalid in general, as they are
begin edited.
The approach taken here works line by line. We receive a program
consisting of N lines or more, and we want to compute the
indentation appropriate for the Nth line. Lines beyond the Nth
lines are of no concern to us, so for simplicity we pretend the
program has exactly N lines and we call the Nth line the "bottom
line". Typically, we have to indent the bottom line when it's still
empty, so we concentrate our analysis on the N - 1 lines that
precede.
By inspecting the (N - 1)-th line, the (N - 2)-th line, ...
backwards, we determine the kind of the bottom line and indent it
accordingly.
* The bottom line is a comment line. See
bottomLineStartsInCComment() and
indentWhenBottomLineStartsInCComment().
* The bottom line is a continuation line. See isContinuationLine()
and indentForContinuationLine().
* The bottom line is a standalone line. See
indentForStandaloneLine().
Certain tokens that influence the indentation, notably braces, are
looked for in the lines. This is done by simple string comparison,
without a real tokenizer. Confusing constructs such as comments and
string literals are removed beforehand.
*/
#include <qregexp.h>
/* qmake ignore Q_OBJECT */
/*
The indenter avoids getting stuck in almost infinite loops by
imposing arbitrary limits on the number of lines it analyzes when
looking for a construct.
For example, the indenter never considers more than BigRoof lines
backwards when looking for the start of a C-style comment.
*/
static const int SmallRoof = 40;
static const int BigRoof = 400;
/*
The indenter supports a few parameters:
* ppHardwareTabSize is the size of a '\t' in your favorite editor.
* ppIndentSize is the size of an indentation, or software tab
size.
* ppContinuationIndentSize is the extra indent for a continuation
line, when there is nothing to align against on the previous
line.
* ppCommentOffset is the indentation within a C-style comment,
when it cannot be picked up.
*/
static int ppHardwareTabSize = 8;
static int ppIndentSize = 4;
static int ppContinuationIndentSize = 8;
static const int ppCommentOffset = 2;
void setTabSize( int size )
{
ppHardwareTabSize = size;
}
void setIndentSize( int size )
{
ppIndentSize = size;
ppContinuationIndentSize = 2 * size;
}
static QRegExp *literal = 0;
static QRegExp *label = 0;
static QRegExp *inlineCComment = 0;
static QRegExp *braceX = 0;
static QRegExp *iflikeKeyword = 0;
/*
Returns the first non-space character in the string t, or
QChar::null if the string is made only of white space.
*/
static QChar firstNonWhiteSpace( const QString& t )
{
int i = 0;
while ( i < (int) t.length() ) {
if ( !t[i].isSpace() )
return t[i];
i++;
}
return QChar::null;
}
/*
Returns TRUE if string t is made only of white space; otherwise
returns FALSE.
*/
static bool isOnlyWhiteSpace( const QString& t )
{
return firstNonWhiteSpace( t ).isNull();
}
/*
Assuming string t is a line, returns the column number of a given
index. Column numbers and index are identical for strings that don't
contain '\t's.
*/
int columnForIndex( const QString& t, int index )
{
int col = 0;
if ( index > (int) t.length() )
index = t.length();
for ( int i = 0; i < index; i++ ) {
if ( t[i] == QChar('\t') ) {
col = ( (col / ppHardwareTabSize) + 1 ) * ppHardwareTabSize;
} else {
col++;
}
}
return col;
}
/*
Returns the indentation size of string t.
*/
int indentOfLine( const QString& t )
{
return columnForIndex( t, t.find(firstNonWhiteSpace(t)) );
}
/*
Replaces t[k] by ch, unless t[k] is '\t'. Tab characters are better
left alone since they break the "index equals column" rule. No
provisions are taken against '\n' or '\r', which shouldn't occur in
t anyway.
*/
static inline void eraseChar( QString& t, int k, QChar ch )
{
if ( t[k] != '\t' )
t[k] = ch;
}
/*
Removes some nefast constructs from a code line and returns the
resulting line.
*/
static QString trimmedCodeLine( const QString& t )
{
QString trimmed = t;
int k;
/*
Replace character and string literals by X's, since they may
contain confusing characters (such as '{' and ';'). "Hello!" is
replaced by XXXXXXXX. The literals are rigourously of the same
length before and after; otherwise, we would break alignment of
continuation lines.
*/
k = 0;
while ( (k = trimmed.find(*literal, k)) != -1 ) {
for ( int i = 0; i < literal->matchedLength(); i++ )
eraseChar( trimmed, k + i, 'X' );
k += literal->matchedLength();
}
/*
Replace inline C-style comments by spaces. Other comments are
handled elsewhere.
*/
k = 0;
while ( (k = trimmed.find(*inlineCComment, k)) != -1 ) {
for ( int i = 0; i < inlineCComment->matchedLength(); i++ )
eraseChar( trimmed, k + i, ' ' );
k += inlineCComment->matchedLength();
}
/*
Replace goto and switch labels by whitespace, but be careful
with this case:
foo1: bar1;
bar2;
*/
while ( trimmed.findRev(':') != -1 && trimmed.find(*label) != -1 ) {
QString cap1 = label->cap( 1 );
int pos1 = label->pos( 1 );
int stop = cap1.length();
if ( pos1 + stop < (int) trimmed.length() && ppIndentSize < stop )
stop = ppIndentSize;
int i = 0;
while ( i < stop ) {
eraseChar( trimmed, pos1 + i, ' ' );
i++;
}
while ( i < (int) cap1.length() ) {
eraseChar( trimmed, pos1 + i, ';' );
i++;
}
}
/*
Remove C++-style comments.
*/
k = trimmed.find( QString::fromLatin1("//") );
if ( k != -1 )
trimmed.truncate( k );
return trimmed;
}
/*
Returns '(' if the last parenthesis is opening, ')' if it is
closing, and QChar::null if there are no parentheses in t.
*/
static inline QChar lastParen( const QString& t )
{
int i = t.length();
while ( i > 0 ) {
i--;
if ( t[i] == QChar('(') || t[i] == QChar(')') )
return t[i];
}
return QChar::null;
}
/*
Returns TRUE if typedIn the same as okayCh or is null; otherwise
returns FALSE.
*/
static inline bool okay( QChar typedIn, QChar okayCh )
{
return typedIn == QChar::null || typedIn == okayCh;
}
/*
The "linizer" is a group of functions and variables to iterate
through the source code of the program to indent. The program is
given as a list of strings, with the bottom line being the line to
indent. The actual program might contain extra lines, but those are
uninteresting and not passed over to us.
*/
struct LinizerState
{
QString line;
int braceDepth;
bool leftBraceFollows;
QStringList::ConstIterator iter;
bool inCComment;
bool pendingRightBrace;
};
static QStringList *yyProgram = 0;
static LinizerState *yyLinizerState = 0;
// shorthands
static const QString *yyLine = 0;
static const int *yyBraceDepth = 0;
static const bool *yyLeftBraceFollows = 0;
/*
Saves and restores the state of the global linizer. This enables
backtracking.
*/
#define YY_SAVE() \
LinizerState savedState = *yyLinizerState
#define YY_RESTORE() \
*yyLinizerState = savedState
/*
Advances to the previous line in yyProgram and update yyLine
accordingly. yyLine is cleaned from comments and other damageable
constructs. Empty lines are skipped.
*/
static bool readLine()
{
int k;
yyLinizerState->leftBraceFollows =
( firstNonWhiteSpace(yyLinizerState->line) == QChar('{') );
do {
if ( yyLinizerState->iter == yyProgram->begin() ) {
yyLinizerState->line = QString::null;
return FALSE;
}
--yyLinizerState->iter;
yyLinizerState->line = *yyLinizerState->iter;
yyLinizerState->line = trimmedCodeLine( yyLinizerState->line );
/*
Remove C-style comments that span multiple lines. If the
bottom line starts in a C-style comment, we are not aware
of that and eventually yyLine will contain a slash-aster.
Notice that both if's can be executed, since
yyLinizerState->inCComment is potentially set to FALSE in
the first if. The order of the if's is also important.
*/
if ( yyLinizerState->inCComment ) {
QString slashAster( "/*" );
k = yyLinizerState->line.find( slashAster );
if ( k == -1 ) {
yyLinizerState->line = QString::null;
} else {
yyLinizerState->line.truncate( k );
yyLinizerState->inCComment = FALSE;
}
}
if ( !yyLinizerState->inCComment ) {
QString asterSlash( "*/" );
k = yyLinizerState->line.find( asterSlash );
if ( k != -1 ) {
for ( int i = 0; i < k + 2; i++ )
eraseChar( yyLinizerState->line, i, ' ' );
yyLinizerState->inCComment = TRUE;
}
}
/*
Remove preprocessor directives.
*/
k = 0;
while ( k < (int) yyLinizerState->line.length() ) {
QChar ch = yyLinizerState->line[k];
if ( ch == QChar('#') ) {
yyLinizerState->line = QString::null;
} else if ( !ch.isSpace() ) {
break;
}
k++;
}
/*
Remove trailing spaces.
*/
k = yyLinizerState->line.length();
while ( k > 0 && yyLinizerState->line[k - 1].isSpace() )
k--;
yyLinizerState->line.truncate( k );
/*
'}' increment the brace depth and '{' decrements it and not
the other way around, as we are parsing backwards.
*/
yyLinizerState->braceDepth +=
yyLinizerState->line.contains( '}' ) -
yyLinizerState->line.contains( '{' );
/*
We use a dirty trick for
} else ...
We don't count the '}' yet, so that it's more or less
equivalent to the friendly construct
}
else ...
*/
if ( yyLinizerState->pendingRightBrace )
yyLinizerState->braceDepth++;
yyLinizerState->pendingRightBrace =
( yyLinizerState->line.find(*braceX) == 0 );
if ( yyLinizerState->pendingRightBrace )
yyLinizerState->braceDepth--;
} while ( yyLinizerState->line.isEmpty() );
return TRUE;
}
/*
Resets the linizer to its initial state, with yyLine containing the
line above the bottom line of the program.
*/
static void startLinizer()
{
yyLinizerState->braceDepth = 0;
yyLinizerState->inCComment = FALSE;
yyLinizerState->pendingRightBrace = FALSE;
yyLine = &yyLinizerState->line;
yyBraceDepth = &yyLinizerState->braceDepth;
yyLeftBraceFollows = &yyLinizerState->leftBraceFollows;
yyLinizerState->iter = yyProgram->end();
--yyLinizerState->iter;
yyLinizerState->line = *yyLinizerState->iter;
readLine();
}
/*
Returns TRUE if the start of the bottom line of yyProgram (and
potentially the whole line) is part of a C-style comment; otherwise
returns FALSE.
*/
static bool bottomLineStartsInCComment()
{
QString slashAster( "/*" );
QString asterSlash( "*/" );
/*
We could use the linizer here, but that would slow us down
terribly. We are better to trim only the code lines we need.
*/
QStringList::ConstIterator p = yyProgram->end();
--p; // skip bottom line
for ( int i = 0; i < BigRoof; i++ ) {
if ( p == yyProgram->begin() )
return FALSE;
--p;
if ( (*p).find(slashAster) != -1 || (*p).find(asterSlash) != -1 ) {
QString trimmed = trimmedCodeLine( *p );
if ( trimmed.find(slashAster) != -1 ) {
return TRUE;
} else if ( trimmed.find(asterSlash) != -1 ) {
return FALSE;
}
}
}
return FALSE;
}
/*
Returns the recommended indent for the bottom line of yyProgram
assuming that it starts in a C-style comment, a condition that is
tested elsewhere.
Essentially, we're trying to align against some text on the previous
line.
*/
static int indentWhenBottomLineStartsInCComment()
{
int k = yyLine->findRev( QString::fromLatin1("/*") );
if ( k == -1 ) {
/*
We found a normal text line in a comment. Align the
bottom line with the text on this line.
*/
return indentOfLine( *yyLine );
} else {
/*
The C-style comment starts on this line. If there is
text on the same line, align with it. Otherwise, align
with the slash-aster plus a given offset.
*/
int indent = columnForIndex( *yyLine, k );
k += 2;
while ( k < (int) yyLine->length() ) {
if ( !(*yyLine)[k].isSpace() )
return columnForIndex( *yyLine, k );
k++;
}
return indent + ppCommentOffset;
}
}
/*
A function called match...() modifies the linizer state. If it
returns TRUE, yyLine is the top line of the matched construct;
otherwise, the linizer is left in an unknown state.
A function called is...() keeps the linizer state intact.
*/
/*
Returns TRUE if the current line (and upwards) forms a braceless
control statement; otherwise returns FALSE.
The first line of the following example is a "braceless control
statement":
if ( x )
y;
*/
static bool matchBracelessControlStatement()
{
int delimDepth = 0;
if ( yyLine->endsWith(QString::fromLatin1("else")) )
return TRUE;
if ( !yyLine->endsWith(QString::fromLatin1(")")) )
return FALSE;
for ( int i = 0; i < SmallRoof; i++ ) {
int j = yyLine->length();
while ( j > 0 ) {
j--;
QChar ch = (*yyLine)[j];
switch ( ch.unicode() ) {
case ')':
delimDepth++;
break;
case '(':
delimDepth--;
if ( delimDepth == 0 ) {
if ( yyLine->find(*iflikeKeyword) != -1 ) {
/*
We have
if ( x )
y
"if ( x )" is not part of the statement
"y".
*/
return TRUE;
}
}
if ( delimDepth == -1 ) {
/*
We have
if ( (1 +
2)
and not
if ( 1 +
2 )
*/
return FALSE;
}
break;
case '{':
case '}':
case ';':
/*
We met a statement separator, but not where we
expected it. What follows is probably a weird
continuation line. Be careful with ';' in for,
though.
*/
if ( ch != QChar(';') || delimDepth == 0 )
return FALSE;
}
}
if ( !readLine() )
break;
}
return FALSE;
}
/*
Returns TRUE if yyLine is an unfinished line; otherwise returns
FALSE.
In many places we'll use the terms "standalone line", "unfinished
line" and "continuation line". The meaning of these should be
evident from this code example:
a = b; // standalone line
c = d + // unfinished line
e + // unfinished continuation line
f + // unfinished continuation line
g; // continuation line
*/
static bool isUnfinishedLine()
{
bool unf = FALSE;
YY_SAVE();
if ( yyLine->isEmpty() )
return FALSE;
QChar lastCh = (*yyLine)[(int) yyLine->length() - 1];
if ( QString(QString::fromLatin1("{};")).find(lastCh) == -1 && !yyLine->endsWith(QString::fromLatin1("...")) ) {
/*
It doesn't end with ';' or similar. If it's neither
"Q_OBJECT" nor "if ( x )", it must be an unfinished line.
*/
unf = ( yyLine->contains(QString::fromLatin1("Q_OBJECT")) == 0 &&
!matchBracelessControlStatement() );
} else if ( lastCh == QChar(';') ) {
if ( lastParen(*yyLine) == QChar('(') ) {
/*
Exception:
for ( int i = 1; i < 10;
*/
unf = TRUE;
} else if ( readLine() && yyLine->endsWith(QString::fromLatin1(";")) &&
lastParen(*yyLine) == QChar('(') ) {
/*
Exception:
for ( int i = 1;
i < 10;
*/
unf = TRUE;
}
}
YY_RESTORE();
return unf;
}
/*
Returns TRUE if yyLine is a continuation line; otherwise returns
FALSE.
*/
static bool isContinuationLine()
{
bool cont = FALSE;
YY_SAVE();
if ( readLine() )
cont = isUnfinishedLine();
YY_RESTORE();
return cont;
}
/*
Returns the recommended indent for the bottom line of yyProgram,
assuming it's a continuation line.
We're trying to align the continuation line against some parenthesis
or other bracked left opened on a previous line, or some interesting
operator such as '='.
*/
static int indentForContinuationLine()
{
int braceDepth = 0;
int delimDepth = 0;
bool leftBraceFollowed = *yyLeftBraceFollows;
for ( int i = 0; i < SmallRoof; i++ ) {
int hook = -1;
int j = yyLine->length();
while ( j > 0 && hook < 0 ) {
j--;
QChar ch = (*yyLine)[j];
switch ( ch.unicode() ) {
case ')':
case ']':
delimDepth++;
break;
case '}':
braceDepth++;
break;
case '(':
case '[':
delimDepth--;
/*
An unclosed delimiter is a good place to align at,
at least for some styles (including Trolltech's).
*/
if ( delimDepth == -1 )
hook = j;
break;
case '{':
braceDepth--;
/*
A left brace followed by other stuff on the same
line is typically for an enum or an initializer.
Such a brace must be treated just like the other
delimiters.
*/
if ( braceDepth == -1 ) {
if ( j < (int) yyLine->length() - 1 ) {
hook = j;
} else {
return 0; // shouldn't happen
}
}
break;
case '=':
/*
An equal sign is a very natural alignment hook
because it's usually the operator with the lowest
precedence in statements it appears in. Case in
point:
int x = 1 +
2;
However, we have to beware of constructs such as
default arguments and explicit enum constant
values:
void foo( int x = 0,
int y = 0 );
And not
void foo( int x = 0,
int y = 0 );
These constructs are caracterized by a ',' at the
end of the unfinished lines or by unbalanced
parentheses.
*/
if ( QString("!=<>").find((*yyLine)[j - 1]) == -1 &&
(*yyLine)[j + 1] != '=' ) {
if ( braceDepth == 0 && delimDepth == 0 &&
j < (int) yyLine->length() - 1 &&
!yyLine->endsWith(QString::fromLatin1(",")) &&
(yyLine->contains('(') == yyLine->contains(')')) )
hook = j;
}
}
}
if ( hook >= 0 ) {
/*
Yes, we have a delimiter or an operator to align
against! We don't really align against it, but rather
against the following token, if any. In this example,
the following token is "11":
int x = ( 11 +
2 );
If there is no such token, we use a continuation indent:
static QRegExp foo( QString(
"foo foo foo foo foo foo foo foo foo") );
*/
hook++;
while ( hook < (int) yyLine->length() ) {
if ( !(*yyLine)[hook].isSpace() )
return columnForIndex( *yyLine, hook );
hook++;
}
return indentOfLine( *yyLine ) + ppContinuationIndentSize;
}
if ( braceDepth != 0 )
break;
/*
The line's delimiters are balanced. It looks like a
continuation line or something.
*/
if ( delimDepth == 0 ) {
if ( leftBraceFollowed ) {
/*
We have
int main()
{
or
Bar::Bar()
: Foo( x )
{
The "{" should be flush left.
*/
if ( !isContinuationLine() )
return indentOfLine( *yyLine );
} else if ( isContinuationLine() || yyLine->endsWith(QString::fromLatin1(",")) ) {
/*
We have
x = a +
b +
c;
or
int t[] = {
1, 2, 3,
4, 5, 6
The "c;" should fall right under the "b +", and the
"4, 5, 6" right under the "1, 2, 3,".
*/
return indentOfLine( *yyLine );
} else {
/*
We have
stream << 1 +
2;
We could, but we don't, try to analyze which
operator has precedence over which and so on, to
obtain the excellent result
stream << 1 +
2;
We do have a special trick above for the assignment
operator above, though.
*/
return indentOfLine( *yyLine ) + ppContinuationIndentSize;
}
}
if ( !readLine() )
break;
}
return 0;
}
/*
Returns the recommended indent for the bottom line of yyProgram if
that line is standalone (or should be indented likewise).
Indenting a standalone line is tricky, mostly because of braceless
control statements. Grossly, we are looking backwards for a special
line, a "hook line", that we can use as a starting point to indent,
and then modify the indentation level according to the braces met
along the way to that hook.
Let's consider a few examples. In all cases, we want to indent the
bottom line.
Example 1:
x = 1;
y = 2;
The hook line is "x = 1;". We met 0 opening braces and 0 closing
braces. Therefore, "y = 2;" inherits the indent of "x = 1;".
Example 2:
if ( x ) {
y;
The hook line is "if ( x ) {". No matter what precedes it, "y;" has
to be indented one level deeper than the hook line, since we met one
opening brace along the way.
Example 3:
if ( a )
while ( b ) {
c;
}
d;
To indent "d;" correctly, we have to go as far as the "if ( a )".
Compare with
if ( a ) {
while ( b ) {
c;
}
d;
Still, we're striving to go back as little as possible to accomodate
people with irregular indentation schemes. A hook line near at hand
is much more reliable than a remote one.
*/
static int indentForStandaloneLine()
{
for ( int i = 0; i < SmallRoof; i++ ) {
if ( !*yyLeftBraceFollows ) {
YY_SAVE();
if ( matchBracelessControlStatement() ) {
/*
The situation is this, and we want to indent "z;":
if ( x &&
y )
z;
yyLine is "if ( x &&".
*/
return indentOfLine( *yyLine ) + ppIndentSize;
}
YY_RESTORE();
}
if ( yyLine->endsWith(QString::fromLatin1(";")) || yyLine->contains('{') > 0 ) {
/*
The situation is possibly this, and we want to indent
"z;":
while ( x )
y;
z;
We return the indent of "while ( x )". In place of "y;",
any arbitrarily complex compound statement can appear.
*/
if ( *yyBraceDepth > 0 ) {
do {
if ( !readLine() )
break;
} while ( *yyBraceDepth > 0 );
}
LinizerState hookState;
while ( isContinuationLine() )
readLine();
hookState = *yyLinizerState;
readLine();
if ( *yyBraceDepth <= 0 ) {
do {
if ( !matchBracelessControlStatement() )
break;
hookState = *yyLinizerState;
} while ( readLine() );
}
*yyLinizerState = hookState;
while ( isContinuationLine() )
readLine();
/*
Never trust lines containing only '{' or '}', as some
people (Richard M. Stallman) format them weirdly.
*/
if ( yyLine->stripWhiteSpace().length() > 1 )
return indentOfLine( *yyLine ) - *yyBraceDepth * ppIndentSize;
}
if ( !readLine() )
return -*yyBraceDepth * ppIndentSize;
}
return 0;
}
/*
Constructs global variables used by the indenter.
*/
static void initializeIndenter()
{
literal = new QRegExp( QString::fromLatin1("([\"'])(?:\\\\.|[^\\\\])*\\1") );
literal->setMinimal( TRUE );
label = new QRegExp(
QString::fromLatin1("^\\s*((?:case\\b([^:]|::)+|[a-zA-Z_0-9]+)(?:\\s+slots)?:)(?!:)") );
inlineCComment = new QRegExp( QString::fromLatin1("/\\*.*\\*/") );
inlineCComment->setMinimal( TRUE );
braceX = new QRegExp( QString::fromLatin1("^\\s*\\}\\s*(?:else|catch)\\b") );
iflikeKeyword = new QRegExp( QString::fromLatin1("\\b(?:catch|do|for|if|while)\\b") );
yyLinizerState = new LinizerState;
}
/*
Destroys global variables used by the indenter.
*/
static void terminateIndenter()
{
delete literal;
delete label;
delete inlineCComment;
delete braceX;
delete iflikeKeyword;
delete yyLinizerState;
}
/*
Returns the recommended indent for the bottom line of program.
Unless null, typedIn stores the character of yyProgram that
triggered reindentation.
This function works better if typedIn is set properly; it is
slightly more conservative if typedIn is completely wild, and
slighly more liberal if typedIn is always null. The user might be
annoyed by the liberal behavior.
*/
int indentForBottomLine( const QStringList& program, QChar typedIn )
{
if ( program.isEmpty() )
return 0;
initializeIndenter();
yyProgram = new QStringList( program );
startLinizer();
const QString& bottomLine = program.last();
QChar firstCh = firstNonWhiteSpace( bottomLine );
int indent;
if ( bottomLineStartsInCComment() ) {
/*
The bottom line starts in a C-style comment. Indent it
smartly, unless the user has already played around with it,
in which case it's better to leave her stuff alone.
*/
if ( isOnlyWhiteSpace(bottomLine) ) {
indent = indentWhenBottomLineStartsInCComment();
} else {
indent = indentOfLine( bottomLine );
}
} else if ( okay(typedIn, '#') && firstCh == QChar('#') ) {
/*
Preprocessor directives go flush left.
*/
indent = 0;
} else {
if ( isUnfinishedLine() ) {
indent = indentForContinuationLine();
} else {
indent = indentForStandaloneLine();
}
if ( okay(typedIn, '}') && firstCh == QChar('}') ) {
/*
A closing brace is one level more to the left than the
code it follows.
*/
indent -= ppIndentSize;
} else if ( okay(typedIn, ':') ) {
QRegExp caseLabel(QString::fromLatin1(
"\\s*(?:case\\b(?:[^:]|::)+"
"|(?:public|protected|private|signals|default)(?:\\s+slots)?\\s*"
")?:.*") );
if ( caseLabel.exactMatch(bottomLine) ) {
/*
Move a case label (or the ':' in front of a
constructor initialization list) one level to the
left, but only if the user did not play around with
it yet. Some users have exotic tastes in the
matter, and most users probably are not patient
enough to wait for the final ':' to format their
code properly.
We don't attempt the same for goto labels, as the
user is probably the middle of "foo::bar". (Who
uses goto, anyway?)
*/
if ( indentOfLine(bottomLine) <= indent )
indent -= ppIndentSize;
else
indent = indentOfLine( bottomLine );
}
}
}
delete yyProgram;
terminateIndenter();
return QMAX( 0, indent );
}
#ifdef Q_TEST_YYINDENT
/*
Test driver.
*/
#include <qfile.h>
#include <qtextstream.h>
#include <errno.h>
static QString fileContents( const QString& fileName )
{
QFile f( fileName );
if ( !f.open(IO_ReadOnly) ) {
qWarning( "yyindent error: Cannot open file '%s' for reading: %s",
fileName.latin1(), strerror(errno) );
return QString::null;
}
QTextStream t( &f );
QString contents = t.read();
f.close();
if ( contents.isEmpty() )
qWarning( "yyindent error: File '%s' is empty", fileName.latin1() );
return contents;
}
int main( int argc, char **argv )
{
if ( argc != 2 ) {
qWarning( "usage: yyindent file.cpp" );
return 1;
}
QString code = fileContents( argv[1] );
QStringList program = QStringList::split( '\n', code, TRUE );
QStringList p;
QString out;
while ( !program.isEmpty() && program.last().stripWhiteSpace().isEmpty() )
program.remove( program.fromLast() );
QStringList::ConstIterator line = program.begin();
while ( line != program.end() ) {
p.push_back( *line );
QChar typedIn = firstNonWhiteSpace( *line );
if ( p.last().endsWith(":") )
typedIn = ':';
int indent = indentForBottomLine( p, typedIn );
if ( !(*line).stripWhiteSpace().isEmpty() ) {
for ( int j = 0; j < indent; j++ )
out += " ";
out += (*line).stripWhiteSpace();
}
out += "\n";
++line;
}
while ( out.endsWith("\n") )
out.truncate( out.length() - 1 );
printf( "%s\n", out.latin1() );
return 0;
}
#endif
|
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
#include "proton_bits.hpp"
#include "proton/connection.hpp"
#include "proton/container.hpp"
#include "proton/error.hpp"
#include "proton/event_loop.hpp"
#include "proton/receiver_options.hpp"
#include "proton/sender_options.hpp"
#include "proton/session.hpp"
#include "proton/session_options.hpp"
#include "proton/transport.hpp"
#include "contexts.hpp"
#include "msg.hpp"
#include "proton_bits.hpp"
#include <proton/connection.h>
#include <proton/session.h>
#include <proton/transport.h>
#include <proton/reactor.h>
#include <proton/object.h>
namespace proton {
transport connection::transport() const {
return make_wrapper(pn_connection_transport(pn_object()));
}
void connection::open() {
open(connection_options());
}
void connection::open(const connection_options &opts) {
opts.apply_unbound(*this);
pn_connection_open(pn_object());
}
void connection::close() { pn_connection_close(pn_object()); }
std::string connection::virtual_host() const {
return str(pn_connection_remote_hostname(pn_object()));
}
std::string connection::container_id() const {
return str(pn_connection_get_container(pn_object()));
}
std::string connection::user() const {
return str(pn_transport_get_user(pn_connection_transport(pn_object())));
}
container& connection::container() const {
class container* c = connection_context::get(pn_object()).container;
if (!c) {
pn_reactor_t *r = pn_object_reactor(pn_object());
if (r)
c = &container_context::get(r);
}
if (!c)
throw proton::error("connection does not have a container");
return *c;
}
session_range connection::sessions() const {
return session_range(session_iterator(make_wrapper(pn_session_head(pn_object(), 0))));
}
receiver_range connection::receivers() const {
pn_link_t *lnk = pn_link_head(pn_object(), 0);
while (lnk) {
if (pn_link_is_receiver(lnk))
break;
lnk = pn_link_next(lnk, 0);
}
return receiver_range(receiver_iterator(make_wrapper<receiver>(lnk)));
}
sender_range connection::senders() const {
pn_link_t *lnk = pn_link_head(pn_object(), 0);
while (lnk) {
if (pn_link_is_sender(lnk))
break;
lnk = pn_link_next(lnk, 0);
}
return sender_range(sender_iterator(make_wrapper<sender>(lnk)));
}
session connection::open_session() {
return open_session(session_options());
}
session connection::open_session(const session_options &opts) {
session s(make_wrapper<session>(pn_session(pn_object())));
// TODO: error check, too many sessions, no mem...
if (!!s) s.open(opts);
return s;
}
session connection::default_session() {
connection_context& ctx = connection_context::get(pn_object());
if (!ctx.default_session) {
// Note we can't use a proton::session here because we don't want to own
// a session reference. The connection owns the session, owning it here as well
// would create a circular ownership.
ctx.default_session = pn_session(pn_object());
pn_session_open(ctx.default_session);
}
return make_wrapper(ctx.default_session);
}
sender connection::open_sender(const std::string &addr) {
return open_sender(addr, sender_options());
}
sender connection::open_sender(const std::string &addr, const sender_options &opts) {
return default_session().open_sender(addr, opts);
}
receiver connection::open_receiver(const std::string &addr) {
return open_receiver(addr, receiver_options());
}
receiver connection::open_receiver(const std::string &addr, const receiver_options &opts)
{
return default_session().open_receiver(addr, opts);
}
error_condition connection::error() const {
return make_wrapper(pn_connection_remote_condition(pn_object()));
}
uint32_t connection::max_frame_size() const {
return pn_transport_get_remote_max_frame(pn_connection_transport(pn_object()));
}
uint16_t connection::max_sessions() const {
return pn_transport_remote_channel_max(pn_connection_transport(pn_object()));
}
uint32_t connection::idle_timeout() const {
return pn_transport_get_remote_idle_timeout(pn_connection_transport(pn_object()));
}
}
|
/* inih -- simple .INI file parser
inih is released under the New BSD license (see BSD-LICENSE.txt). Go to the project
home page for more info:
http://code.google.com/p/inih/
Copyright (c) 2009, Ben Hoyt
All rights reserved.
inih library license: https://raw.githubusercontent.com/benhoyt/inih/master/LICENSE.txt
Enhanced for use of C++11 syntax and features; May 2015, Roger D. Voss
clang-tidy inspection recommendations applied; Dec 2018, Roger D. Voss
*/
#include <cctype>
#include <cstring>
#include <cerrno>
#include <memory>
#include "ini.h"
#define MAX_SECTION 50
#define MAX_NAME 50
/* Strip whitespace chars off end of given string, in place. Return s. */
static char* rstrip(char* s)
{
char* p = s + strlen(s);
while (p > s && isspace((unsigned char)(*--p)) != 0) {
*p = '\0';
}
return s;
}
/* Return pointer to first non-whitespace char in given string. */
static char* lskip(char* s)
{
while (*s != '\0' && isspace((unsigned char)(*s)) != 0) {
s++;
}
return s;
}
/* Return pointer to first char c or ';' comment in given string, or pointer to
null at end of string if neither found. ';' must be prefixed by a whitespace
character to register as a comment. */
static char* find_char_or_comment(char* s, char c)
{
bool was_whitespace = false;
while (*s != '\0' && *s != c && !(was_whitespace && *s == ';')) {
was_whitespace = isspace((unsigned char)(*s)) != 0;
s++;
}
return s;
}
/* Version of strncpy that ensures dest (size bytes) is null-terminated. */
static char* strncpy0(char* dest, unsigned int dest_buf_size, const char* src, size_t size,
const err_code_handler_t &/*error_code*/)
{
if (size >= dest_buf_size) {
size = dest_buf_size - 1;
}
return strncpy(dest, src, size);
}
/* See documentation in header file. */
static int ini_parse_file_core(FILE* file, const cfg_parse_handler_t &handler, const err_code_handler_t &error_code)
{
/* Uses a fair bit of stack (use heap instead if you need to) */
char line[INI_MAX_LINE];
char section[MAX_SECTION] = "";
char prev_name[MAX_NAME] = "";
char* start = nullptr;
char* end = nullptr;
char* name = nullptr;
char* value = nullptr;
int lineno = 0;
int error = 0;
/* Scan through file line by line */
while (fgets(line, INI_MAX_LINE, file) != nullptr) {
lineno++;
start = line;
#if INI_ALLOW_BOM
if (lineno == 1 && (unsigned char)start[0] == 0xEF &&
(unsigned char)start[1] == 0xBB &&
(unsigned char)start[2] == 0xBF) {
start += 3;
}
#endif
start = lskip(rstrip(start));
if (*start == ';' || *start == '#') {
/* Per Python ConfigParser, allow '#' comments at start of line */
}
#if INI_ALLOW_MULTILINE
else if (*prev_name && *start && start > line) {
/* Non-black line with leading whitespace, treat as continuation
of previous name's value (as per Python ConfigParser). */
if (!handler(section, prev_name, start) && !error) {
error = lineno;size
}
else {
error_code(EILSEQ, __func__, __LINE__);
}
}
#endif
else if (*start == '[') {
/* A "[section]" line */
end = find_char_or_comment(start + 1, ']');
if (*end == ']') {
*end = '\0';
strncpy0(section, MAX_SECTION, start + 1, sizeof(section), error_code);
*prev_name = '\0';
}
else if (error == 0) {
/* No ']' found on section line */
error = lineno;
}
else {
error_code(EILSEQ, __func__, __LINE__);
}
}
else if (*start != '\0' && *start != ';') {
/* Not a comment, must be a name[=:]value pair */
end = find_char_or_comment(start, '=');
if (*end != '=') {
end = find_char_or_comment(start, ':');
}
if (*end == '=' || *end == ':') {
*end = '\0';
name = rstrip(start);
value = lskip(end + 1);
end = find_char_or_comment(value, '\0');
if (*end == ';') {
*end = '\0';
}
rstrip(value);
/* Valid name[=:]value pair found, call handler */
strncpy0(prev_name, MAX_NAME, name, sizeof(prev_name), error_code);
if (handler(section, name, value) == 0 && error == 0) {
error = lineno;
}
}
else if (error == 0) {
/* No '=' or ':' found on name[=:]value line */
error = lineno;
}
else {
error_code(EILSEQ, __func__, __LINE__);
}
}
#if INI_STOP_ON_FIRST_ERROR
if (error != 0) { break; }
#endif
}
return error;
}
/* See documentation in header file. */
int ini_parse(FILE* file, const cfg_parse_handler_t &handler, const err_code_handler_t &error_code)
{
return ini_parse_file_core(file, handler, error_code);
}
int ini_parse(const char* filename, const cfg_parse_handler_t &handler, const err_code_handler_t &error_code)
{
int error = 0;
auto const close_file = [&error](FILE *f) {
if (f != nullptr) {
if (fclose(f) != 0) {
error = errno;
}
}
};
FILE* const file = fopen(filename, "r");
if (file == nullptr) {
error_code(errno, __func__, __LINE__); // open file error
return -1;
}
std::unique_ptr<FILE, decltype(close_file)> file_sp(file, close_file);
const int err = ini_parse_file_core(file, handler, error_code);
file_sp.reset(nullptr);
if (err != 0) {
error_code(err, __func__, __LINE__); // parse file error
return -1;
}
if (error != 0) {
error_code(error, __func__, __LINE__); // close file error
return -1;
}
return 0;
}
|
#include "libb.h"
std::string hello_libb(void) {
return hello_liba() + " Hello from LIBB!";
}
|
//..............................................................................
//
// This file is part of the AXL library.
//
// AXL is distributed under the MIT license.
// For details see accompanying license.txt file,
// the public copy of which is also available at:
// http://tibbo.com/downloads/archive/axl/license.txt
//
//..............................................................................
#include "pch.h"
#include "axl_io_File.h"
#include "axl_io_Mapping.h"
namespace axl {
namespace io {
//..............................................................................
#if (_AXL_OS_WIN)
bool
File::open(
const sl::StringRef& fileName,
uint_t flags
) {
uint_t accessMode =
(flags & FileFlag_ReadOnly) ? GENERIC_READ :
(flags & FileFlag_WriteOnly) ? GENERIC_WRITE : GENERIC_READ | GENERIC_WRITE;
if (flags & FileFlag_WriteAttributes)
accessMode |= FILE_WRITE_ATTRIBUTES;
uint_t shareMode =
(flags & FileFlag_Exclusive) ? 0 :
(flags & (FileFlag_ReadOnly | FileFlag_ShareWrite)) ?
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE :
FILE_SHARE_READ;
uint_t creationDisposition = (flags & (FileFlag_ReadOnly | FileFlag_OpenExisting)) ?
OPEN_EXISTING :
OPEN_ALWAYS;
uint_t flagsAttributes = (flags & FileFlag_DeleteOnClose) ?
FILE_FLAG_DELETE_ON_CLOSE :
0;
if (flags & FileFlag_Asynchronous)
flagsAttributes |= FILE_FLAG_OVERLAPPED;
char buffer[256];
sl::String_w fileName_w(rc::BufKind_Stack, buffer, sizeof(buffer));
fileName_w = fileName;
bool result = m_file.create(
fileName_w,
accessMode,
shareMode,
NULL,
creationDisposition,
flagsAttributes
);
if (!result)
return false;
if (flags & FileFlag_Clear)
m_file.setSize(0);
return true;
}
#elif (_AXL_OS_POSIX)
bool
File::open(
const sl::StringRef& fileName,
uint_t flags
) {
uint_t posixFlags =
(flags & FileFlag_ReadOnly) ? O_RDONLY :
(flags & FileFlag_WriteOnly) ? O_WRONLY : O_RDWR;
if (!(flags & (FileFlag_ReadOnly | FileFlag_OpenExisting)))
posixFlags |= O_CREAT;
if (flags & FileFlag_Asynchronous)
posixFlags |= O_NONBLOCK;
// TODO: handle exclusive and share write flags with fcntl locks
bool result = m_file.open(fileName.sz(), posixFlags);
if (!result)
return false;
if (flags & FileFlag_Unlink)
::unlink(fileName.sz());
if (flags & FileFlag_Clear)
m_file.setSize(0);
return true;
}
#endif
//..............................................................................
uint64_t
copyFile(
const sl::StringRef& srcFileName,
const sl::StringRef& dstFileName,
uint64_t size
) {
File srcFile;
bool result = srcFile.open(srcFileName, FileFlag_ReadOnly);
if (!result)
return -1;
return copyFile(&srcFile, dstFileName, size);
}
uint64_t
copyFile(
const io::File* srcFile,
const sl::StringRef& dstFileName,
uint64_t size
) {
File dstFile;
bool result = dstFile.open(dstFileName);
if (!result)
return -1;
return copyFile(srcFile, &dstFile, size);
}
uint64_t
copyFile(
const io::File* srcFile,
io::File* dstFile,
uint64_t size
) {
enum {
BaseBlockSize = 64 * 1024, // 64K
};
bool result;
const g::SystemInfo* systemInfo = g::getModule()->getSystemInfo();
size_t blockSize = BaseBlockSize + systemInfo->m_mappingAlignFactor - BaseBlockSize % systemInfo->m_mappingAlignFactor;
uint64_t offset = 0;
if (size == -1)
size = srcFile->getSize();
result = dstFile->setSize(size);
if (!result)
return -1;
#if (_AXL_OS_WIN)
win::Mapping srcMapping;
win::Mapping dstMapping;
win::MappedView srcView;
win::MappedView dstView;
result =
srcMapping.create(srcFile->m_file, NULL, PAGE_READONLY, size) &&
dstMapping.create(dstFile->m_file, NULL, PAGE_READWRITE, size);
if (!result)
return -1;
while (size) {
if (blockSize > size)
blockSize = (size_t)size;
const void* src = srcView.view(srcMapping, FILE_MAP_READ, offset, blockSize);
void* dst = dstView.view(dstMapping, FILE_MAP_READ | FILE_MAP_WRITE, offset, blockSize);
if (!src || !dst)
return -1;
memcpy(dst, src, blockSize);
offset += blockSize;
size -= blockSize;
}
srcMapping.close();
dstMapping.close();
srcView.close();
dstView.close();
#else
psx::Mapping srcMapping;
psx::Mapping dstMapping;
while (size) {
if (blockSize > size)
blockSize = (size_t)size;
const void* src = srcMapping.map(NULL, blockSize, PROT_READ, MAP_SHARED, srcFile->m_file, offset);
void* dst = dstMapping.map(NULL, blockSize, PROT_READ | PROT_WRITE, MAP_SHARED, dstFile->m_file, offset);
if (!src || !dst)
return -1;
memcpy(dst, src, blockSize);
offset += blockSize;
size -= blockSize;
}
srcMapping.close();
dstMapping.close();
#endif
return offset;
}
//..............................................................................
} // namespace io
} // namespace axl
|
/*ckwg +29
* Copyright 2017 by Kitware, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither name of Kitware, Inc. nor the names of any contributors may be used
* to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <arrows/kpf/kwiver_algo_kpf_plugin_export.h>
#include <vital/algo/algorithm_factory.h>
#include <arrows/kpf/detected_object_set_input_kpf.h>
#include <arrows/kpf/detected_object_set_output_kpf.h>
namespace kwiver {
namespace arrows {
namespace kpf {
extern "C"
KWIVER_ALGO_KPF_PLUGIN_EXPORT
void
register_factories( kwiver::vital::plugin_loader& vpm )
{
static auto const module_name = std::string( "arrows.kpf" );
if (vpm.is_module_loaded( module_name ) )
{
return;
}
// add factory implementation-name type-to-create
auto fact = vpm.ADD_ALGORITHM( "kpf_input", kwiver::arrows::kpf::detected_object_set_input_kpf);
fact->add_attribute( kwiver::vital::plugin_factory::PLUGIN_DESCRIPTION,
"Detected object set reader using kpf format." )
.add_attribute( kwiver::vital::plugin_factory::PLUGIN_MODULE_NAME, module_name )
.add_attribute( kwiver::vital::plugin_factory::PLUGIN_VERSION, "1.0" )
.add_attribute( kwiver::vital::plugin_factory::PLUGIN_ORGANIZATION, "Kitware Inc." )
;
fact = vpm.ADD_ALGORITHM( "kpf_output", kwiver::arrows::kpf::detected_object_set_output_kpf);
fact->add_attribute( kwiver::vital::plugin_factory::PLUGIN_DESCRIPTION,
"Detected object set writer using kpf format.t" )
.add_attribute( kwiver::vital::plugin_factory::PLUGIN_MODULE_NAME, module_name )
.add_attribute( kwiver::vital::plugin_factory::PLUGIN_VERSION, "1.0" )
.add_attribute( kwiver::vital::plugin_factory::PLUGIN_ORGANIZATION, "Kitware Inc." )
;
vpm.mark_module_as_loaded( module_name );
}
} } } // end namespace
|
/**
* __author__ = anonymized
* __date__ = 2019-05
* __copyright__ = Creative Commons CC0
*/
#include <stdint.h>
#include <gtest/gtest.h>
#include "ciphers/small_aes_toy6_sbox.h"
#include "utils/utils.h"
using ciphers::small_aes_ctx_t;
using ciphers::small_aes_key_t;
using ciphers::small_aes_state_t;
using utils::assert_equal;
// ---------------------------------------------------------
TEST(Small_AES_TOY6_SBOX, test_key_schedule) {
const small_aes_key_t key = {
0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef
};
small_aes_ctx_t ctx;
small_aes_key_setup(&ctx, key);
uint8_t round_key[16];
const uint8_t expected_round_keys[16 * SMALL_AES_NUM_ROUND_KEYS] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x00, 0x01, 0x0a, 0x00, 0x04, 0x04, 0x0c, 0x07,
0x0c, 0x0d, 0x06, 0x0c, 0x00, 0x00, 0x08, 0x03,
0x04, 0x08, 0x0e, 0x06, 0x00, 0x0c, 0x02, 0x01,
0x0c, 0x01, 0x04, 0x0d, 0x0c, 0x01, 0x0c, 0x0e,
0x0b, 0x0b, 0x0e, 0x05, 0x0b, 0x07, 0x0c, 0x04,
0x07, 0x06, 0x08, 0x09, 0x0b, 0x07, 0x04, 0x07,
0x09, 0x09, 0x04, 0x09, 0x02, 0x0e, 0x08, 0x0d,
0x05, 0x08, 0x00, 0x04, 0x0e, 0x0f, 0x04, 0x03,
0x02, 0x0b, 0x00, 0x09, 0x00, 0x05, 0x08, 0x04,
0x05, 0x0d, 0x08, 0x00, 0x0b, 0x02, 0x0c, 0x03,
0x01, 0x08, 0x04, 0x05, 0x01, 0x0d, 0x0c, 0x01,
0x04, 0x00, 0x04, 0x01, 0x0f, 0x02, 0x08, 0x02,
0x08, 0x01, 0x01, 0x0d, 0x09, 0x0c, 0x0d, 0x0c,
0x0d, 0x0c, 0x09, 0x0d, 0x02, 0x0e, 0x01, 0x0f,
0x03, 0x0a, 0x09, 0x08, 0x0a, 0x06, 0x04, 0x04,
0x07, 0x0a, 0x0d, 0x09, 0x05, 0x04, 0x0c, 0x06,
0x04, 0x09, 0x0e, 0x06, 0x0e, 0x0f, 0x0a, 0x02,
0x09, 0x05, 0x07, 0x0b, 0x0c, 0x01, 0x0b, 0x0d,
0x05, 0x05, 0x0f, 0x05, 0x0b, 0x0a, 0x05, 0x07,
0x02, 0x0f, 0x02, 0x0c, 0x0e, 0x0e, 0x09, 0x01
};
for (size_t i = 0; i < SMALL_AES_NUM_ROUND_KEYS; ++i) {
const uint8_t *start_expected_round_key = expected_round_keys + i * 16;
storeu(round_key, ctx.key[i]);
ASSERT_TRUE(assert_equal(start_expected_round_key, round_key, 16));
}
}
// ---------------------------------------------------------
TEST(Small_AES_TOY6_SBOX,
test_encrypt_6_rounds_only_sbox_in_final_with_aes_ni) {
const small_aes_key_t key = {
0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef
};
const __m128i plaintext = vsetr8(
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
);
const __m128i expected_ciphertext = vsetr8(
0x0b, 0x07, 0x0d, 0x01, 0x01, 0x07, 0x0f, 0x07,
0x0d, 0x0d, 0x00, 0x08, 0x06, 0x03, 0x04, 0x04
);
const size_t num_rounds = 6;
small_aes_ctx_t ctx;
small_aes_key_setup(&ctx, key);
__m128i ciphertext =
small_aes_toy6_sbox_encrypt_rounds_only_sbox_in_final_with_aes_ni(
&ctx,
plaintext,
num_rounds
);
ASSERT_TRUE(vare_equal(expected_ciphertext, ciphertext));
}
// ---------------------------------------------------------
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
// ---------------------------------------------------------
|
#include "driver.h"
#include <math.h>
#include "vidhrdw/vector.h"
#include "dirty.h"
dirtygrid grid1;
dirtygrid grid2;
char *dirty_old=grid1;
char *dirty_new=grid2;
/* in msdos/sound.c */
int msdos_update_audio(void);
/* specialized update_screen functions defined in blit.c */
/* dirty mode 1 (VIDEO_SUPPORTS_DIRTY) */
void blitscreen_dirty1_color8(struct osd_bitmap *bitmap);
void blitscreen_dirty1_color16(struct osd_bitmap *bitmap);
void blitscreen_dirty1_palettized16(struct osd_bitmap *bitmap);
/* dirty mode 0 (no osd_mark_dirty calls) */
void blitscreen_dirty0_color8(struct osd_bitmap *bitmap);
void blitscreen_dirty0_color16(struct osd_bitmap *bitmap);
void blitscreen_dirty0_palettized16(struct osd_bitmap *bitmap);
static void update_screen_dummy(struct osd_bitmap *bitmap);
void (*update_screen)(struct osd_bitmap *bitmap) = update_screen_dummy;
static int video_depth,video_fps;
static int modifiable_palette;
static int screen_colors;
static unsigned char *current_palette;
static unsigned int *dirtycolor;
static int dirtypalette;
static int dirty_bright;
static int bright_lookup[256];
extern UINT32 *palette_16bit_lookup;
int frameskip,autoframeskip;
#define FRAMESKIP_LEVELS 12
int video_sync;
int wait_vsync;
int vsync_frame_rate;
int skiplines;
int skipcolumns;
int use_dirty;
float osd_gamma_correction = 1.0;
int brightness;
float brightness_paused_adjust;
int gfx_width;
int gfx_height;
static int viswidth;
static int visheight;
static int skiplinesmax;
static int skipcolumnsmax;
static int skiplinesmin;
static int skipcolumnsmin;
int vector_game;
int gfx_xoffset;
int gfx_yoffset;
int gfx_display_lines;
int gfx_display_columns;
static int xmultiply,ymultiply;
int throttle = 1; /* toggled by F10 */
static int frameskip_counter;
#include "minimal.h"
#define TICKER unsigned long
#define ticker() gp2x_timer_read()
#define vsync() gp2x_video_wait_vsync()
#define makecol(r,g,b) gp2x_video_color15(r,g,b,0)
#define getr(c) gp2x_video_getr15(c)
#define getg(c) gp2x_video_getg15(c)
#define getb(c) gp2x_video_getb15(c)
static struct osd_bitmap *mybitmap;
int video_scale=0;
int video_border=0;
int video_aspect=0;
void gp2x_video_wait_vsync(void)
{
}
/* Create a bitmap. Also calls osd_clearbitmap() to appropriately initialize */
/* it to the background color. */
/* VERY IMPORTANT: the function must allocate also a "safety area" 16 pixels wide all */
/* around the bitmap. This is required because, for performance reasons, some graphic */
/* routines don't clip at boundaries of the bitmap. */
const int safety = 16;
struct osd_bitmap *osd_alloc_bitmap(int width,int height,int depth)
{
struct osd_bitmap *bitmap;
if ((bitmap = (struct osd_bitmap *)malloc(sizeof(struct osd_bitmap))) != 0)
{
int i,rowlen,rdwidth;
unsigned char *bm;
if (depth != 8 && depth != 16) depth = 8;
bitmap->depth = depth;
bitmap->width = width;
bitmap->height = height;
rdwidth = (width + 7) & ~7; /* round width to a quadword */
if (depth == 16)
rowlen = 2 * (rdwidth + 2 * safety) * sizeof(unsigned char);
else
rowlen = (rdwidth + 2 * safety) * sizeof(unsigned char);
if ((bm = (unsigned char*)malloc((height + 2 * safety) * rowlen)) == 0)
{
free(bitmap);
return 0;
}
/* clear ALL bitmap, including safety area, to avoid garbage on right */
/* side of screen is width is not a multiple of 4 */
memset(bm,0,(height + 2 * safety) * rowlen);
if ((bitmap->line = (unsigned char**)malloc((height + 2 * safety) * sizeof(unsigned char *))) == 0)
{
free(bm);
free(bitmap);
return 0;
}
for (i = 0;i < height + 2 * safety;i++)
{
if (depth == 16)
bitmap->line[i] = &bm[i * rowlen + 2*safety];
else
bitmap->line[i] = &bm[i * rowlen + safety];
}
bitmap->line += safety;
bitmap->_private = bm;
osd_clearbitmap(bitmap);
}
mybitmap = bitmap;
return bitmap;
}
/* set the bitmap to black */
void osd_clearbitmap(struct osd_bitmap *bitmap)
{
int i;
for (i = 0;i < bitmap->height;i++)
{
if (bitmap->depth == 16)
memset(bitmap->line[i],0,2*bitmap->width);
else
memset(bitmap->line[i],0,bitmap->width);
}
if (bitmap == Machine->scrbitmap)
{
extern int bitmap_dirty; /* in mame.c */
osd_mark_dirty (0,0,bitmap->width-1,bitmap->height-1,1);
bitmap_dirty = 1;
}
}
void osd_free_bitmap(struct osd_bitmap *bitmap)
{
if (bitmap)
{
bitmap->line -= safety;
free(bitmap->line);
free(bitmap->_private);
free(bitmap);
}
}
void osd_mark_dirty(int _x1, int _y1, int _x2, int _y2, int ui)
{
if (use_dirty)
{
int x, y;
// logerror("mark_dirty %3d,%3d - %3d,%3d\n", _x1,_y1, _x2,_y2);
_x1 -= skipcolumns;
_x2 -= skipcolumns;
_y1 -= skiplines;
_y2 -= skiplines;
if (_y1 >= gfx_display_lines || _y2 < 0 || _x1 > gfx_display_columns || _x2 < 0) return;
if (_y1 < 0) _y1 = 0;
if (_y2 >= gfx_display_lines) _y2 = gfx_display_lines - 1;
if (_x1 < 0) _x1 = 0;
if (_x2 >= gfx_display_columns) _x2 = gfx_display_columns - 1;
for (y = _y1; y <= _y2 + 15; y += 16)
for (x = _x1; x <= _x2 + 15; x += 16)
MARKDIRTY(x,y);
}
}
static void init_dirty(char dirty)
{
memset(dirty_new, dirty, MAX_GFX_WIDTH/16 * MAX_GFX_HEIGHT/16);
}
INLINE void swap_dirty(void)
{
char *tmp;
tmp = dirty_old;
dirty_old = dirty_new;
dirty_new = tmp;
}
/*
* This function tries to find the best display mode.
*/
static void select_display_mode(int width,int height,int depth,int attributes,int orientation)
{
//SQ we're only using 8bit, no 16bit support for maximum performance
/* 16 bit color is supported only by VESA modes */
if (depth == 16 || depth == 32)
{
logerror("Game needs %d-bit colors.\n",depth);
}
if (!gfx_width && !gfx_height)
{
gfx_height = height;
//SQ, make sure width is divisible by 32, no idea why without this it
//breaks the display. Possibly required by dispmanx?
if (width%32 > 0) {
gfx_width = ((width/32) + 1)*32;
}
else {
gfx_width = width;
}
}
/* Border TV-Out */
if (video_border)
{
gfx_width=(((gfx_width+((gfx_width*6)/100))+7)&~7);
gfx_height=(((gfx_height+((gfx_height*8)/100))+7)&~7);
}
}
/* center image inside the display based on the visual area */
void osd_set_visible_area(int min_x,int max_x,int min_y,int max_y)
{
int act_width;
logerror("set visible area %d-%d %d-%d\n",min_x,max_x,min_y,max_y);
act_width = gfx_width;
viswidth = max_x - min_x + 1;
visheight = max_y - min_y + 1;
/* setup xmultiply to handle SVGA driver's (possible) double width */
xmultiply = 1;
ymultiply = 1;
gfx_display_lines = visheight;
gfx_display_columns = viswidth;
gfx_xoffset = (act_width - viswidth * xmultiply) / 2;
if (gfx_display_columns > act_width / xmultiply)
gfx_display_columns = act_width / xmultiply;
gfx_yoffset = (gfx_height - visheight * ymultiply) / 2;
if (gfx_display_lines > gfx_height / ymultiply)
gfx_display_lines = gfx_height / ymultiply;
skiplinesmin = min_y;
skiplinesmax = visheight - gfx_display_lines + min_y;
skipcolumnsmin = min_x;
skipcolumnsmax = viswidth - gfx_display_columns + min_x;
/* Align on a quadword !*/
gfx_xoffset &= ~7;
/* the skipcolumns from mame.cfg/cmdline is relative to the visible area */
skipcolumns = min_x + skipcolumns;
skiplines = min_y + skiplines;
/* Just in case the visual area doesn't fit */
if (gfx_xoffset < 0)
{
skipcolumns -= gfx_xoffset;
gfx_xoffset = 0;
}
if (gfx_yoffset < 0)
{
skiplines -= gfx_yoffset;
gfx_yoffset = 0;
}
/* Failsafe against silly parameters */
if (skiplines < skiplinesmin)
skiplines = skiplinesmin;
if (skipcolumns < skipcolumnsmin)
skipcolumns = skipcolumnsmin;
if (skiplines > skiplinesmax)
skiplines = skiplinesmax;
if (skipcolumns > skipcolumnsmax)
skipcolumns = skipcolumnsmax;
logerror("gfx_width = %d gfx_height = %d\n"
"gfx_xoffset = %d gfx_yoffset = %d\n"
"xmin %d ymin %d xmax %d ymax %d\n"
"skiplines %d skipcolumns %d\n"
"gfx_display_lines %d gfx_display_columns %d\n"
"xmultiply %d ymultiply %d\n",
gfx_width,gfx_height,
gfx_xoffset,gfx_yoffset,
min_x, min_y, max_x, max_y, skiplines, skipcolumns,gfx_display_lines,gfx_display_columns,xmultiply,ymultiply);
set_ui_visarea(skipcolumns, skiplines, skipcolumns+gfx_display_columns-1, skiplines+gfx_display_lines-1);
/* round to a multiple of 4 to avoid missing pixels on the right side */
gfx_display_columns = (gfx_display_columns + 3) & ~3;
}
/*
Create a display screen, or window, of the given dimensions (or larger).
Attributes are the ones defined in driver.h.
Returns 0 on success.
*/
int osd_create_display(int width,int height,int depth,int fps,int attributes,int orientation)
{
logerror("width %d, height %d\n", width,height);
printf("[trngaje] video.cpp:osd_create_display++\n");
video_depth = depth;
video_fps = fps;
brightness = 100;
brightness_paused_adjust = 1.0;
dirty_bright = 1;
if (frameskip < 0) frameskip = 0;
if (frameskip >= FRAMESKIP_LEVELS) frameskip = FRAMESKIP_LEVELS-1;
/* Look if this is a vector game */
if (attributes & VIDEO_TYPE_VECTOR)
vector_game = 1;
else
vector_game = 0;
if (use_dirty == -1) /* dirty=auto in mame.cfg? */
{
/* Is the game using a dirty system? */
if ((attributes & VIDEO_SUPPORTS_DIRTY) || vector_game)
use_dirty = 1;
else
use_dirty = 0;
}
select_display_mode(width,height,depth,attributes,orientation);
if (!osd_set_display(width,height,depth,attributes,orientation))
return 1;
printf("[trngaje] video.cpp:osd_create_display-step1\n");
/* set visible area to nothing just to initialize it - it will be set by the core */
osd_set_visible_area(0,0,0,0);
printf("[trngaje] video.cpp:osd_create_display--\n");
return 0;
}
/* set the actual display screen but don't allocate the screen bitmap */
int osd_set_display(int width,int height,int depth,int attributes,int orientation)
{
int i;
printf("[trngaje] video.cpp: osd_set_display\n");
if (!gfx_height || !gfx_width)
{
printf("Please specify height AND width (e.g. -640x480)\n");
return 0;
}
/* Mark the dirty buffers as dirty */
if (use_dirty)
{
if (vector_game)
/* vector games only use one dirty buffer */
init_dirty (0);
else
init_dirty(1);
swap_dirty();
init_dirty(1);
}
if (dirtycolor)
{
for (i = 0;i < screen_colors;i++)
dirtycolor[i] = 1;
dirtypalette = 1;
}
/* Set video mode */
gp2x_set_video_mode(mybitmap, depth, gfx_width, gfx_height);
vsync_frame_rate = video_fps;
printf("[trngaje] video.cpp: osd_set_display-step2\n");
if (video_sync)
{
TICKER a,b;
float rate;
printf("[trngaje] video.cpp: osd_set_display-step3\n");
/* wait some time to let everything stabilize */
for (i = 0;i < 60;i++)
{
vsync();
a = ticker();
}
printf("[trngaje] video.cpp: osd_set_display-step4\n");
/* small delay for really really fast machines */
for (i = 0;i < 100000;i++) ;
vsync();
b = ticker();
rate = ((float)TICKS_PER_SEC)/(b-a);
logerror("target frame rate = %ffps, video frame rate = %3.2fHz\n",video_fps,rate);
/* don't allow more than 8% difference between target and actual frame rate */
while (rate > video_fps * 108 / 100)
rate /= 2;
if (rate < video_fps * 92 / 100)
{
osd_close_display();
logerror("-vsync option cannot be used with this display mode:\n"
"video refresh frequency = %dHz, target frame rate = %ffps\n",
(int)(TICKS_PER_SEC/(b-a)),video_fps);
return 0;
}
logerror("adjusted video frame rate = %3.2fHz\n",rate);
vsync_frame_rate = rate;
printf("[trngaje] video.cpp: osd_set_display-step5\n");
if (Machine->sample_rate)
{
Machine->sample_rate = Machine->sample_rate * video_fps / rate;
logerror("sample rate adjusted to match video freq: %d\n",Machine->sample_rate);
}
printf("[trngaje] video.cpp: osd_set_display-step6\n");
}
printf("[trngaje] video.cpp: osd_set_display--\n");
return 1;
}
/* shut up the display */
void osd_close_display(void)
{
free(dirtycolor);
dirtycolor = 0;
free(current_palette);
current_palette = 0;
free(palette_16bit_lookup);
palette_16bit_lookup = 0;
}
int osd_allocate_colors(unsigned int totalcolors,const unsigned char *palette,unsigned short *pens,int modifiable)
{
int i;
modifiable_palette = modifiable;
screen_colors = totalcolors;
if (video_depth != 8)
screen_colors += 2;
else screen_colors = 256;
dirtycolor = (unsigned int*)malloc(screen_colors * sizeof(int));
current_palette = (unsigned char*)malloc(3 * screen_colors * sizeof(unsigned char));
palette_16bit_lookup = (UINT32*)malloc(screen_colors * sizeof(palette_16bit_lookup[0]));
if (dirtycolor == 0 || current_palette == 0 || palette_16bit_lookup == 0)
return 1;
for (i = 0;i < screen_colors;i++)
dirtycolor[i] = 1;
dirtypalette = 1;
for (i = 0;i < screen_colors;i++)
current_palette[3*i+0] = current_palette[3*i+1] = current_palette[3*i+2] = 0;
if (video_depth != 8 && modifiable == 0)
{
int r,g,b;
for (i = 0;i < totalcolors;i++)
{
r = 255 * brightness * pow(palette[3*i+0] / 255.0, 1 / osd_gamma_correction) / 100;
g = 255 * brightness * pow(palette[3*i+1] / 255.0, 1 / osd_gamma_correction) / 100;
b = 255 * brightness * pow(palette[3*i+2] / 255.0, 1 / osd_gamma_correction) / 100;
*pens++ = makecol(r,g,b);
}
Machine->uifont->colortable[0] = makecol(0x00,0x00,0x00);
Machine->uifont->colortable[1] = makecol(0xff,0xff,0xff);
Machine->uifont->colortable[2] = makecol(0xff,0xff,0xff);
Machine->uifont->colortable[3] = makecol(0x00,0x00,0x00);
}
else
{
if (video_depth == 8 && totalcolors >= 255)
{
int bestblack,bestwhite;
int bestblackscore,bestwhitescore;
bestblack = bestwhite = 0;
bestblackscore = 3*255*255;
bestwhitescore = 0;
for (i = 0;i < totalcolors;i++)
{
int r,g,b,score;
r = palette[3*i+0];
g = palette[3*i+1];
b = palette[3*i+2];
score = r*r + g*g + b*b;
if (score < bestblackscore)
{
bestblack = i;
bestblackscore = score;
}
if (score > bestwhitescore)
{
bestwhite = i;
bestwhitescore = score;
}
}
for (i = 0;i < totalcolors;i++)
pens[i] = i;
/* map black to pen 0, otherwise the screen border will not be black */
pens[bestblack] = 0;
pens[0] = bestblack;
Machine->uifont->colortable[0] = pens[bestblack];
Machine->uifont->colortable[1] = pens[bestwhite];
Machine->uifont->colortable[2] = pens[bestwhite];
Machine->uifont->colortable[3] = pens[bestblack];
}
else
{
/* reserve color 1 for the user interface text */
current_palette[3*1+0] = current_palette[3*1+1] = current_palette[3*1+2] = 0xff;
Machine->uifont->colortable[0] = 0;
Machine->uifont->colortable[1] = 1;
Machine->uifont->colortable[2] = 1;
Machine->uifont->colortable[3] = 0;
/* fill the palette starting from the end, so we mess up badly written */
/* drivers which don't go through Machine->pens[] */
for (i = 0;i < totalcolors;i++)
pens[i] = (screen_colors-1)-i;
}
for (i = 0;i < totalcolors;i++)
{
current_palette[3*pens[i]+0] = palette[3*i];
current_palette[3*pens[i]+1] = palette[3*i+1];
current_palette[3*pens[i]+2] = palette[3*i+2];
}
}
if (video_depth == 16)
{
if (modifiable_palette)
{
if (use_dirty)
{
update_screen = blitscreen_dirty1_palettized16;
logerror("blitscreen_dirty1_palettized16\n");
}
else
{
update_screen = blitscreen_dirty0_palettized16;
logerror("blitscreen_dirty0_palettized16\n");
}
}
else
{
if (use_dirty)
{
update_screen = blitscreen_dirty1_color16;
logerror("blitscreen_dirty1_color16\n");
}
else
{
update_screen = blitscreen_dirty0_color16;
logerror("blitscreen_dirty0_color16\n");
}
}
}
else
{
if (use_dirty) /* supports dirty ? */
{
update_screen = blitscreen_dirty1_color8;
logerror("blitscreen_dirty1_color8\n");
}
else
{
update_screen = blitscreen_dirty0_color8;
logerror("blitscreen_dirty0_color8\n");
}
}
return 0;
}
void osd_modify_pen(int pen,unsigned char red, unsigned char green, unsigned char blue)
{
if (modifiable_palette == 0)
{
logerror("error: osd_modify_pen() called with modifiable_palette == 0\n");
return;
}
if (current_palette[3*pen+0] != red ||
current_palette[3*pen+1] != green ||
current_palette[3*pen+2] != blue)
{
current_palette[3*pen+0] = red;
current_palette[3*pen+1] = green;
current_palette[3*pen+2] = blue;
dirtycolor[pen] = 1;
dirtypalette = 1;
}
}
void osd_get_pen(int pen,unsigned char *red, unsigned char *green, unsigned char *blue)
{
if (video_depth != 8 && modifiable_palette == 0)
{
*red = getr(pen);
*green = getg(pen);
*blue = getb(pen);
}
else
{
*red = current_palette[3*pen+0];
*green = current_palette[3*pen+1];
*blue = current_palette[3*pen+2];
}
}
static void update_screen_dummy(struct osd_bitmap *bitmap)
{
logerror("msdos/video.c: undefined update_screen() function for %d x %d!\n",xmultiply,ymultiply);
}
INLINE void pan_display(void)
{
int pan_changed = 0;
/* horizontal panning */
if (input_ui_pressed_repeat(IPT_UI_PAN_LEFT,1))
if (skipcolumns < skipcolumnsmax)
{
skipcolumns++;
osd_mark_dirty (0,0,Machine->scrbitmap->width-1,Machine->scrbitmap->height-1,1);
pan_changed = 1;
}
if (input_ui_pressed_repeat(IPT_UI_PAN_RIGHT,1))
if (skipcolumns > skipcolumnsmin)
{
skipcolumns--;
osd_mark_dirty (0,0,Machine->scrbitmap->width-1,Machine->scrbitmap->height-1,1);
pan_changed = 1;
}
if (input_ui_pressed_repeat(IPT_UI_PAN_DOWN,1))
if (skiplines < skiplinesmax)
{
skiplines++;
osd_mark_dirty (0,0,Machine->scrbitmap->width-1,Machine->scrbitmap->height-1,1);
pan_changed = 1;
}
if (input_ui_pressed_repeat(IPT_UI_PAN_UP,1))
if (skiplines > skiplinesmin)
{
skiplines--;
osd_mark_dirty (0,0,Machine->scrbitmap->width-1,Machine->scrbitmap->height-1,1);
pan_changed = 1;
}
if (pan_changed)
{
if (use_dirty) init_dirty(1);
set_ui_visarea (skipcolumns, skiplines, skipcolumns+gfx_display_columns-1, skiplines+gfx_display_lines-1);
}
}
int osd_skip_this_frame(void)
{
static const int skiptable[FRAMESKIP_LEVELS][FRAMESKIP_LEVELS] =
{
{ 0,0,0,0,0,0,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,0,0,0,0,0,1 },
{ 0,0,0,0,0,1,0,0,0,0,0,1 },
{ 0,0,0,1,0,0,0,1,0,0,0,1 },
{ 0,0,1,0,0,1,0,0,1,0,0,1 },
{ 0,1,0,0,1,0,1,0,0,1,0,1 },
{ 0,1,0,1,0,1,0,1,0,1,0,1 },
{ 0,1,0,1,1,0,1,0,1,1,0,1 },
{ 0,1,1,0,1,1,0,1,1,0,1,1 },
{ 0,1,1,1,0,1,1,1,0,1,1,1 },
{ 0,1,1,1,1,1,0,1,1,1,1,1 },
{ 0,1,1,1,1,1,1,1,1,1,1,1 }
};
return skiptable[frameskip][frameskip_counter];
}
/* Update the display. */
void osd_update_video_and_audio(struct osd_bitmap *bitmap)
{
static const int waittable[FRAMESKIP_LEVELS][FRAMESKIP_LEVELS] =
{
{ 1,1,1,1,1,1,1,1,1,1,1,1 },
{ 2,1,1,1,1,1,1,1,1,1,1,0 },
{ 2,1,1,1,1,0,2,1,1,1,1,0 },
{ 2,1,1,0,2,1,1,0,2,1,1,0 },
{ 2,1,0,2,1,0,2,1,0,2,1,0 },
{ 2,0,2,1,0,2,0,2,1,0,2,0 },
{ 2,0,2,0,2,0,2,0,2,0,2,0 },
{ 2,0,2,0,0,3,0,2,0,0,3,0 },
{ 3,0,0,3,0,0,3,0,0,3,0,0 },
{ 4,0,0,0,4,0,0,0,4,0,0,0 },
{ 6,0,0,0,0,0,6,0,0,0,0,0 },
{12,0,0,0,0,0,0,0,0,0,0,0 }
};
int i;
static int showfps,showfpstemp;
TICKER curr;
static TICKER prev_measure=0,this_frame_base,prev;
static int speed = 100;
static int vups,vfcount;
int have_to_clear_bitmap = 0;
if (prev_measure==0)
{
/* first time through, initialize timer */
prev_measure = ticker() - FRAMESKIP_LEVELS * TICKS_PER_SEC/video_fps;
}
if (frameskip_counter == 0)
this_frame_base = prev_measure + FRAMESKIP_LEVELS * TICKS_PER_SEC/video_fps;
/* update audio */
msdos_update_audio();
if (osd_skip_this_frame() == 0)
{
if (showfpstemp)
{
showfpstemp--;
if (showfps == 0 && showfpstemp == 0)
{
have_to_clear_bitmap = 1;
}
}
if (input_ui_pressed(IPT_UI_SHOW_FPS))
{
if (showfpstemp)
{
showfpstemp = 0;
have_to_clear_bitmap = 1;
}
else
{
showfps ^= 1;
if (showfps == 0)
{
have_to_clear_bitmap = 1;
}
}
}
/* now wait until it's time to update the screen */
if (throttle)
{
profiler_mark(PROFILER_IDLE);
if (video_sync)
{
static TICKER last;
do
{
vsync();
curr = ticker();
} while (TICKS_PER_SEC / (curr - last) > video_fps * 11 /10);
last = curr;
}
else
{
TICKER target;
/* wait for video sync but use normal throttling */
if (wait_vsync)
vsync();
curr = ticker();
target = this_frame_base + frameskip_counter * TICKS_PER_SEC/video_fps;
if ((curr < target) && (target-curr<TICKS_PER_SEC))
{
do
{
curr = ticker();
} while ((curr < target) && (target-curr<TICKS_PER_SEC));
}
}
profiler_mark(PROFILER_END);
}
else curr = ticker();
if (frameskip_counter == 0)
{
int divdr;
divdr = video_fps * (curr - prev_measure) / (100 * FRAMESKIP_LEVELS);
if (divdr==0)
divdr=1;
speed = (TICKS_PER_SEC + divdr/2) / divdr;
prev_measure = curr;
}
prev = curr;
vfcount += waittable[frameskip][frameskip_counter];
if (vfcount >= video_fps)
{
extern int vector_updates; /* avgdvg_go_w()'s per Mame frame, should be 1 */
vfcount = 0;
vups = vector_updates;
vector_updates = 0;
}
if (showfps || showfpstemp)
{
int fps;
char buf[30];
int divdr;
divdr = 100 * FRAMESKIP_LEVELS;
fps = (video_fps * (FRAMESKIP_LEVELS - frameskip) * speed + (divdr / 2)) / divdr;
sprintf(buf,"%s%2d%4d%%%4d/%d fps",autoframeskip?"auto":"fskp",frameskip,speed,fps,(int)(video_fps+0.5));
ui_text(bitmap,buf,Machine->uiwidth-strlen(buf)*Machine->uifontwidth,0);
if (vector_game)
{
sprintf(buf," %d vector updates",vups);
ui_text(bitmap,buf,Machine->uiwidth-strlen(buf)*Machine->uifontwidth,Machine->uifontheight);
}
}
if (bitmap->depth == 8)
{
if (dirty_bright)
{
dirty_bright = 0;
for (i = 0;i < 256;i++)
{
float rate = brightness * brightness_paused_adjust * pow(i / 255.0, 1 / osd_gamma_correction) / 100;
bright_lookup[i] = 255 * rate + 0.5;
}
}
if (dirtypalette)
{
dirtypalette = 0;
for (i = 0;i < screen_colors;i++)
{
if (dirtycolor[i])
{
unsigned char r,g,b;
dirtycolor[i] = 0;
r = current_palette[3*i+0];
g = current_palette[3*i+1];
b = current_palette[3*i+2];
if (i != Machine->uifont->colortable[1]) /* don't adjust the user interface text */
{
r = bright_lookup[r];
g = bright_lookup[g];
b = bright_lookup[b];
}
gp2x_video_color8(i,r,g,b);
}
}
gp2x_video_setpalette();
}
}
else
{
if (dirty_bright)
{
dirty_bright = 0;
for (i = 0;i < 256;i++)
{
float rate = brightness * brightness_paused_adjust * pow(i / 255.0, 1 / osd_gamma_correction) / 100;
bright_lookup[i] = 255 * rate + 0.5;
}
}
if (dirtypalette)
{
if (use_dirty) init_dirty(1); /* have to redraw the whole screen */
dirtypalette = 0;
for (i = 0;i < screen_colors;i++)
{
if (dirtycolor[i])
{
int r,g,b;
dirtycolor[i] = 0;
r = current_palette[3*i+0];
g = current_palette[3*i+1];
b = current_palette[3*i+2];
if (i != Machine->uifont->colortable[1]) /* don't adjust the user interface text */
{
r = bright_lookup[r];
g = bright_lookup[g];
b = bright_lookup[b];
}
palette_16bit_lookup[i] = makecol(r,g,b);
}
}
gp2x_video_setpalette();
}
}
/* copy the bitmap to screen memory */
profiler_mark(PROFILER_BLIT);
update_screen(bitmap);
profiler_mark(PROFILER_END);
if (have_to_clear_bitmap)
osd_clearbitmap(bitmap);
if (use_dirty)
{
if (!vector_game)
swap_dirty();
init_dirty(0);
}
if (have_to_clear_bitmap)
osd_clearbitmap(bitmap);
if (throttle && autoframeskip && frameskip_counter == 0)
{
static int frameskipadjust;
int adjspeed;
/* adjust speed to video refresh rate if vsync is on */
adjspeed = speed * video_fps / vsync_frame_rate;
if (adjspeed >= 92)
{
frameskipadjust++;
if (frameskipadjust >= 3)
{
frameskipadjust = 0;
#ifdef GP2X
{
if (frameskip > 0)
frameskip--;
}
#else
if (frameskip > 0) frameskip--;
#endif
}
}
else
{
if (adjspeed < 80)
frameskipadjust -= (90 - adjspeed) / 5;
else
{
/* don't push frameskip too far if we are close to 100% speed */
if (frameskip < 8)
frameskipadjust--;
}
while (frameskipadjust <= -2)
{
frameskipadjust += 2;
if (frameskip < FRAMESKIP_LEVELS-1) frameskip++;
}
}
}
}
/* Check for PGUP, PGDN and pan screen */
pan_display();
if (input_ui_pressed(IPT_UI_FRAMESKIP_INC))
{
if (autoframeskip)
{
autoframeskip = 0;
frameskip = 0;
}
else
{
if (frameskip == FRAMESKIP_LEVELS-1)
{
frameskip = 0;
autoframeskip = 1;
}
else
frameskip++;
}
if (showfps == 0)
showfpstemp = 2*video_fps;
}
if (input_ui_pressed(IPT_UI_FRAMESKIP_DEC))
{
if (autoframeskip)
{
autoframeskip = 0;
frameskip = FRAMESKIP_LEVELS-1;
}
else
{
if (frameskip == 0)
autoframeskip = 1;
else
frameskip--;
}
if (showfps == 0)
showfpstemp = 2*video_fps;
}
if (input_ui_pressed(IPT_UI_THROTTLE))
{
throttle ^= 1;
update_throttle();
}
frameskip_counter = (frameskip_counter + 1) % FRAMESKIP_LEVELS;
}
void osd_set_gamma(float _gamma)
{
int i;
osd_gamma_correction = _gamma;
for (i = 0;i < screen_colors;i++)
dirtycolor[i] = 1;
dirtypalette = 1;
dirty_bright = 1;
}
float osd_get_gamma(void)
{
return osd_gamma_correction;
}
/* brightess = percentage 0-100% */
void osd_set_brightness(int _brightness)
{
int i;
brightness = _brightness;
for (i = 0;i < screen_colors;i++)
dirtycolor[i] = 1;
dirtypalette = 1;
dirty_bright = 1;
}
int osd_get_brightness(void)
{
return brightness;
}
void osd_save_snapshot(struct osd_bitmap *bitmap)
{
save_screen_snapshot(bitmap);
}
void osd_pause(int paused)
{
int i;
if (paused) brightness_paused_adjust = 0.65;
else brightness_paused_adjust = 1.0;
for (i = 0;i < screen_colors;i++)
dirtycolor[i] = 1;
dirtypalette = 1;
dirty_bright = 1;
}
|
#ifndef __TRACYPROTOCOL_HPP__
#define __TRACYPROTOCOL_HPP__
#include <limits>
#include <stdint.h>
namespace tracy
{
constexpr unsigned Lz4CompressBound( unsigned isize ) { return isize + ( isize / 255 ) + 16; }
enum : uint32_t { ProtocolVersion = 40 };
enum : uint32_t { BroadcastVersion = 1 };
using lz4sz_t = uint32_t;
enum { TargetFrameSize = 256 * 1024 };
enum { LZ4Size = Lz4CompressBound( TargetFrameSize ) };
static_assert( LZ4Size <= std::numeric_limits<lz4sz_t>::max(), "LZ4Size greater than lz4sz_t" );
static_assert( TargetFrameSize * 2 >= 64 * 1024, "Not enough space for LZ4 stream buffer" );
enum { HandshakeShibbolethSize = 8 };
static const char HandshakeShibboleth[HandshakeShibbolethSize] = { 'T', 'r', 'a', 'c', 'y', 'P', 'r', 'f' };
enum HandshakeStatus : uint8_t
{
HandshakePending,
HandshakeWelcome,
HandshakeProtocolMismatch,
HandshakeNotAvailable,
HandshakeDropped
};
enum { WelcomeMessageProgramNameSize = 64 };
enum { WelcomeMessageHostInfoSize = 1024 };
#pragma pack( 1 )
// Must increase left query space after handling!
enum ServerQuery : uint8_t
{
ServerQueryTerminate,
ServerQueryString,
ServerQueryThreadString,
ServerQuerySourceLocation,
ServerQueryPlotName,
ServerQueryCallstackFrame,
ServerQueryFrameName,
ServerQueryDisconnect,
ServerQueryExternalName,
ServerQueryParameter,
ServerQuerySymbol,
ServerQuerySymbolCode,
ServerQueryCodeLocation
};
struct ServerQueryPacket
{
ServerQuery type;
uint64_t ptr;
uint32_t extra;
};
enum { ServerQueryPacketSize = sizeof( ServerQueryPacket ) };
enum CpuArchitecture : uint8_t
{
CpuArchUnknown,
CpuArchX86,
CpuArchX64,
CpuArchArm32,
CpuArchArm64
};
struct WelcomeMessage
{
double timerMul;
int64_t initBegin;
int64_t initEnd;
uint64_t delay;
uint64_t resolution;
uint64_t epoch;
uint64_t pid;
int64_t samplingPeriod;
uint8_t onDemand;
uint8_t isApple;
uint8_t cpuArch;
uint8_t codeTransfer;
char cpuManufacturer[12];
uint32_t cpuId;
char programName[WelcomeMessageProgramNameSize];
char hostInfo[WelcomeMessageHostInfoSize];
};
enum { WelcomeMessageSize = sizeof( WelcomeMessage ) };
struct OnDemandPayloadMessage
{
uint64_t frames;
uint64_t currentTime;
};
enum { OnDemandPayloadMessageSize = sizeof( OnDemandPayloadMessage ) };
struct BroadcastMessage
{
uint32_t broadcastVersion;
uint32_t protocolVersion;
uint32_t listenPort;
uint32_t activeTime; // in seconds
char programName[WelcomeMessageProgramNameSize];
};
enum { BroadcastMessageSize = sizeof( BroadcastMessage ) };
#pragma pack()
}
#endif
|
//
// base class to resolve hit ambiguities. This class also interacts with the
// simulated annealing.
//
// Original author: David Brown (LBNL), 2012
//
// $Id: AmbigResolver.hh,v 1.4 2014/08/01 18:56:10 gandr Exp $
// $Author: gandr $
// $Date: 2014/08/01 18:56:10 $
//
#ifndef AmbigResolver_HH
#define AmbigResolver_HH
#include "BTrk/BaBar/BaBar.hh"
#include <vector>
class KalRep;
class TrkSimpTraj;
namespace mu2e {
class TrkStrawHit;
class AmbigResolver {
public:
explicit AmbigResolver(double tmpErr);
virtual ~AmbigResolver() = 0;
// resolve a track. Depending on the configuration, this might
// update the hit state and the t0 value.
virtual bool resolveTrk(KalRep* kfit) const = 0;
protected:
// reset penalty errors
virtual void initHitErrors(KalRep* kfit) const ;
// find the local trajectory piece computed from the fit excluding a particular set of hits.
// the hits are assumed to be contiguous
const TrkSimpTraj* findTraj(std::vector<TrkStrawHit*> const& phits, const KalRep* krep) const;
double _tmpErr; // hit error associated with annealing 'temperature'
};
}
#endif
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include <BinaryProtoLookupService.h>
#include <pulsar/Client.h>
#include <gtest/gtest.h>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <Future.h>
#include <Utils.h>
#include "ConnectionPool.h"
#include "HttpHelper.h"
#include <pulsar/Authentication.h>
#include <boost/exception/all.hpp>
DECLARE_LOG_OBJECT()
using namespace pulsar;
TEST(BinaryLookupServiceTest, basicLookup) {
ExecutorServiceProviderPtr service = boost::make_shared<ExecutorServiceProvider>(1);
AuthenticationPtr authData = AuthFactory::Disabled();
std::string url = "pulsar://localhost:8885";
ClientConfiguration conf;
ExecutorServiceProviderPtr ioExecutorProvider_(boost::make_shared<ExecutorServiceProvider>(1));
ConnectionPool pool_(conf, ioExecutorProvider_, authData, true);
BinaryProtoLookupService lookupService(pool_, url);
std::string topic = "persistent://prop/unit/ns1/topic";
TopicNamePtr topicName = TopicName::get(topic);
Future<Result, LookupDataResultPtr> partitionFuture = lookupService.getPartitionMetadataAsync(topicName);
LookupDataResultPtr lookupData;
Result result = partitionFuture.get(lookupData);
ASSERT_TRUE(lookupData != NULL);
ASSERT_EQ(0, lookupData->getPartitions());
Future<Result, LookupDataResultPtr> future =
lookupService.lookupAsync("persistent://prop/unit/ns1/topic");
result = future.get(lookupData);
ASSERT_EQ(ResultOk, result);
ASSERT_TRUE(lookupData != NULL);
ASSERT_EQ(url, lookupData->getBrokerUrl());
}
TEST(BinaryLookupServiceTest, basicGetNamespaceTopics) {
std::string url = "pulsar://localhost:8885";
std::string adminUrl = "http://localhost:8765/";
Result result;
// 1. create some topics under same namespace
Client client(url);
std::string topicName1 = "persistent://prop/unit/ns4/basicGetNamespaceTopics1";
std::string topicName2 = "persistent://prop/unit/ns4/basicGetNamespaceTopics2";
std::string topicName3 = "persistent://prop/unit/ns4/basicGetNamespaceTopics3";
// This is not in same namespace.
std::string topicName4 = "persistent://prop/unit/ns2/basicGetNamespaceTopics4";
// call admin api to make topics partitioned
std::string url1 = adminUrl + "admin/persistent/prop/unit/ns4/basicGetNamespaceTopics1/partitions";
std::string url2 = adminUrl + "admin/persistent/prop/unit/ns4/basicGetNamespaceTopics2/partitions";
std::string url3 = adminUrl + "admin/persistent/prop/unit/ns4/basicGetNamespaceTopics3/partitions";
int res = makePutRequest(url1, "2");
ASSERT_FALSE(res != 204 && res != 409);
res = makePutRequest(url2, "3");
ASSERT_FALSE(res != 204 && res != 409);
res = makePutRequest(url3, "4");
ASSERT_FALSE(res != 204 && res != 409);
Producer producer1;
result = client.createProducer(topicName1, producer1);
ASSERT_EQ(ResultOk, result);
Producer producer2;
result = client.createProducer(topicName2, producer2);
ASSERT_EQ(ResultOk, result);
Producer producer3;
result = client.createProducer(topicName3, producer3);
ASSERT_EQ(ResultOk, result);
Producer producer4;
result = client.createProducer(topicName4, producer4);
ASSERT_EQ(ResultOk, result);
// 2. call getTopicsOfNamespaceAsync
ExecutorServiceProviderPtr service = boost::make_shared<ExecutorServiceProvider>(1);
AuthenticationPtr authData = AuthFactory::Disabled();
ClientConfiguration conf;
ExecutorServiceProviderPtr ioExecutorProvider_(boost::make_shared<ExecutorServiceProvider>(1));
ConnectionPool pool_(conf, ioExecutorProvider_, authData, true);
BinaryProtoLookupService lookupService(pool_, url);
TopicNamePtr topicName = TopicName::get(topicName1);
NamespaceNamePtr nsName = topicName->getNamespaceName();
Future<Result, NamespaceTopicsPtr> getTopicsFuture = lookupService.getTopicsOfNamespaceAsync(nsName);
NamespaceTopicsPtr topicsData;
result = getTopicsFuture.get(topicsData);
ASSERT_EQ(ResultOk, result);
ASSERT_TRUE(topicsData != NULL);
// 3. verify result contains first 3 topic
ASSERT_EQ(topicsData->size(), 3);
ASSERT_TRUE(std::find(topicsData->begin(), topicsData->end(), topicName1) != topicsData->end());
ASSERT_TRUE(std::find(topicsData->begin(), topicsData->end(), topicName2) != topicsData->end());
ASSERT_TRUE(std::find(topicsData->begin(), topicsData->end(), topicName3) != topicsData->end());
client.shutdown();
}
|
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace ktl;
using namespace Data::Utilities;
ULONG32 NULL_OPERATION_DATA_COUNT = MAXULONG;
OperationData::OperationData()
: KObject()
, KShared()
, buffers_(GetThisAllocator())
{
if (!NT_SUCCESS(buffers_.Status()))
{
throw Exception(buffers_.Status());
}
}
OperationData::OperationData(__in KArray<KBuffer::CSPtr> const & buffers)
: KObject()
, KShared()
, buffers_(buffers)
{
if (!NT_SUCCESS(buffers_.Status()))
{
throw Exception(buffers_.Status());
}
}
OperationData::~OperationData()
{
}
OperationData::SPtr OperationData::Create(__in KAllocator & allocator)
{
OperationData* pointer = _new(OPERATIONDATA_TAG, allocator) OperationData();
if (!pointer)
{
throw Exception(STATUS_INSUFFICIENT_RESOURCES);
}
return OperationData::SPtr(pointer);
}
OperationData::CSPtr OperationData::Create(
__in KArray<KBuffer::CSPtr> const & buffers,
__in KAllocator & allocator)
{
OperationData const * pointer = _new(OPERATIONDATA_TAG, allocator) OperationData(buffers);
if (!pointer)
{
throw Exception(STATUS_INSUFFICIENT_RESOURCES);
}
return OperationData::CSPtr(pointer);;
}
OperationData::CSPtr OperationData::Create(
__in OperationData const& operationData,
__in KAllocator& allocator)
{
return Create(
operationData,
0,
operationData.BufferCount,
allocator);
}
OperationData::CSPtr OperationData::Create(
__in OperationData const& operationData,
__in ULONG32 startingIndex,
__in ULONG32 count,
__in KAllocator& allocator)
{
ASSERT_IFNOT(
startingIndex + count <= operationData.BufferCount,
"Starting index: {0} + count: {1} should be <= operation data buffer count: {2}",
startingIndex, count, operationData.BufferCount);
if (count == 0)
{
return Create(allocator).RawPtr();
}
OperationData * pointer = _new(OPERATIONDATA_TAG, allocator) OperationData(allocator);
if (!pointer)
{
throw Exception(STATUS_INSUFFICIENT_RESOURCES);
}
// Shallow copy
for (ULONG32 i = startingIndex; i < startingIndex + count; i++)
{
pointer->Append(*operationData[i]);
}
return OperationData::CSPtr(pointer);
}
KBuffer::CSPtr OperationData::IncrementIndexAndGetBuffer(
__in OperationData const & operationData,
__inout INT & index)
{
index += 1;
return operationData[index];
}
void OperationData::Serialize(
__inout BinaryWriter & binaryWriter,
__in_opt OperationData const * const toSerialize,
__inout OperationData & serializedOutput)
{
ULONG startPos = binaryWriter.Position;
if (!toSerialize)
{
binaryWriter.Write(NULL_OPERATION_DATA_COUNT);
KBuffer::SPtr countBuffer = binaryWriter.GetBuffer(startPos);
serializedOutput.Append(*countBuffer);
return;
}
// Ensure maximum number of buffers is less than the MAXULONG as this is used for encoding an empty buffer
ASSERT_IFNOT(toSerialize->BufferCount < MAXULONG, "Buffer count should be less than MAXULONG");
binaryWriter.Write(toSerialize->BufferCount);
KBuffer::SPtr buffer = binaryWriter.GetBuffer(startPos);
serializedOutput.Append(*buffer);
for (ULONG i = 0; i < toSerialize->BufferCount; i++)
{
ULONG32 size = (*toSerialize)[i]->QuerySize();
startPos = binaryWriter.Position;
binaryWriter.Write(size);
buffer = binaryWriter.GetBuffer(startPos);
serializedOutput.Append(*buffer);
// NOTE: Include the buffer only if it has some data. Otherwise, V1 replicator fails replication
if (size > 0)
{
serializedOutput.Append(*(*toSerialize)[i]);
}
}
}
OperationData::CSPtr OperationData::DeSerialize(
__in OperationData const & inputData,
__inout INT & index,
__in KAllocator & allocator)
{
auto buffer = IncrementIndexAndGetBuffer(inputData, index);
BinaryReader reader(*buffer, allocator);
ULONG32 bufferCount = 0;
reader.Read(bufferCount);
if (bufferCount == NULL_OPERATION_DATA_COUNT)
{
return nullptr;
}
KArray<KBuffer::CSPtr> items(allocator);
if (!NT_SUCCESS(items.Status()))
{
throw Exception(items.Status());
}
NTSTATUS status;
for (ULONG i = 0; i < bufferCount; i++)
{
KBuffer::CSPtr lBuffer = DeSerializeBytes(inputData, index, allocator);
status = items.Append(lBuffer);
if (!NT_SUCCESS(status))
{
throw Exception(status);
}
}
OperationData::CSPtr constOperationData = OperationData::Create(items, allocator);
return constOperationData;
}
OperationData::CSPtr OperationData::DeSerialize(
__in BinaryReader & binaryReader,
__in KAllocator & allocator)
{
ULONG32 bufferCount = 0;
binaryReader.Read(bufferCount);
if (bufferCount == NULL_OPERATION_DATA_COUNT)
{
return nullptr;
}
KArray<KBuffer::CSPtr> items(allocator);
if (!NT_SUCCESS(items.Status()))
{
throw Exception(items.Status());
}
NTSTATUS status;
for (ULONG i = 0; i < bufferCount; i++)
{
KBuffer::CSPtr buffer = DeSerializeBytes(binaryReader, allocator);
status = items.Append(buffer);
if (!NT_SUCCESS(status))
{
throw Exception(status);
}
}
OperationData::CSPtr constOperationData = OperationData::Create(items, allocator);
return constOperationData;
}
KBuffer::CSPtr OperationData::DeSerializeBytes(
__in OperationData const & inputData,
__inout INT & index,
__in KAllocator & allocator)
{
auto buffer = IncrementIndexAndGetBuffer(inputData, index);
BinaryReader reader(*buffer, allocator);
ULONG32 count = 0;
reader.Read(count);
if (count == 0)
{
KBuffer::CSPtr returnBuffer;
KBuffer::SPtr emptyBuffer;
NTSTATUS status = KBuffer::Create(0, emptyBuffer, allocator);
if (!NT_SUCCESS(status))
{
throw Exception(status);
}
returnBuffer = emptyBuffer.RawPtr();
return returnBuffer;
}
return IncrementIndexAndGetBuffer(inputData, index);
}
KBuffer::CSPtr OperationData::DeSerializeBytes(
__in BinaryReader & binaryReader,
__in KAllocator & allocator)
{
ULONG32 size;
binaryReader.Read(size);
KBuffer::SPtr buffer = nullptr;
NTSTATUS status = KBuffer::Create(
size,
buffer,
allocator,
BINARYREADER_TAG);
if (!NT_SUCCESS(status))
{
throw Exception(status);
}
if(size > 0)
{
binaryReader.Read(size, buffer);
}
return KBuffer::CSPtr(buffer.RawPtr());
}
LONG64 OperationData::GetOperationSize(
__in OperationData const & operation)
{
LONG64 size = 0;
for (ULONG32 i = 0; i < operation.BufferCount; i++)
{
size += operation[i]->QuerySize();
}
return size;
}
void OperationData::Append(__in KBuffer const & buffer)
{
ASSERT_IFNOT(BufferCount + 1 < MAXULONG, "Invalid buffer count: {0}", BufferCount);
KBuffer::CSPtr sharedBuffer(&buffer);
NTSTATUS status = buffers_.Append(sharedBuffer);
if (!NT_SUCCESS(status))
{
throw Exception(status);
}
}
void OperationData::Append(__in OperationData const & operationData)
{
ASSERT_IFNOT(
BufferCount + operationData.BufferCount < MAXULONG,
"Invalid total buffer count: {0}",
BufferCount + operationData.BufferCount);
INT intBufferCount = static_cast<INT>(operationData.BufferCount);
NTSTATUS status = STATUS_SUCCESS;
for (INT index = 0; index < intBufferCount; index++)
{
status = buffers_.Append(operationData[index]);
if (!NT_SUCCESS(status))
{
throw Exception(status);
}
}
}
void OperationData::InsertAt0(__in KBuffer const & buffer)
{
ASSERT_IFNOT(BufferCount + 1 < MAXULONG, "Invalid buffer count: {0}", BufferCount);
KBuffer::CSPtr sharedBuffer(&buffer);
NTSTATUS status = buffers_.InsertAt(0, sharedBuffer);
if (!NT_SUCCESS(status))
{
throw Exception(status);
}
}
bool OperationData::Test_Equals(__in OperationData const & other) const
{
if(buffers_.Count() != other.buffers_.Count())
{
return false;
}
ULONG bufferSize;
for(ULONG i = 0; i < buffers_.Count(); i++)
{
bufferSize = buffers_[i]->QuerySize();
if(bufferSize != other.buffers_[i]->QuerySize())
{
return false;
}
// NOTE: This is due to a bug in KBuffer which requires the left hand value to be const
KBuffer::CSPtr currentConstBuffer = buffers_[i];
KBuffer const & currentBufferRef = *currentConstBuffer;
KBuffer & currentBuffer = const_cast<KBuffer &>(currentBufferRef);
if(currentBuffer != *other.buffers_[i])
{
return false;
}
}
return true;
}
|
#pragma once
#include "Sto.hh"
#include "TArrayProxy.hh"
#include "MVCC.hh"
template <typename T, unsigned N>
class TMvArray : public TObject {
public:
class iterator;
class const_iterator;
typedef T value_type;
typedef T get_type;
typedef unsigned size_type;
typedef int difference_type;
typedef TConstArrayProxy<TMvArray<T, N> > const_proxy_type;
typedef TArrayProxy<TMvArray<T, N> > proxy_type;
typedef typename commutators::Commutator<T> comm_type;
size_type size() const {
return N;
}
const_proxy_type operator[](size_type i) const {
assert(i < N);
return const_proxy_type(this, i);
}
proxy_type operator[](size_type i) {
assert(i < N);
return proxy_type(this, i);
}
inline iterator begin();
inline iterator end();
inline const_iterator cbegin() const;
inline const_iterator cend() const;
inline const_iterator begin() const;
inline const_iterator end() const;
// transGet and friends
bool transGet(size_type i, value_type& ret) const {
assert(i < N);
auto item = Sto::item(this, i);
if (item.has_write()) {
ret = item.template write_value<T>();
return true;
}
else {
history_type *h = data_[i].v.find(Sto::read_tid<false/*!commute*/>());
MvAccess::template read<T>(item, h);
ret = h->v();
return true;
}
}
value_type transGet_throws(size_type i) const {
assert(i < N);
auto item = Sto::item(this, i);
if (item.has_write()) {
return item.template write_value<T>();
}
else {
history_type *h = data_[i].v.find(Sto::read_tid<false/*!commute*/>());
if (!h) {
throw Transaction::Abort();
}
MvAccess::template read<T>(item, h);
return h->v();
}
}
bool transPut(size_type i, T x) const {
assert(i < N);
Sto::item(this, i).add_write(x);
return true;
}
void transPut_throws(size_type i, T x) const {
transPut(i, x);
}
get_type& nontrans_access(size_type i) {
assert(i < N);
return data_[i].v.nontrans_access();
}
get_type nontrans_get(size_type i) const {
assert(i < N);
return data_[i].v.nontrans_access();
}
void nontrans_put(size_type i, const T& x) {
assert(i < N);
data_[i].v.nontrans_access() = x;
}
void nontrans_put(size_type i, T&& x) {
assert(i < N);
data_[i].v.nontrans_access() = std::move(x);
}
// transactional methods
bool lock(TransItem& item, Transaction& txn) override {
object_type &v = data_[item.key<size_type>()].v;
history_type *hprev = nullptr;
if (item.has_read()) {
hprev = item.read_value<history_type*>();
} else {
hprev = v.find(Sto::read_tid<false/*!commute*/>(), false);
}
if (Sto::commit_tid() < hprev->rtid()) {
TransProxy(txn, item).add_write(nullptr);
return false;
}
history_type *h;
if (item.has_commute()) {
auto wval = item.template write_value<comm_type>();
h = v.new_history(Sto::commit_tid(), &v, std::move(wval), hprev);
} else {
h = v.new_history(
Sto::commit_tid(), &v, item.write_value<T>(), hprev);
}
bool result = v.cp_lock(Sto::commit_tid(), h);
if (!result && !h->status_is(MvStatus::ABORTED)) {
v.delete_history(h);
TransProxy(txn, item).add_write(nullptr);
} else {
TransProxy(txn, item).add_write(h);
TransProxy(txn, item).clear_commute();
}
return result;
}
bool check(TransItem& item, Transaction&) override {
assert(item.has_read());
fence();
history_type *hprev = item.read_value<history_type*>();
return data_[item.key<size_type>()].v.cp_check(Sto::commit_tid(), hprev);
}
void install(TransItem& item, Transaction&) override {
auto h = item.template write_value<history_type*>();
data_[item.key<size_type>()].v.cp_install(h);
}
void unlock(TransItem&) override {
// no-op
}
void cleanup(TransItem& item, bool committed) override {
if (!committed) {
if (item.has_write()) {
auto h = item.template write_value<history_type*>();
if (h && !item.has_commute()) {
data_[item.key<size_type>()].v.abort(h);
}
}
}
}
private:
typedef MvObject<T> object_type;
typedef typename object_type::history_type history_type;
struct elem {
object_type v;
};
elem data_[N];
friend class iterator;
friend class const_iterator;
};
template <typename T, unsigned N>
class TMvArray<T, N>::const_iterator : public std::iterator<std::random_access_iterator_tag, T> {
public:
typedef TMvArray<T, N> array_type;
typedef typename array_type::size_type size_type;
typedef typename array_type::difference_type difference_type;
const_iterator(const TMvArray<T, N>* a, size_type i)
: a_(const_cast<array_type*>(a)), i_(i) {
}
typename array_type::const_proxy_type operator*() const {
return array_type::const_proxy_type(a_, i_);
}
bool operator==(const const_iterator& x) const {
return a_ == x.a_ && i_ == x.i_;
}
bool operator!=(const const_iterator& x) const {
return !(*this == x);
}
bool operator<(const const_iterator& x) const {
assert(a_ == x.a_);
return i_ < x.i_;
}
bool operator<=(const const_iterator& x) const {
assert(a_ == x.a_);
return i_ <= x.i_;
}
bool operator>(const const_iterator& x) const {
assert(a_ == x.a_);
return i_ > x.i_;
}
bool operator>=(const const_iterator& x) const {
assert(a_ == x.a_);
return i_ >= x.i_;
}
const_iterator& operator+=(difference_type delta) {
i_ += delta;
return *this;
}
const_iterator& operator-=(difference_type delta) {
i_ += delta;
return *this;
}
const_iterator operator+(difference_type delta) const {
return const_iterator(a_, i_ + delta);
}
const_iterator operator-(difference_type delta) const {
return const_iterator(a_, i_ - delta);
}
const_iterator& operator++() {
++i_;
return *this;
}
const_iterator operator++(int) {
++i_;
return const_iterator(a_, i_ - 1);
}
const_iterator& operator--() {
--i_;
return *this;
}
const_iterator operator--(int) {
--i_;
return const_iterator(a_, i_ + 1);
}
difference_type operator-(const const_iterator& x) const {
assert(a_ == x.a_);
return i_ - x.i_;
}
protected:
array_type* a_;
size_type i_;
};
template <typename T, unsigned N>
class TMvArray<T, N>::iterator : public const_iterator {
public:
typedef TMvArray<T, N> array_type;
typedef typename array_type::size_type size_type;
typedef typename array_type::difference_type difference_type;
iterator(const TMvArray<T, N>* a, size_type i)
: const_iterator(a, i) {
}
typename array_type::proxy_type operator*() const {
return array_type::proxy_type(this->a_, this->i_);
}
iterator& operator+=(difference_type delta) {
this->i_ += delta;
return *this;
}
iterator& operator-=(difference_type delta) {
this->i_ += delta;
return *this;
}
iterator operator+(difference_type delta) const {
return iterator(this->a_, this->i_ + delta);
}
iterator operator-(difference_type delta) const {
return iterator(this->a_, this->i_ - delta);
}
iterator& operator++() {
++this->i_;
return *this;
}
iterator operator++(int) {
++this->i_;
return iterator(this->a_, this->i_ - 1);
}
iterator& operator--() {
--this->i_;
return *this;
}
iterator operator--(int) {
--this->i_;
return iterator(this->a_, this->i_ + 1);
}
};
template <typename T, unsigned N>
inline auto TMvArray<T, N>::begin() -> iterator {
return iterator(this, 0);
}
template <typename T, unsigned N>
inline auto TMvArray<T, N>::end() -> iterator {
return iterator(this, N);
}
template <typename T, unsigned N>
inline auto TMvArray<T, N>::cbegin() const -> const_iterator {
return const_iterator(this, 0);
}
template <typename T, unsigned N>
inline auto TMvArray<T, N>::cend() const -> const_iterator {
return const_iterator(this, N);
}
template <typename T, unsigned N>
inline auto TMvArray<T, N>::begin() const -> const_iterator {
return const_iterator(this, 0);
}
template <typename T, unsigned N>
inline auto TMvArray<T, N>::end() const -> const_iterator {
return const_iterator(this, N);
}
|
/*---------------------------------------------------------------------------*\
Copyright (C) 2011 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of CAELUS.
CAELUS is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CAELUS is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with CAELUS. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "transform.hpp"
// * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
template<class TrackingData>
inline bool CML::sweepData::update
(
const sweepData& svf,
const point& position,
const scalar tol,
TrackingData& td
)
{
if (!valid(td))
{
operator=(svf);
return true;
}
scalar myDist2 = magSqr(position - origin());
if (myDist2 < SMALL)
{
if (svf.value() > value())
{
operator=(svf);
return true;
}
else
{
return false;
}
}
scalar dist2 = magSqr(position - svf.origin());
if (dist2 < myDist2)
{
operator=(svf);
return true;
}
return false;
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
inline CML::sweepData::sweepData()
:
value_(-GREAT),
origin_(vector::max)
{}
inline CML::sweepData::sweepData(const scalar value, const point& origin)
:
value_(value),
origin_(origin)
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
template<class TrackingData>
inline bool CML::sweepData::valid(TrackingData& td) const
{
return value_ > -SMALL;
}
template<class TrackingData>
inline bool CML::sweepData::sameGeometry
(
const polyMesh&,
const sweepData&,
const scalar,
TrackingData& td
) const
{
return true;
}
template<class TrackingData>
inline void CML::sweepData::leaveDomain
(
const polyMesh&,
const polyPatch&,
const label,
const point& faceCentre,
TrackingData& td
)
{
origin_ -= faceCentre;
}
template<class TrackingData>
inline void CML::sweepData::transform
(
const polyMesh&,
const tensor& rotTensor,
TrackingData& td
)
{
origin_ = CML::transform(rotTensor, origin_);
}
template<class TrackingData>
inline void CML::sweepData::enterDomain
(
const polyMesh&,
const polyPatch&,
const label,
const point& faceCentre,
TrackingData& td
)
{
// back to absolute form
origin_ += faceCentre;
}
template<class TrackingData>
inline bool CML::sweepData::updateCell
(
const polyMesh& mesh,
const label thisCellI,
const label,
const sweepData& svf,
const scalar tol,
TrackingData& td
)
{
return update(svf, mesh.cellCentres()[thisCellI], tol, td);
}
template<class TrackingData>
inline bool CML::sweepData::updateFace
(
const polyMesh& mesh,
const label thisFaceI,
const label,
const sweepData& svf,
const scalar tol,
TrackingData& td
)
{
return update(svf, mesh.faceCentres()[thisFaceI], tol, td);
}
// Update this (face) with coupled face information.
template<class TrackingData>
inline bool CML::sweepData::updateFace
(
const polyMesh& mesh,
const label thisFaceI,
const sweepData& svf,
const scalar tol,
TrackingData& td
)
{
return update(svf, mesh.faceCentres()[thisFaceI], tol, td);
}
template <class TrackingData>
inline bool CML::sweepData::equal
(
const sweepData& rhs,
TrackingData& td
) const
{
return operator==(rhs);
}
// * * * * * * * * * * * * * * * Member Operators * * * * * * * * * * * * * //
inline void CML::sweepData::operator=
(
const scalar value
)
{
value_ = value;
}
inline bool CML::sweepData::operator==
(
const sweepData& rhs
) const
{
return origin() == rhs.origin();
}
inline bool CML::sweepData::operator!=
(
const sweepData& rhs
) const
{
return !(*this == rhs);
}
// ************************************************************************* //
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: DG.Tweening.DOTweenModuleUtils
#include "DG/Tweening/DOTweenModuleUtils.hpp"
// Including type: UnityEngine.Vector3
#include "UnityEngine/Vector3.hpp"
// Including type: DG.Tweening.Plugins.Options.PathOptions
#include "DG/Tweening/Plugins/Options/PathOptions.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: MonoBehaviour
class MonoBehaviour;
// Skipping declaration: Quaternion because it is already included!
// Forward declaring type: Transform
class Transform;
// Forward declaring type: Component
class Component;
}
// Forward declaring namespace: DG::Tweening
namespace DG::Tweening {
// Forward declaring type: Tween
class Tween;
// Skipping declaration: PathMode because it is already included!
}
// Forward declaring namespace: DG::Tweening::Core
namespace DG::Tweening::Core {
// Forward declaring type: TweenerCore`3<T1, T2, TPlugOptions>
template<typename T1, typename T2, typename TPlugOptions>
class TweenerCore_3;
}
// Forward declaring namespace: DG::Tweening::Plugins::Core::PathCore
namespace DG::Tweening::Plugins::Core::PathCore {
// Forward declaring type: Path
class Path;
}
// Completed forward declares
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::DG::Tweening::DOTweenModuleUtils::Physics);
DEFINE_IL2CPP_ARG_TYPE(::DG::Tweening::DOTweenModuleUtils::Physics*, "DG.Tweening", "DOTweenModuleUtils/Physics");
// Type namespace: DG.Tweening
namespace DG::Tweening {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: DG.Tweening.DOTweenModuleUtils/DG.Tweening.Physics
// [TokenAttribute] Offset: FFFFFFFF
class DOTweenModuleUtils::Physics : public ::Il2CppObject {
public:
// static public System.Void SetOrientationOnPath(DG.Tweening.Plugins.Options.PathOptions options, DG.Tweening.Tween t, UnityEngine.Quaternion newRot, UnityEngine.Transform trans)
// Offset: 0x1265EE4
static void SetOrientationOnPath(::DG::Tweening::Plugins::Options::PathOptions options, ::DG::Tweening::Tween* t, ::UnityEngine::Quaternion newRot, ::UnityEngine::Transform* trans);
// static public System.Boolean HasRigidbody2D(UnityEngine.Component target)
// Offset: 0x1265FE8
static bool HasRigidbody2D(::UnityEngine::Component* target);
// static public System.Boolean HasRigidbody(UnityEngine.Component target)
// Offset: 0x1266080
static bool HasRigidbody(::UnityEngine::Component* target);
// static public DG.Tweening.Core.TweenerCore`3<UnityEngine.Vector3,DG.Tweening.Plugins.Core.PathCore.Path,DG.Tweening.Plugins.Options.PathOptions> CreateDOTweenPathTween(UnityEngine.MonoBehaviour target, System.Boolean tweenRigidbody, System.Boolean isLocal, DG.Tweening.Plugins.Core.PathCore.Path path, System.Single duration, DG.Tweening.PathMode pathMode)
// Offset: 0x1266118
static ::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Vector3, ::DG::Tweening::Plugins::Core::PathCore::Path*, ::DG::Tweening::Plugins::Options::PathOptions>* CreateDOTweenPathTween(::UnityEngine::MonoBehaviour* target, bool tweenRigidbody, bool isLocal, ::DG::Tweening::Plugins::Core::PathCore::Path* path, float duration, ::DG::Tweening::PathMode pathMode);
}; // DG.Tweening.DOTweenModuleUtils/DG.Tweening.Physics
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: DG::Tweening::DOTweenModuleUtils::Physics::SetOrientationOnPath
// Il2CppName: SetOrientationOnPath
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(::DG::Tweening::Plugins::Options::PathOptions, ::DG::Tweening::Tween*, ::UnityEngine::Quaternion, ::UnityEngine::Transform*)>(&DG::Tweening::DOTweenModuleUtils::Physics::SetOrientationOnPath)> {
static const MethodInfo* get() {
static auto* options = &::il2cpp_utils::GetClassFromName("DG.Tweening.Plugins.Options", "PathOptions")->byval_arg;
static auto* t = &::il2cpp_utils::GetClassFromName("DG.Tweening", "Tween")->byval_arg;
static auto* newRot = &::il2cpp_utils::GetClassFromName("UnityEngine", "Quaternion")->byval_arg;
static auto* trans = &::il2cpp_utils::GetClassFromName("UnityEngine", "Transform")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTweenModuleUtils::Physics*), "SetOrientationOnPath", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{options, t, newRot, trans});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTweenModuleUtils::Physics::HasRigidbody2D
// Il2CppName: HasRigidbody2D
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::UnityEngine::Component*)>(&DG::Tweening::DOTweenModuleUtils::Physics::HasRigidbody2D)> {
static const MethodInfo* get() {
static auto* target = &::il2cpp_utils::GetClassFromName("UnityEngine", "Component")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTweenModuleUtils::Physics*), "HasRigidbody2D", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{target});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTweenModuleUtils::Physics::HasRigidbody
// Il2CppName: HasRigidbody
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::UnityEngine::Component*)>(&DG::Tweening::DOTweenModuleUtils::Physics::HasRigidbody)> {
static const MethodInfo* get() {
static auto* target = &::il2cpp_utils::GetClassFromName("UnityEngine", "Component")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTweenModuleUtils::Physics*), "HasRigidbody", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{target});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTweenModuleUtils::Physics::CreateDOTweenPathTween
// Il2CppName: CreateDOTweenPathTween
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Vector3, ::DG::Tweening::Plugins::Core::PathCore::Path*, ::DG::Tweening::Plugins::Options::PathOptions>* (*)(::UnityEngine::MonoBehaviour*, bool, bool, ::DG::Tweening::Plugins::Core::PathCore::Path*, float, ::DG::Tweening::PathMode)>(&DG::Tweening::DOTweenModuleUtils::Physics::CreateDOTweenPathTween)> {
static const MethodInfo* get() {
static auto* target = &::il2cpp_utils::GetClassFromName("UnityEngine", "MonoBehaviour")->byval_arg;
static auto* tweenRigidbody = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* isLocal = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* path = &::il2cpp_utils::GetClassFromName("DG.Tweening.Plugins.Core.PathCore", "Path")->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* pathMode = &::il2cpp_utils::GetClassFromName("DG.Tweening", "PathMode")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTweenModuleUtils::Physics*), "CreateDOTweenPathTween", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{target, tweenRigidbody, isLocal, path, duration, pathMode});
}
};
|
/*Create a class which stores employee name, id and salary Derive two classes from
‘Employee’ class: ‘Regular’ and ‘Part-Time’. The ‘Regular’ class stores DA, HRA and
basic salary. The ‘Part-Time’ class stores the number of hours and pay per hour.
Calculate the salary of a regular employee and a part-time – use the concept of
virtual function
Gross Salary = Basic Salary + DA + HRA
DA = 80% of Basic Salary
HRA = 10% of Basic Salary*/
#include <iostream>
#include <string.h>
using namespace std;
class Employee {
private:
string name;
int id;
protected:
int salary;
public:
Employee(string n, int i, int s) : name(n), id(i), salary(s) {}
void display() {
cout<<"\tName: "<<name<<endl;
cout<<"\tId: "<<id<<endl;
cout<<"\tSalary: "<<salary<<endl;
}
virtual void calculateSalary() = 0;
};
class Regular : public Employee {
float DA, HRA, GSal;
public:
Regular(string n, int i, int sal) : Employee(n,i,sal){
DA = HRA = 0.0f;
GSal = 0;
}
void calculateSalary() {
DA = 0.8 * salary;
HRA = 0.1 * salary;
GSal = DA + HRA + salary;
cout<<"\nRegular\n";
display();
cout<<"\tDA: "<<DA<<endl;
cout<<"\tHRA: "<<HRA<<endl;
cout<<"\tGrossSalary: "<<GSal<<endl;
}
};
class PartTime : public Employee {
int time;
float salPerTime;
public:
PartTime(string n, int i, int t, float P) : Employee(n,i,0){
time=t;
salPerTime=P;
}
void calculateSalary() {
cout<<"\nPartime\n";
salary = time * salPerTime;
display();
}
};
int main(int argc, char** argv) {
Regular a("xyz",2341,30000);
a.calculateSalary();
PartTime b("ABC",3244,10,20.5);
b.calculateSalary();
remove(argv[0]);
return EXIT_SUCCESS;
}
|
#include "Beatmap.h"
Beatmap::Beatmap(const char* filename, const char* basedir)
{
fLoadable = false;
mFilename = filename;
mBaseDir = basedir;
mReader = NULL;
FileReader r(filename);
if (r.Ready())
{
//check header before processing
char id[4] = { r.ReadInt8(), r.ReadInt8(), r.ReadInt8(), 0 };
if (strcmp(id, "ODS") == 0)
{
u8 odsver = r.ReadInt8();
mTitle = r.ReadString();
mArtist = r.ReadString();
mCreator = r.ReadString();
mVersion = r.ReadString();
mAudioFilename = r.ReadString();
fLoadable = true;
}
}
fReady = false;
}
void Beatmap::Initialize()
{
if (!fReady)
{
if (!fLoadable)
{
iprintf("\x1b[0;0Hcannot load this file");
return;
}
chdir(mBaseDir.c_str());
mReader = new FileReader(mFilename);
//skip header
mReader->Skip(3);
u8 odsver = mReader->ReadInt8();
mTitle = mReader->ReadString();
mArtist = mReader->ReadString();
mCreator = mReader->ReadString();
mVersion = mReader->ReadString();
mAudioFilename = mReader->ReadString();
nocashMessage(mAudioFilename.c_str());
DifficultyManager::DifficultyHpDrain = mReader->ReadInt8();
DifficultyManager::DifficultyCircleSize = mReader->ReadInt8();
DifficultyManager::DifficultyOverall = mReader->ReadInt8();
DifficultyManager::SliderMultiplier = mReader->ReadFloat();
DifficultyManager::SliderTickRate = mReader->ReadFloat();
DifficultyManager::DifficultyHpDrainRate = mReader->ReadFloat();
DifficultyManager::DifficultyPeppyStars = mReader->ReadInt8();
DifficultyManager::DifficultyEyupStars = mReader->ReadFloat();
u32 tpointcount = mReader->ReadVarInt();
for (u32 j=0; j<tpointcount; ++j)
{
s32 time = mReader->ReadInt32();
float beattime = mReader->ReadFloat();
u8 samplesetid = mReader->ReadInt8();
BeatmapElements::Element().AddTimingPoint(time, beattime, samplesetid);
}
nocashMessage("hio\n");
u32 breakcount = mReader->ReadVarInt();
nocashMessage(std::to_string(breakcount).c_str());
for (u32 j=0; j<breakcount; ++j)
{
s32 starttime = mReader->ReadInt32();
s32 endtime = mReader->ReadInt32();
BeatmapElements::Element().AddBreakPoint(starttime, endtime);
}
nocashMessage("hio\n");
iprintf("\x1b[2J");
mHitObjectCount = mReader->ReadVarInt();
mHitObjectRead = 0;
mLastObjectEndTime = 0;
mForceNewCombo = true;
//read ahead
ReadNextObject();
mFirstObjectTime = mNextObjectTime;
//the time to skip to is the first object - 8 beats
mSkipTime = MathHelper::Max(0, (s32)mNextObjectTime - (BeatmapElements::Element().GetTimingPoint(mNextObjectTime).BeatTime*8));
//strangely calling this in ctor of BeatmapElements causes game to not load :/
BeatmapElements::Element().ResetColours(true);
//now we can play this map
fReady = true;
}
}
void Beatmap::CleanUp()
{
//set object back to uninitialised state
fReady = false;
if (mReader != NULL)
delete mReader;
mReader = NULL;
}
Beatmap::~Beatmap()
{
if (mReader != NULL)
delete mReader;
}
void Beatmap::Buffer(list<HitObject*>& hitObjectList)
{
if (!fReady)
{
iprintf("\x1b[0;0Hnot ready to buffer");
return;
}
//we buffer objects to 10 seconds ahead
while (mHitObjectRead < mHitObjectCount && mNextObjectTime < GameClock::Clock().Time() + 3000)
{
HitObject* object;
//all coordinates are s16 in file but s32 in RAM
HitObjectType type = mNextObjectType;
s32 x = mNextObjectX;
s32 y = mNextObjectY;
HitObjectSound sound = (HitObjectSound)mReader->ReadInt8();
if (mForceNewCombo)
{
type = (HitObjectType)(type|HIT_COMBO);
mForceNewCombo = false;
}
switch (type & ~HIT_COMBO) //ignore HIT_COMBO
{
case HIT_NORMAL:
{
object = new HitCircle(x, y, mNextObjectTime, type, sound);
break;
}
case HIT_SLIDER:
{
u32 repeats = mReader->ReadInt16();
u32 lengthtime = mReader->ReadInt32();
u32 pointcount = mReader->ReadVarInt();
vector<HitObjectPoint*> points;
points.reserve(pointcount);
for (u32 i=0; i<pointcount; ++i)
{
HitObjectPoint* tPoint = new HitObjectPoint();
tPoint->x = (s16)mReader->ReadInt16(); //s32 x
tPoint->y = (s16)mReader->ReadInt16(); //s32 y
tPoint->angle = mReader->ReadInt32(); //s32 angle
points.push_back(tPoint);
}
u32 tickcount = mReader->ReadVarInt();
vector<HitObjectPoint*> ticks;
ticks.reserve(tickcount);
for (u32 i=0; i<tickcount; ++i)
{
HitObjectPoint* tPoint = new HitObjectPoint();
tPoint->x = (s16)mReader->ReadInt16(); //s32 x
tPoint->y = (s16)mReader->ReadInt16(); //s32 y
ticks.push_back(tPoint);
}
object = new HitSlider(x, y, mNextObjectTime, lengthtime, points, ticks, repeats, type, sound);
//free allocated memory
for (u32 i=0; i<pointcount; ++i)
delete points[i];
for (u32 i=0; i<tickcount; ++i)
delete ticks[i];
break;
}
case HIT_SPINNER:
{
s32 endtime = mReader->ReadInt32();
object = new HitSpinner(mNextObjectTime, endtime, sound);
mForceNewCombo = true;
break;
}
}
//track when the beatmap has ended
mLastObjectEndTime = object->GetEndTime();
//add to list
hitObjectList.push_back(object);
++mHitObjectRead;
if (mHitObjectRead < mHitObjectCount)
{
ReadNextObject();
object->SetPostCreateOptions((mNextObjectType & HIT_COMBO) | mForceNewCombo, mNextObjectX, mNextObjectY);
}
else
{
object->SetPostCreateOptions(true, 0, 0);
}
}
}
void Beatmap::ReadNextObject()
{
mNextObjectTime = mReader->ReadInt32();
mNextObjectType = (HitObjectType)mReader->ReadInt8();
mNextObjectX = (s16)mReader->ReadInt16();
mNextObjectY = (s16)mReader->ReadInt16();
}
|
// Copyright (c) 2015-2018 Daniel Cooke
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.
#ifndef calling_components_hpp
#define calling_components_hpp
#include <vector>
#include <cstddef>
#include <functional>
#include <memory>
#include <boost/optional.hpp>
#include <boost/filesystem/path.hpp>
#include "config/common.hpp"
#include "config/option_parser.hpp"
#include "basics/genomic_region.hpp"
#include "basics/ploidy_map.hpp"
#include "basics/pedigree.hpp"
#include "io/reference/reference_genome.hpp"
#include "io/read/read_manager.hpp"
#include "io/variant/vcf_writer.hpp"
#include "readpipe/read_pipe_fwd.hpp"
#include "core/callers/caller_factory.hpp"
#include "core/csr/filters/variant_call_filter_factory.hpp"
#include "utils/input_reads_profiler.hpp"
#include "logging/progress_meter.hpp"
namespace octopus {
class GenomeCallingComponents
{
public:
using Path = boost::filesystem::path;
GenomeCallingComponents() = delete;
GenomeCallingComponents(ReferenceGenome&& reference, ReadManager&& read_manager,
VcfWriter&& output, const options::OptionMap& options);
GenomeCallingComponents(const GenomeCallingComponents&) = delete;
GenomeCallingComponents& operator=(const GenomeCallingComponents&) = delete;
GenomeCallingComponents(GenomeCallingComponents&& other) noexcept;
GenomeCallingComponents& operator=(GenomeCallingComponents&& other) = delete;
~GenomeCallingComponents() = default;
const ReferenceGenome& reference() const noexcept;
ReadManager& read_manager() noexcept;
const ReadManager& read_manager() const noexcept;
ReadPipe& read_pipe() noexcept;
const ReadPipe& read_pipe() const noexcept;
const std::vector<SampleName>& samples() const noexcept;
const InputRegionMap& search_regions() const noexcept;
const std::vector<GenomicRegion::ContigName>& contigs() const noexcept;
VcfWriter& output() noexcept;
const VcfWriter& output() const noexcept;
std::size_t read_buffer_size() const noexcept;
const boost::optional<Path>& temp_directory() const noexcept;
boost::optional<unsigned> num_threads() const noexcept;
const CallerFactory& caller_factory() const noexcept;
boost::optional<VcfWriter&> filtered_output() noexcept;
boost::optional<const VcfWriter&> filtered_output() const noexcept;
const VariantCallFilterFactory& call_filter_factory() const;
ReadPipe& filter_read_pipe() noexcept;
const ReadPipe& filter_read_pipe() const noexcept;
ProgressMeter& progress_meter() noexcept;
bool sites_only() const noexcept;
const PloidyMap& ploidies() const noexcept;
boost::optional<Pedigree> pedigree() const;
boost::optional<Path> legacy() const;
boost::optional<Path> filter_request() const;
boost::optional<Path> bamout() const;
boost::optional<Path> split_bamout() const;
boost::optional<Path> data_profile() const;
private:
struct Components
{
Components() = delete;
Components(ReferenceGenome&& reference, ReadManager&& read_manager,
VcfWriter&& output, const options::OptionMap& options);
Components(const Components&) = delete;
Components& operator=(const Components&) = delete;
Components(Components&&) = default;
Components& operator=(Components&&) = default;
~Components() = default;
ReferenceGenome reference;
ReadManager read_manager;
std::vector<SampleName> samples;
InputRegionMap regions;
std::vector<GenomicRegion::ContigName> contigs;
boost::optional<ReadSetProfile> reads_profile;
ReadPipe read_pipe;
CallerFactory caller_factory;
boost::optional<ReadPipe> filter_read_pipe;
VcfWriter output;
boost::optional<VcfWriter> filtered_output;
boost::optional<unsigned> num_threads;
std::size_t read_buffer_size;
ProgressMeter progress_meter;
PloidyMap ploidies;
boost::optional<Pedigree> pedigree;
bool sites_only;
boost::optional<Path> legacy;
boost::optional<Path> filter_request;
boost::optional<Path> bamout, split_bamout, data_profile;
// Components that require temporary directory during construction appear last to make
// exception handling easier.
boost::optional<Path> temp_directory;
std::unique_ptr<VariantCallFilterFactory> call_filter_factory;
void setup_progress_meter(const options::OptionMap& options);
void set_read_buffer_size(const options::OptionMap& options);
void setup_writers(const options::OptionMap& options);
void setup_filter_read_pipe(const options::OptionMap& options);
};
Components components_;
void update_dependents() noexcept;
};
GenomeCallingComponents collate_genome_calling_components(const options::OptionMap& options);
bool validate(const GenomeCallingComponents& components);
void cleanup(GenomeCallingComponents& components) noexcept;
struct ContigCallingComponents
{
std::reference_wrapper<const ReferenceGenome> reference;
std::reference_wrapper<const ReadManager> read_manager;
const InputRegionMap::mapped_type regions;
std::reference_wrapper<const std::vector<SampleName>> samples;
std::unique_ptr<const Caller> caller;
std::size_t read_buffer_size;
std::reference_wrapper<VcfWriter> output;
std::reference_wrapper<ProgressMeter> progress_meter;
ContigCallingComponents() = delete;
ContigCallingComponents(const GenomicRegion::ContigName& contig,
GenomeCallingComponents& genome_components);
ContigCallingComponents(const GenomicRegion::ContigName& contig, VcfWriter& output,
GenomeCallingComponents& genome_components);
ContigCallingComponents(const ContigCallingComponents&) = delete;
ContigCallingComponents& operator=(const ContigCallingComponents&) = delete;
ContigCallingComponents(ContigCallingComponents&&) = default;
ContigCallingComponents& operator=(ContigCallingComponents&&) = default;
~ContigCallingComponents() = default;
};
} // namespace octopus
#endif
|
/**
* swagger <-> libpacket transmogrify implementation for MPLS
*
* This file is automatically generated by the transmogrify code generator.
* Do not edit this file manually.
**/
#include "mpls.hpp"
namespace openperf::packet::protocol::transmogrify {
std::shared_ptr<swagger::v1::model::PacketProtocolMpls> to_swagger(const libpacket::protocol::mpls& src)
{
auto dst = std::make_shared<swagger::v1::model::PacketProtocolMpls>();
dst->setLabel(get_mpls_label(src));
dst->setTrafficClass(get_mpls_traffic_class(src));
dst->setBottomOfStack(get_mpls_bottom_of_stack(src));
dst->setTtl(get_mpls_ttl(src));
return (dst);
}
libpacket::protocol::mpls to_protocol(const std::shared_ptr<swagger::v1::model::PacketProtocolMpls>& src)
{
auto dst = libpacket::protocol::mpls{};
set_mpls_defaults(dst);
if (src) {
if (src->labelIsSet())
{
set_mpls_label(dst, src->getLabel());
}
if (src->trafficClassIsSet())
{
set_mpls_traffic_class(dst, src->getTrafficClass());
}
if (src->bottomOfStackIsSet())
{
set_mpls_bottom_of_stack(dst, src->isBottomOfStack());
}
if (src->ttlIsSet())
{
set_mpls_ttl(dst, src->getTtl());
}
}
return (dst);
}
}
|
/*
PICCANTE
The hottest HDR imaging library!
http://vcg.isti.cnr.it/piccante
Copyright (C) 2014
Visual Computing Laboratory - ISTI CNR
http://vcg.isti.cnr.it
First author: Francesco Banterle
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef PIC_COMPUTER_VISION_TRIANGULATION_HPP
#define PIC_COMPUTER_VISION_TRIANGULATION_HPP
#include <vector>
#include <random>
#include <stdlib.h>
#include "../base.hpp"
#include "../image.hpp"
#include "../util/math.hpp"
#include "../util/eigen_util.hpp"
#include "../computer_vision/nelder_mead_opt_triangulation.hpp"
#ifndef PIC_DISABLE_EIGEN
#ifndef PIC_EIGEN_NOT_BUNDLED
#include "../externals/Eigen/Dense"
#else
#include <Eigen/Dense>
#endif
#endif
namespace pic {
#ifndef PIC_DISABLE_EIGEN
/**
* @brief triangulationLonguetHiggins computes triangulation using Longuet-Higgins equations.
* @param point_0 is the point from the first view that matches point_1
* @param point_1 is the point from the second view that matches point_0
* @param R is the rotation matrix between the two views.
* @param t is the translation matrix between the two views.
* @return
*/
PIC_INLINE Eigen::Vector3d triangulationLonguetHiggins(Eigen::Vector3d &point_0, Eigen::Vector3d &point_1, Eigen::Matrix3d &R, Eigen::Vector3d &t)
{
Eigen::Vector3d ret;
Eigen::Vector3d r_0 = Eigen::Vector3d(R(0, 0), R(0, 1), R(0, 2));
Eigen::Vector3d r_2 = Eigen::Vector3d(R(2, 0), R(2, 1), R(2, 2));
Eigen::Vector3d tmp = r_0 - point_1[0] * r_2;
ret[2] = tmp.dot(t) / tmp.dot(point_0);
ret[0] = point_0[0] * ret[2];
ret[1] = point_0[1] * ret[2];
return ret;
}
/**
* @brief triangulationHartl
* Sturm
* @param point_0
* @param point_1
* @param R
* @param t
* @return
*/
PIC_INLINE Eigen::Vector4d triangulationHartleySturm(Eigen::Vector3d &point_0, Eigen::Vector3d &point_1,
Eigen::Matrix34d &M0, Eigen::Matrix34d &M1, int maxIter = 100)
{
Eigen::Vector4d M0_row[3], M1_row[3];
for(int i = 0; i < 3; i++) {
M0_row[i] = Eigen::Vector4d(M0(i, 0), M0(i, 1), M0(i, 2), M0(i, 3));
M1_row[i] = Eigen::Vector4d(M1(i, 0), M1(i, 1), M1(i, 2), M1(i, 3));
}
Eigen::Vector4d x;
double weight0 = 1.0;
double weight0_prev = 1.0;
double weight1 = 1.0;
double weight1_prev = 1.0;
int j = 0;
while(j < maxIter) {
Eigen::Vector4d A0 = (M0_row[0] - point_0[0] * M0_row[2]) / weight0;
Eigen::Vector4d A1 = (M0_row[1] - point_0[1] * M0_row[2]) / weight0;
Eigen::Vector4d A2 = (M1_row[0] - point_1[0] * M1_row[2]) / weight1;
Eigen::Vector4d A3 = (M1_row[1] - point_1[1] * M1_row[2]) / weight1;
Eigen::MatrixXd A(4, 4);
for(int i = 0; i < 4; i++) {
A(0, i) = A0[i];
A(1, i) = A1[i];
A(2, i) = A2[i];
A(3, i) = A3[i];
}
Eigen::JacobiSVD< Eigen::MatrixXd > svdA(A, Eigen::ComputeFullV);
Eigen::MatrixXd V = svdA.matrixV();
int n = int(V.cols()) - 1;
x[0] = V(0, n);
x[1] = V(1, n);
x[2] = V(2, n);
x[3] = V(3, n);
x /= x[3];
weight0_prev = weight0;
weight1_prev = weight1;
weight0 = x.dot(M0_row[2]);
weight1 = x.dot(M1_row[2]);
double d0 = weight0_prev - weight0;
double d1 = weight1_prev - weight1;
double err = sqrt(d0 * d0 + d1 * d1);
if(err < 1e-12){
break;
}
j++;
}
#ifdef PIC_DEBUG
printf("triangulationHartleySturm's Iterations: %d\n",j);
#endif
return x;
}
/**
* @brief triangulationPoints
* @param M0
* @param M1
* @param m0f
* @param m1f
* @param points_3d
* @param colors
* @param bColor
*/
PIC_INLINE void triangulationPoints(Eigen::Matrix34d &M0,
Eigen::Matrix34d &M1,
std::vector< Eigen::Vector2f > &m0f,
std::vector< Eigen::Vector2f > &m1f,
std::vector< Eigen::Vector3d > &points_3d,
std::vector< unsigned char > &colors,
Image *img0 = NULL,
Image *img1 = NULL,
bool bColor = false
)
{
if(m0f.size() != m1f.size()) {
return;
}
NelderMeadOptTriangulation nmTri(M0, M1);
for(unsigned int i = 0; i < m0f.size(); i++) {
//normalized coordinates
Eigen::Vector3d p0 = Eigen::Vector3d(m0f[i][0], m0f[i][1], 1.0);
Eigen::Vector3d p1 = Eigen::Vector3d(m1f[i][0], m1f[i][1], 1.0);
//triangulation
Eigen::Vector4d point = triangulationHartleySturm(p0, p1, M0, M1);
//non-linear refinement
nmTri.update(m0f[i], m1f[i]);
double tmpp[] = {point[0], point[1], point[2]};
double out[3];
nmTri.run(tmpp, 3, 1e-9f, 10000, &out[0]);
//output
points_3d.push_back(Eigen::Vector3d(out[0], out[1], out[2]));
if(bColor) {
float *color0 = (*img0)(int(m0f[i][0]), int(m0f[i][1]));
float *color1 = (*img1)(int(m1f[i][0]), int(m1f[i][1]));
for(int j = 0; j < img0->channels; j++) {
float c_mean = (color0[j] + color1[j]) * 0.5f;
c_mean = CLAMPi(c_mean, 0.0f, 1.0f);
unsigned char c = int(c_mean * 255.0f);
colors.push_back(c);
}
}
}
}
#endif // PIC_DISABLE_EIGEN
} // end namespace pic
#endif // PIC_COMPUTER_VISION_TRIANGULATION_HPP
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <string>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <mesos/mesos.hpp>
#include <mesos/slave/containerizer.hpp>
#include <process/future.hpp>
#include <process/gmock.hpp>
#include <process/gtest.hpp>
#include <process/owned.hpp>
#include <process/pid.hpp>
#include <stout/gtest.hpp>
#include <stout/os/constants.hpp>
#include "master/master.hpp"
#include "master/detector/standalone.hpp"
#include "slave/slave.hpp"
#include "slave/containerizer/mesos/containerizer.hpp"
#include "tests/kill_policy_test_helper.hpp"
#include "tests/mesos.hpp"
#include "tests/mock_slave.hpp"
#include "tests/utils.hpp"
using mesos::internal::master::Master;
using mesos::internal::slave::Fetcher;
using mesos::internal::slave::MesosContainerizer;
using mesos::internal::slave::Slave;
using mesos::master::detector::MasterDetector;
using mesos::master::detector::StandaloneMasterDetector;
using mesos::slave::ContainerTermination;
using process::Future;
using process::Owned;
using process::PID;
using std::string;
using std::vector;
using ::testing::WithParamInterface;
namespace mesos {
namespace internal {
namespace tests {
// Tests that exercise the command executor implementation
// should be located in this file.
class CommandExecutorTest
: public MesosTest,
public WithParamInterface<bool> {};
// The Command Executor tests are parameterized by the underlying library
// used by the executor (e.g., driver or the HTTP based executor library).
INSTANTIATE_TEST_CASE_P(
HTTPCommandExecutor,
CommandExecutorTest,
::testing::Bool());
// This test ensures that the command executor does not send
// TASK_KILLING to frameworks that do not support the capability.
TEST_P(CommandExecutorTest, NoTaskKillingCapability)
{
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
Owned<MasterDetector> detector = master.get()->createDetector();
slave::Flags flags = CreateSlaveFlags();
flags.http_command_executor = GetParam();
Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), flags);
ASSERT_SOME(slave);
// Start the framework without the task killing capability.
MockScheduler sched;
MesosSchedulerDriver driver(
&sched, DEFAULT_FRAMEWORK_INFO, master.get()->pid, DEFAULT_CREDENTIAL);
EXPECT_CALL(sched, registered(&driver, _, _));
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(&driver, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(offers);
EXPECT_EQ(1u, offers->size());
// Launch a task with the command executor.
TaskInfo task = createTask(
offers->front().slave_id(),
offers->front().resources(),
SLEEP_COMMAND(1000));
Future<TaskStatus> statusRunning;
EXPECT_CALL(sched, statusUpdate(_, _))
.WillOnce(FutureArg<1>(&statusRunning));
driver.launchTasks(offers->front().id(), {task});
AWAIT_READY(statusRunning);
EXPECT_EQ(TASK_RUNNING, statusRunning->state());
// There should only be a TASK_KILLED update.
Future<TaskStatus> statusKilled;
EXPECT_CALL(sched, statusUpdate(_, _))
.WillOnce(FutureArg<1>(&statusKilled));
driver.killTask(task.task_id());
AWAIT_READY(statusKilled);
EXPECT_EQ(TASK_KILLED, statusKilled->state());
driver.stop();
driver.join();
}
// This test ensures that the command executor sends TASK_KILLING
// to frameworks that support the capability.
// TODO(hausdorff): Enable test. The executor tests use the replicated log
// by default. This is not currently supported on Windows, so they will all
// fail until that changes.
TEST_P(CommandExecutorTest, TaskKillingCapability)
{
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
Owned<MasterDetector> detector = master.get()->createDetector();
slave::Flags flags = CreateSlaveFlags();
flags.http_command_executor = GetParam();
Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), flags);
ASSERT_SOME(slave);
// Start the framework with the task killing capability.
FrameworkInfo::Capability capability;
capability.set_type(FrameworkInfo::Capability::TASK_KILLING_STATE);
FrameworkInfo frameworkInfo = DEFAULT_FRAMEWORK_INFO;
frameworkInfo.add_capabilities()->CopyFrom(capability);
MockScheduler sched;
MesosSchedulerDriver driver(
&sched, frameworkInfo, master.get()->pid, DEFAULT_CREDENTIAL);
EXPECT_CALL(sched, registered(&driver, _, _));
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(&driver, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(offers);
EXPECT_EQ(1u, offers->size());
// Launch a task with the command executor.
TaskInfo task = createTask(
offers->front().slave_id(),
offers->front().resources(),
SLEEP_COMMAND(1000));
Future<TaskStatus> statusRunning;
EXPECT_CALL(sched, statusUpdate(_, _))
.WillOnce(FutureArg<1>(&statusRunning));
driver.launchTasks(offers->front().id(), {task});
AWAIT_READY(statusRunning);
EXPECT_EQ(TASK_RUNNING, statusRunning->state());
Future<TaskStatus> statusKilling, statusKilled;
EXPECT_CALL(sched, statusUpdate(_, _))
.WillOnce(FutureArg<1>(&statusKilling))
.WillOnce(FutureArg<1>(&statusKilled));
driver.killTask(task.task_id());
AWAIT_READY(statusKilling);
EXPECT_EQ(TASK_KILLING, statusKilling->state());
AWAIT_READY(statusKilled);
EXPECT_EQ(TASK_KILLED, statusKilled->state());
driver.stop();
driver.join();
}
// TODO(hausdorff): Kill policy helpers are not yet enabled on Windows. See
// MESOS-6698.
#ifndef __WINDOWS__
// This test ensures that a task will transition straight from `TASK_KILLING` to
// `TASK_KILLED`, even if the health check begins to fail during the kill policy
// grace period.
//
// TODO(gkleiman): this test takes about 7 seconds to run, consider using mock
// tasks and health checkers to speed it up.
TEST_P(CommandExecutorTest, NoTransitionFromKillingToRunning)
{
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
Owned<MasterDetector> detector = master.get()->createDetector();
slave::Flags flags = CreateSlaveFlags();
flags.http_command_executor = GetParam();
Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), flags);
ASSERT_SOME(slave);
// Start the framework with the task killing capability.
FrameworkInfo::Capability capability;
capability.set_type(FrameworkInfo::Capability::TASK_KILLING_STATE);
FrameworkInfo frameworkInfo = DEFAULT_FRAMEWORK_INFO;
frameworkInfo.add_capabilities()->CopyFrom(capability);
MockScheduler sched;
MesosSchedulerDriver driver(
&sched, frameworkInfo, master.get()->pid, DEFAULT_CREDENTIAL);
EXPECT_CALL(sched, registered(&driver, _, _));
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(&driver, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(offers);
EXPECT_EQ(1u, offers->size());
const string command = strings::format(
"%s %s --sleep_duration=15",
getTestHelperPath("test-helper"),
KillPolicyTestHelper::NAME).get();
TaskInfo task = createTask(offers->front(), command);
// Create a health check that succeeds until a temporary file is removed.
Try<string> temporaryPath = os::mktemp(path::join(os::getcwd(), "XXXXXX"));
ASSERT_SOME(temporaryPath);
const string tmpPath = temporaryPath.get();
HealthCheck healthCheck;
healthCheck.set_type(HealthCheck::COMMAND);
healthCheck.mutable_command()->set_value(
"ls " + tmpPath + " > " + os::DEV_NULL);
healthCheck.set_delay_seconds(0);
healthCheck.set_grace_period_seconds(0);
healthCheck.set_interval_seconds(0);
task.mutable_health_check()->CopyFrom(healthCheck);
// Set the kill policy grace period to 5 seconds.
KillPolicy killPolicy;
killPolicy.mutable_grace_period()->set_nanoseconds(Seconds(5).ns());
task.mutable_kill_policy()->CopyFrom(killPolicy);
vector<TaskInfo> tasks;
tasks.push_back(task);
Future<TaskStatus> statusRunning;
Future<TaskStatus> statusHealthy;
Future<TaskStatus> statusKilling;
Future<TaskStatus> statusKilled;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&statusRunning))
.WillOnce(FutureArg<1>(&statusHealthy))
.WillOnce(FutureArg<1>(&statusKilling))
.WillOnce(FutureArg<1>(&statusKilled));
driver.launchTasks(offers->front().id(), tasks);
AWAIT_READY(statusRunning);
EXPECT_EQ(TASK_RUNNING, statusRunning->state());
AWAIT_READY(statusHealthy);
EXPECT_EQ(TASK_RUNNING, statusHealthy->state());
EXPECT_TRUE(statusHealthy->has_healthy());
EXPECT_TRUE(statusHealthy->healthy());
driver.killTask(task.task_id());
AWAIT_READY(statusKilling);
EXPECT_EQ(TASK_KILLING, statusKilling->state());
EXPECT_FALSE(statusKilling->has_healthy());
// Remove the temporary file, so that the health check fails.
os::rm(tmpPath);
AWAIT_READY(statusKilled);
EXPECT_EQ(TASK_KILLED, statusKilled->state());
EXPECT_FALSE(statusKilled->has_healthy());
driver.stop();
driver.join();
}
#endif // __WINDOWS__
class HTTPCommandExecutorTest
: public MesosTest {};
// This test ensures that the HTTP command executor can self terminate
// after it gets the ACK for the terminal status update from agent.
TEST_F_TEMP_DISABLED_ON_WINDOWS(HTTPCommandExecutorTest, TerminateWithACK)
{
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
slave::Flags flags = CreateSlaveFlags();
flags.http_command_executor = true;
Fetcher fetcher(flags);
Try<MesosContainerizer*> _containerizer =
MesosContainerizer::create(flags, false, &fetcher);
ASSERT_SOME(_containerizer);
Owned<MesosContainerizer> containerizer(_containerizer.get());
StandaloneMasterDetector detector(master.get()->pid);
MockSlave slave(flags, &detector, containerizer.get());
spawn(slave);
MockScheduler sched;
MesosSchedulerDriver driver(
&sched, DEFAULT_FRAMEWORK_INFO, master.get()->pid, DEFAULT_CREDENTIAL);
EXPECT_CALL(sched, registered(&driver, _, _));
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(&driver, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(offers);
EXPECT_EQ(1u, offers->size());
// Launch a short lived task.
TaskInfo task = createTask(
offers->front().slave_id(),
offers->front().resources(),
"sleep 1");
Future<TaskStatus> statusRunning;
Future<TaskStatus> statusFinished;
EXPECT_CALL(sched, statusUpdate(_, _))
.WillOnce(FutureArg<1>(&statusRunning))
.WillOnce(FutureArg<1>(&statusFinished));
Future<Future<Option<ContainerTermination>>> termination;
EXPECT_CALL(slave, executorTerminated(_, _, _))
.WillOnce(FutureArg<2>(&termination));
driver.launchTasks(offers->front().id(), {task});
// Scheduler should first receive TASK_RUNNING followed by TASK_FINISHED.
AWAIT_READY(statusRunning);
EXPECT_EQ(TASK_RUNNING, statusRunning->state());
AWAIT_READY(statusFinished);
EXPECT_EQ(TASK_FINISHED, statusFinished->state());
// The executor should self terminate with 0 as exit status once
// it gets the ACK for the terminal status update from agent.
AWAIT_READY(termination);
ASSERT_TRUE(termination->isReady());
EXPECT_EQ(0, termination->get()->status());
driver.stop();
driver.join();
terminate(slave);
wait(slave);
}
// This test ensures that driver based schedulers using explicit
// acknowledgements can acknowledge status updates sent from
// HTTP based executors.
TEST_F(HTTPCommandExecutorTest, ExplicitAcknowledgements)
{
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
Owned<MasterDetector> detector = master.get()->createDetector();
slave::Flags flags = CreateSlaveFlags();
flags.http_command_executor = true;
Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), flags);
ASSERT_SOME(slave);
MockScheduler sched;
MesosSchedulerDriver driver(
&sched,
DEFAULT_FRAMEWORK_INFO,
master.get()->pid,
false,
DEFAULT_CREDENTIAL);
EXPECT_CALL(sched, registered(&driver, _, _));
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(&driver, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(offers);
EXPECT_EQ(1u, offers->size());
// Launch a task with the command executor.
TaskInfo task = createTask(
offers->front().slave_id(),
offers->front().resources(),
SLEEP_COMMAND(1000));
Future<TaskStatus> statusRunning;
EXPECT_CALL(sched, statusUpdate(_, _))
.WillOnce(FutureArg<1>(&statusRunning));
// Ensure no status update acknowledgements are sent from the driver
// to the master until the explicit acknowledgement is sent.
EXPECT_NO_FUTURE_CALLS(
mesos::scheduler::Call(),
mesos::scheduler::Call::ACKNOWLEDGE,
_,
master.get()->pid);
driver.launchTasks(offers->front().id(), {task});
AWAIT_READY(statusRunning);
EXPECT_TRUE(statusRunning->has_slave_id());
EXPECT_EQ(TASK_RUNNING, statusRunning->state());
// Now send the acknowledgement.
Future<mesos::scheduler::Call> acknowledgement = FUTURE_CALL(
mesos::scheduler::Call(),
mesos::scheduler::Call::ACKNOWLEDGE,
_,
master.get()->pid);
driver.acknowledgeStatusUpdate(statusRunning.get());
AWAIT_READY(acknowledgement);
driver.stop();
driver.join();
}
} // namespace tests {
} // namespace internal {
} // namespace mesos {
|
#ifndef __ENVIRONMENT_COMMANDS_FAKE_ASSETS_RELATER__
#define __ENVIRONMENT_COMMANDS_FAKE_ASSETS_RELATER__
#include "../../../fwd.hpp"
namespace Environment
{
namespace Commands
{
namespace Rich
{
namespace Assets
{
class Relater : public supps::Command<structs::Buffer, const std::string &, const std::string &>
{
public:
Relater(supps::Command<structs::Buffer, const std::string &> * fetcher);
structs::Buffer execute(const std::string & object, const std::string & type) override;
private:
supps::Command<structs::Buffer, const std::string &> * _featcher;
supps::Command<structs::Buffer, const std::string &> * _assetsFeatcher;
};
}
}
}
}
#endif
|
// ------------------------------------------------------------------
// Fast R-CNN
// copyright (c) 2015 Microsoft
// Licensed under The MIT License [see fast-rcnn/LICENSE for details]
// Written by Ross Girshick
// Modified by Wei Liu
// ------------------------------------------------------------------
#include <vector>
#include "caffe/layers/smooth_L1_loss_layer.hpp"
#include "caffe/util/math_functions.hpp"
namespace caffe {
template <typename Dtype>
void SmoothL1LossLayer<Dtype>::LayerSetUp(
const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {
LossLayer<Dtype>::LayerSetUp(bottom, top);
has_weights_ = (bottom.size() == 3);
}
template <typename Dtype>
void SmoothL1LossLayer<Dtype>::Reshape(
const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {
LossLayer<Dtype>::Reshape(bottom, top);
CHECK_EQ(bottom[0]->channels(), bottom[1]->channels());
CHECK_EQ(bottom[0]->height(), bottom[1]->height());
CHECK_EQ(bottom[0]->width(), bottom[1]->width());
if (has_weights_) {
CHECK_EQ(bottom[0]->channels(), bottom[2]->channels());
CHECK_EQ(bottom[0]->height(), bottom[2]->height());
CHECK_EQ(bottom[0]->width(), bottom[2]->width());
}
diff_.Reshape(bottom[0]->num(), bottom[0]->channels(),
bottom[0]->height(), bottom[0]->width());
errors_.Reshape(bottom[0]->num(), bottom[0]->channels(),
bottom[0]->height(), bottom[0]->width());
}
template <typename Dtype>
void SmoothL1LossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
int count = bottom[0]->count();
caffe_sub(
count,
bottom[0]->cpu_data(),
bottom[1]->cpu_data(),
diff_.mutable_cpu_data());
if (has_weights_) {
caffe_mul(
count,
bottom[2]->cpu_data(),
diff_.cpu_data(),
diff_.mutable_cpu_data()); // d := w * (b0 - b1)
}
const Dtype* diff_data = diff_.cpu_data();
Dtype* error_data = errors_.mutable_cpu_data();
for (int i = 0; i < count; ++i) {
Dtype val = diff_data[i];
Dtype abs_val = fabs(val);
if (abs_val < 1.) {
error_data[i] = 0.5 * val * val;
} else {
error_data[i] = abs_val - 0.5;
}
}
top[0]->mutable_cpu_data()[0] =
caffe_cpu_asum(count, errors_.cpu_data()) / bottom[0]->num();
}
template <typename Dtype>
void SmoothL1LossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
int count = diff_.count();
Dtype* diff_data = diff_.mutable_cpu_data();
for (int i = 0; i < count; ++i) {
Dtype val = diff_data[i];
// f'(x) = x if |x| < 1
// = sign(x) otherwise
if (fabs(val) < 1.) {
diff_data[i] = val;
} else {
diff_data[i] = (Dtype(0) < val) - (val < Dtype(0));
}
}
for (int i = 0; i < 2; ++i) {
if (propagate_down[i]) {
const Dtype sign = (i == 0) ? 1 : -1;
const Dtype alpha = sign * top[0]->cpu_diff()[0] / bottom[i]->num();
caffe_cpu_axpby(
bottom[i]->count(), // count
alpha, // alpha
diff_.cpu_data(), // a
Dtype(0), // beta
bottom[i]->mutable_cpu_diff()); // b
}
}
}
#ifdef CPU_ONLY
STUB_GPU(SmoothL1LossLayer);
#endif
INSTANTIATE_CLASS(SmoothL1LossLayer);
REGISTER_LAYER_CLASS(SmoothL1Loss);
} // namespace caffe
|
#include <vector>
using namespace std;
class Solution {
public:
void rotate(vector<int> &nums, int k) {
vector<int> nums2 = nums;
int l = size(nums);
for (int i = 0; i < l; i++) {
nums2[(i + k) % l] = nums[i];
}
nums = nums2;
}
};
|
#include <pybind11/eigen.h>
#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
#include <string>
#include <extrinsics_calibrator/CheckerboardExtrinsicCalibration.h>
namespace py = pybind11;
PYBIND11_MODULE(ExtrinsicCalibPyModules, m) {
m.doc() = "Python Wrapper for Extrinsics Calibrator using GTSAM"; // optional module
pybind11::class_<CheckerboardExtrinsicCalibration>(m, "CheckerboardExtrinsicCalibration")
.def(pybind11::init<std::string>())
.def("add_measurement", &CheckerboardExtrinsicCalibration::addMeasurement)
.def("solve", &CheckerboardExtrinsicCalibration::solve);
}
|
#ifndef CLIENT_WINDOW_HPP_INCLUDED
#define CLIENT_WINDOW_HPP_INCLUDED
#include <glm/vec2.hpp>
#include <SDL2/SDL.h>
namespace Client
{
class Window
{
public:
Window();
virtual ~Window();
/**
* @brief Initialize the window.
*
* Creates the SDL_Window and all required SDL structs.
*
* @param windowSize The size the SDL Window should have.
*/
int init(const glm::ivec2 &windowSize, bool fullscreen);
SDL_Renderer* getSDLRenderer();
SDL_Window* getSDLWindow();
void onEvent(const SDL_Event &e);
glm::ivec2 getSize();
void glClear();
private:
typedef void (*GLFunction_ClearColor)(float , float, float, float);
typedef void (*GLFunction_Clear)(SDL_Window*);
SDL_Window *m_window = nullptr;
SDL_Renderer *m_renderer = nullptr;
SDL_GLContext m_glContext = nullptr;
bool m_SDLInitialized = false;
bool m_SDLImageInitialized = false;
bool m_SDLTTFInitialized = true;
void* m_glClearColor = nullptr;
void* m_glClear = nullptr;
};
}
#endif
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <istream>
#include <memory>
#include "ir_frontend/utility.hpp"
#include "openvino/core/attribute_visitor.hpp"
#include "utils.hpp"
namespace ov {
class RTInfoDeserializer : public ov::AttributeVisitor {
public:
explicit RTInfoDeserializer(const pugi::xml_node& node) : m_node(node) {}
void on_adapter(const std::string& name, ov::ValueAccessor<std::string>& value) override {
check_attribute_name(name);
std::string val;
if (!getStrAttribute(m_node, name, val))
return;
value.set(val);
}
void on_adapter(const std::string& name, ov::ValueAccessor<bool>& value) override {
check_attribute_name(name);
std::string val;
if (!getStrAttribute(m_node, name, val))
return;
std::transform(val.begin(), val.end(), val.begin(), [](char ch) {
return std::tolower(static_cast<unsigned char>(ch));
});
std::set<std::string> true_names{"true", "1"};
std::set<std::string> false_names{"false", "0"};
bool is_true = true_names.find(val) != true_names.end();
bool is_false = false_names.find(val) != false_names.end();
if (!is_true && !is_false)
return;
value.set(is_true);
}
void on_adapter(const std::string& name, ov::ValueAccessor<void>& adapter) override;
void on_adapter(const std::string& name, ov::ValueAccessor<double>& adapter) override {
check_attribute_name(name);
std::string val;
if (!getStrAttribute(m_node, name, val))
return;
adapter.set(stringToType<double>(val));
}
void on_adapter(const std::string& name, ov::ValueAccessor<int64_t>& adapter) override {
check_attribute_name(name);
std::string val;
if (!getStrAttribute(m_node, name, val))
return;
adapter.set(stringToType<int64_t>(val));
}
void on_adapter(const std::string& name, ov::ValueAccessor<std::shared_ptr<ov::Model>>& adapter) override {
throw ov::Exception("Function type is unsupported for rt info deserialization");
}
void on_adapter(const std::string& name, ov::ValueAccessor<std::vector<int32_t>>& adapter) override {
check_attribute_name(name);
std::string val;
if (!getStrAttribute(m_node, name, val))
return;
std::vector<int32_t> value;
str_to_container(val, value);
adapter.set(value);
}
void on_adapter(const std::string& name, ov::ValueAccessor<std::vector<int64_t>>& adapter) override {
check_attribute_name(name);
std::string val;
if (!getStrAttribute(m_node, name, val))
return;
std::vector<int64_t> value;
str_to_container(val, value);
adapter.set(value);
}
void on_adapter(const std::string& name, ov::ValueAccessor<std::vector<float>>& adapter) override {
check_attribute_name(name);
std::string val;
if (!getStrAttribute(m_node, name, val))
return;
std::vector<float> value;
str_to_container(val, value);
adapter.set(value);
}
void on_adapter(const std::string& name, ov::ValueAccessor<std::vector<uint64_t>>& adapter) override {
check_attribute_name(name);
std::string val;
if (!getStrAttribute(m_node, name, val))
return;
std::vector<uint64_t> value;
str_to_container(val, value);
adapter.set(value);
}
void on_adapter(const std::string& name, ov::ValueAccessor<std::vector<std::string>>& adapter) override {
check_attribute_name(name);
std::string val;
if (!getStrAttribute(m_node, name, val))
return;
std::vector<std::string> value;
str_to_container(val, value);
adapter.set(value);
}
void check_attribute_name(const std::string& name) const {
if (name == "name" || name == "version") {
throw ov::Exception("Attribute key with name: " + name + " is not allowed. Please use another name");
}
}
private:
pugi::xml_node m_node;
};
} // namespace ov
|
#pragma once
#include "./BaseObj.hpp"
namespace android::renderscript
{
class RenderScript;
}
namespace android::renderscript
{
class Script;
}
namespace android::renderscript
{
class Script_KernelID : public android::renderscript::BaseObj
{
public:
// Fields
// QJniObject forward
template<typename ...Ts> explicit Script_KernelID(const char *className, const char *sig, Ts...agv) : android::renderscript::BaseObj(className, sig, std::forward<Ts>(agv)...) {}
Script_KernelID(QJniObject obj);
// Constructors
// Methods
};
} // namespace android::renderscript
|
#include "GstReStreamer2.h"
#include <cassert>
#include <gst/gst.h>
#include <gst/pbutils/pbutils.h>
#include <gst/webrtc/rtptransceiver.h>
#include <CxxPtr/GlibPtr.h>
#include <CxxPtr/GstPtr.h>
#include "Helpers.h"
GstReStreamer2::GstReStreamer2(
const std::string& sourceUrl,
const std::string& forceH264ProfileLevelId) :
_sourceUrl(sourceUrl),
_forceH264ProfileLevelId(forceH264ProfileLevelId)
{
}
void GstReStreamer2::prepare() noexcept
{
assert(!pipeline());
if(pipeline())
return;
_h264CapsPtr.reset(gst_caps_from_string("video/x-h264"));
_vp8CapsPtr.reset(gst_caps_from_string("video/x-vp8"));
GstCapsPtr supportedCapsPtr(gst_caps_copy(_h264CapsPtr.get()));
gst_caps_append(supportedCapsPtr.get(), gst_caps_copy(_vp8CapsPtr.get()));
GstCaps* supportedCaps = supportedCapsPtr.get();
setPipeline(GstElementPtr(gst_pipeline_new(nullptr)));
GstElement* pipeline = this->pipeline();
GstElementPtr srcPtr(gst_element_factory_make("uridecodebin", nullptr));
GstElement* decodebin = srcPtr.get();
if(!decodebin)
return;
g_object_set(decodebin, "caps", supportedCaps, nullptr);
auto srcPadAddedCallback =
(void (*)(GstElement*, GstPad*, gpointer))
[] (GstElement* decodebin, GstPad* pad, gpointer userData) {
GstReStreamer2* self = static_cast<GstReStreamer2*>(userData);
self->srcPadAdded(decodebin, pad);
};
g_signal_connect(decodebin, "pad-added", G_CALLBACK(srcPadAddedCallback), this);
auto noMorePadsCallback =
(void (*)(GstElement*, gpointer))
[] (GstElement* decodebin, gpointer userData) {
GstReStreamer2* self = static_cast<GstReStreamer2*>(userData);
self->noMorePads(decodebin);
};
g_signal_connect(decodebin, "no-more-pads", G_CALLBACK(noMorePadsCallback), this);
g_object_set(decodebin,
"uri", _sourceUrl.c_str(),
nullptr);
gst_bin_add(GST_BIN(pipeline), srcPtr.release());
play();
}
void GstReStreamer2::srcPadAdded(
GstElement* /*decodebin*/,
GstPad* pad)
{
GstElement* pipeline = this->pipeline();
GstCapsPtr capsPtr(gst_pad_get_current_caps(pad));
GstCaps* caps = capsPtr.get();
GstElement* payBin = nullptr;
if(gst_caps_is_always_compatible(caps, _h264CapsPtr.get())) {
const bool forceH264ProfileLevelId = !_forceH264ProfileLevelId.empty();
std::string repayPipelineDesc =
"h264parse config-interval=-1 ! rtph264pay pt=96";
if(forceH264ProfileLevelId)
repayPipelineDesc += " ! capssetter name=capssetter";
payBin =
gst_parse_bin_from_description(
repayPipelineDesc.c_str(),
TRUE, NULL);
gst_bin_add(GST_BIN(pipeline), payBin);
gst_element_sync_state_with_parent(payBin);
GstPad* sink = (GstPad*)payBin->sinkpads->data;
if(GST_PAD_LINK_OK != gst_pad_link(pad, sink))
assert(false);
if(forceH264ProfileLevelId) {
GstElementPtr capsSetterPtr(gst_bin_get_by_name(GST_BIN(payBin), "capssetter"));
const std::string caps = "application/x-rtp,profile-level-id=(string)" + _forceH264ProfileLevelId;
gst_util_set_object_arg(G_OBJECT(capsSetterPtr.get()), "caps", caps.c_str());
}
} else if(gst_caps_is_always_compatible(caps, _vp8CapsPtr.get())) {
payBin =
gst_parse_bin_from_description(
"rtpvp8pay pt=96",
TRUE, NULL);
gst_bin_add(GST_BIN(pipeline), payBin);
gst_element_sync_state_with_parent(payBin);
GstPad* sink = (GstPad*)payBin->sinkpads->data;
if(GST_PAD_LINK_OK != gst_pad_link(pad, sink))
assert(false);
} else
return;
GstElementPtr teePtr(gst_element_factory_make("tee", nullptr));
GstElement* tee = teePtr.get();
gst_bin_add(GST_BIN(pipeline), GST_ELEMENT(gst_object_ref(tee)));
gst_element_sync_state_with_parent(tee);
gst_element_link(payBin, tee);
setTee(std::move(teePtr));
}
void GstReStreamer2::noMorePads(GstElement* /*decodebin*/)
{
}
void GstReStreamer2::cleanup() noexcept
{
_h264CapsPtr.reset();
_vp8CapsPtr.reset();
GstStreamingSource::cleanup();
}
|
/*
* Copyright (c) 2016, Georgia Tech Research Corporation
* All rights reserved.
*
* Author(s): Jeongseok Lee <jslee02@gmail.com>
*
* Georgia Tech Graphics Lab and Humanoid Robotics Lab
*
* Directed by Prof. C. Karen Liu and Prof. Mike Stilman
* <karenliu@cc.gatech.edu> <mstilman@cc.gatech.edu>
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "dart/collision/CollisionObject.hpp"
#include "dart/collision/CollisionDetector.hpp"
#include "dart/dynamics/ShapeFrame.hpp"
namespace dart {
namespace collision {
//==============================================================================
CollisionDetector* CollisionObject::getCollisionDetector()
{
return mCollisionDetector;
}
//==============================================================================
const CollisionDetector* CollisionObject::getCollisionDetector() const
{
return mCollisionDetector;
}
//==============================================================================
const dynamics::ShapeFrame* CollisionObject::getShapeFrame() const
{
return mShapeFrame;
}
//==============================================================================
dynamics::ConstShapePtr CollisionObject::getShape() const
{
return mShapeFrame->getShape();
}
//==============================================================================
const Eigen::Isometry3d& CollisionObject::getTransform() const
{
return mShapeFrame->getWorldTransform();
}
//==============================================================================
CollisionObject::CollisionObject(
CollisionDetector* collisionDetector,
const dynamics::ShapeFrame* shapeFrame)
: mCollisionDetector(collisionDetector),
mShapeFrame(shapeFrame)
{
assert(mCollisionDetector);
assert(mShapeFrame);
}
} // namespace collision
} // namespace dart
|
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include "interfaces/iroha_internal/transaction_batch.hpp"
#include "interfaces/transaction.hpp"
#include "utils/string_builder.hpp"
namespace shared_model {
namespace interface {
std::string TransactionBatch::toString() const {
return detail::PrettyStringBuilder()
.init("TransactionBatch")
.appendNamed("Transactions", transactions())
.finalize();
}
bool BatchHashEquality::operator()(
const std::shared_ptr<TransactionBatch> &left_tx,
const std::shared_ptr<TransactionBatch> &right_tx) const {
return left_tx->reducedHash() == right_tx->reducedHash();
}
} // namespace interface
} // namespace shared_model
|
/*****************************************************************************/
/**
* @file main.cpp
* @author Naohisa Sakamoto
* @brief Example program for kvs::StochasticPolygonRenderer class.
*/
/*****************************************************************************/
#include <kvs/glut/Application>
#include <kvs/glut/Screen>
#include <kvs/CheckBox>
#include <kvs/Slider>
#include <kvs/PolygonObject>
#include <kvs/PolygonImporter>
#include <kvs/StructuredVolumeObject>
#include <kvs/HydrogenVolumeData>
#include <kvs/Isosurface>
#include <kvs/StochasticPolygonRenderer>
#include <kvs/Scene>
#include <kvs/ObjectManager>
#include <kvs/RendererManager>
#include <iostream>
/*===========================================================================*/
/**
* @brief LOD check box.
*/
/*===========================================================================*/
class LODCheckBox : public kvs::CheckBox
{
public:
LODCheckBox( kvs::glut::Screen* screen ):
kvs::CheckBox( screen )
{
setMargin( 10 );
setCaption( "Level-of-Detail" );
}
void stateChanged()
{
typedef kvs::StochasticPolygonRenderer Renderer;
kvs::Scene* scene = static_cast<kvs::glut::Screen*>( screen() )->scene();
Renderer* renderer = static_cast<Renderer*>( scene->rendererManager()->renderer( "Renderer" ) );
renderer->setEnabledLODControl( state() );
screen()->redraw();
}
};
/*===========================================================================*/
/**
* @brief Opacity slider.
*/
/*===========================================================================*/
class OpacitySlider : public kvs::Slider
{
public:
OpacitySlider( kvs::glut::Screen* screen ):
kvs::Slider( screen )
{
setWidth( 150 );
setMargin( 10 );
setCaption( "Opacity" );
}
void valueChanged()
{
typedef kvs::PolygonObject Object;
kvs::Scene* scene = static_cast<kvs::glut::Screen*>( screen() )->scene();
Object* object1 = Object::DownCast( scene->objectManager()->object( "Polygon" ) );
Object* object2 = new Object();
object2->shallowCopy( *object1 );
object2->setName( "Polygon" );
object2->setOpacity( int( value() * 255 + 0.5 ) );
scene->objectManager()->change( "Polygon", object2 );
}
};
/*===========================================================================*/
/**
* @brief Repetition slider.
*/
/*===========================================================================*/
class RepetitionSlider : public kvs::Slider
{
public:
RepetitionSlider( kvs::glut::Screen* screen ):
kvs::Slider( screen )
{
setWidth( 150 );
setMargin( 10 );
setCaption( "Repetition" );
}
void valueChanged()
{
typedef kvs::StochasticPolygonRenderer Renderer;
kvs::Scene* scene = static_cast<kvs::glut::Screen*>( screen() )->scene();
Renderer* renderer = static_cast<Renderer*>( scene->rendererManager()->renderer( "Renderer" ) );
renderer->setRepetitionLevel( int( value() + 0.5 ) );
screen()->redraw();
}
};
/*===========================================================================*/
/**
* @brief Import polygon object
* @param argc [i] argument count
* @param argv [i] argument values
* @return pointer to the imported polygon object
*/
/*===========================================================================*/
kvs::PolygonObject* Import( int argc, char** argv )
{
kvs::PolygonObject* object = NULL;
if ( argc > 1 )
{
object = new kvs::PolygonImporter( argv[1] );
}
else
{
/* If the data file isn't specified, a hydrogen volume data is generated by
* using kvs::HydrogenVolumeData class and then an isosurface polygon object
* is extracted from the volume data.
*/
kvs::Vector3ui resolution( 64, 64, 64 );
kvs::StructuredVolumeObject* volume = new kvs::HydrogenVolumeData( resolution );
volume->updateMinMaxValues();
const double i = ( volume->maxValue() + volume->minValue() ) * 0.5;
const kvs::PolygonObject::NormalType n = kvs::PolygonObject::VertexNormal;
const bool d = false;
const kvs::TransferFunction t( 256 );
object = new kvs::Isosurface( volume, i, n, d, t );
delete volume;
}
return object;
}
/*===========================================================================*/
/**
* @brief Main function.
* @param argc [i] argument counter
* @param argv [i] argument values
* @return true, if the main process is done succesfully
*/
/*===========================================================================*/
int main( int argc, char** argv )
{
kvs::glut::Application app( argc, argv );
kvs::PolygonObject* object = Import( argc, argv );
object->setName( "Polygon" );
object->setOpacity( 128 );
object->print( std::cout );
kvs::StochasticPolygonRenderer* renderer = new kvs::StochasticPolygonRenderer();
renderer->setName( "Renderer" );
renderer->setRepetitionLevel( 50 );
renderer->enableLODControl();
kvs::glut::Screen screen( &app );
screen.setTitle("Example program for kvs::StochasticPolygonRenderer");
screen.registerObject( object, renderer );
screen.show();
LODCheckBox checkbox( &screen );
checkbox.setPosition( 0, 0 );
checkbox.setState( true );
checkbox.show();
OpacitySlider opacity( &screen );
opacity.setPosition( checkbox.x(), checkbox.y() + checkbox.height() );
opacity.setValue( 0.5 );
opacity.setRange( 0, 1 );
opacity.show();
RepetitionSlider repetition( &screen );
repetition.setPosition( opacity.x(), opacity.y() + opacity.height() );
repetition.setValue( 50 );
repetition.setRange( 1, 100 );
repetition.show();
return app.run();
}
|
// Copyright 2013 Samsung Electronics. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "browser/vibration/vibration_provider_client.h"
VibrationProviderClient* VibrationProviderClient::vibration_provider_client_ = NULL;
VibrationProviderClient* VibrationProviderClient::GetInstance() {
if (!vibration_provider_client_)
vibration_provider_client_ = new VibrationProviderClient;
return vibration_provider_client_;
}
void VibrationProviderClient::DeleteInstance() {
if (vibration_provider_client_)
delete vibration_provider_client_;
vibration_provider_client_ = NULL;
}
void VibrationProviderClient::Vibrate(uint64_t vibration_time) {
if (vibration_client_.get() && vibration_client_->vibrate_)
vibration_client_->vibrate_(vibration_time, vibration_client_->user_data_);
}
void VibrationProviderClient::CancelVibration() {
if (vibration_client_.get() && vibration_client_->cancel_vibration_)
vibration_client_->cancel_vibration_(vibration_client_->user_data_);
}
void VibrationProviderClient::SetVibrationClientCallbacks(tizen_webview::Vibration_Client_Vibrate_Cb vibrate,
tizen_webview::Vibration_Client_Vibration_Cancel_Cb cancelVibration,
void* data) {
vibration_client_.reset(new Ewk_Vibration_Client(vibrate, cancelVibration, data));
}
|
#pragma once
#include "search/bookmarks/types.hpp"
#include "search/mode.hpp"
#include "geometry/point2d.hpp"
#include "geometry/rect2d.hpp"
#include <chrono>
#include <cstddef>
#include <functional>
#include <memory>
#include <optional>
#include <string>
namespace search
{
class Results;
class Tracer;
struct SearchParams
{
inline static size_t const kDefaultNumBookmarksResults = 1000;
inline static size_t const kDefaultBatchSizeEverywhere = 10;
inline static size_t const kDefaultNumResultsEverywhere = 30;
inline static size_t const kDefaultNumResultsInViewport = 200;
inline static size_t const kPreResultsCount = 200;
inline static double const kDefaultStreetSearchRadiusM = 8e4;
inline static double const kDefaultVillageSearchRadiusM = 2e5;
// TODO: Short timeouts leads to a non-working search on slow devices. Design a better solution.
inline static std::chrono::steady_clock::duration const kDefaultTimeout =
std::chrono::seconds(8);
inline static std::chrono::steady_clock::duration const kDefaultDesktopTimeout =
std::chrono::seconds(8);
using OnStarted = std::function<void()>;
using OnResults = std::function<void(Results const &)>;
bool IsEqualCommon(SearchParams const & rhs) const;
void Clear() { m_query.clear(); }
OnStarted m_onStarted;
// This function may be called an arbitrary number of times during
// the search session. The argument to every call except the first must contain
// as its prefix the argument of the previous call, i.e. |m_onResults| is
// always called for the whole array of results found so far but new results
// are only appended to the end.
//
// The function may be called several times with the same arguments.
// The reasoning is as follows: we could either 1) rearrange results
// between calls if a better ranked result is found after the first
// emit has happened or 2) only append as we do now but never call
// the function twice with the same array of results.
// We decided against the option 1) so as not to annoy the user by
// rearranging.
// We do not guarantee the option 2) because an efficient client
// would only need to redraw the appended part and therefore would
// be fast enough if the two calls are the same. The implementation of
// the search may decide against duplicating calls but no guarantees are given.
OnResults m_onResults;
std::string m_query;
std::string m_inputLocale;
std::optional<m2::PointD> m_position;
m2::RectD m_viewport;
size_t m_batchSize = kDefaultBatchSizeEverywhere;
size_t m_maxNumResults = kDefaultNumResultsEverywhere;
// Minimal distance between search results in mercators, needed for
// pre-ranking of viewport search results.
double m_minDistanceOnMapBetweenResultsX = 0.0;
double m_minDistanceOnMapBetweenResultsY = 0.0;
// Street search radius from pivot or matched city center for everywhere search mode.
double m_streetSearchRadiusM = kDefaultStreetSearchRadiusM;
// Street search radius from pivot for everywhere search mode.
double m_villageSearchRadiusM = kDefaultVillageSearchRadiusM;
Mode m_mode = Mode::Everywhere;
// Needed to generate search suggests.
bool m_suggestsEnabled = false;
// Needed to generate address for results.
bool m_needAddress = false;
// Needed to highlight matching parts of search result names.
bool m_needHighlighting = false;
bookmarks::GroupId m_bookmarksGroupId = bookmarks::kInvalidGroupId;
// Amount of time after which the search is aborted.
std::chrono::steady_clock::duration m_timeout = kDefaultTimeout;
std::shared_ptr<Tracer> m_tracer;
};
std::string DebugPrint(SearchParams const & params);
} // namespace search
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/file_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
// These are only used for commented out tests. If someone wants to enable
// them, they should be moved to chrome first.
// #include "chrome/browser/history/history_service.h"
// #include "chrome/browser/profiles/profile_manager.h"
// #include "chrome/browser/sessions/session_service.h"
// #include "chrome/browser/sessions/session_service_factory.h"
// #include "chrome/browser/sessions/session_service_test_helper.h"
// #include "chrome/browser/sessions/session_types.h"
#include "content/browser/renderer_host/test_render_view_host.h"
#include "content/browser/site_instance_impl.h"
#include "content/browser/web_contents/navigation_controller_impl.h"
#include "content/browser/web_contents/navigation_entry_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/browser/web_contents/web_contents_screenshot_manager.h"
#include "content/common/view_messages.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_view_host_observer.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/common/page_state.h"
#include "content/public/common/url_constants.h"
#include "content/public/test/mock_render_process_host.h"
#include "content/public/test/test_notification_tracker.h"
#include "content/public/test/test_utils.h"
#include "content/test/test_web_contents.h"
#include "net/base/net_util.h"
#include "skia/ext/platform_canvas.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::Time;
namespace {
// Creates an image with a 1x1 SkBitmap of the specified |color|.
gfx::Image CreateImage(SkColor color) {
SkBitmap bitmap;
bitmap.setConfig(SkBitmap::kARGB_8888_Config, 1, 1);
bitmap.allocPixels();
bitmap.eraseColor(color);
return gfx::Image::CreateFrom1xBitmap(bitmap);
}
// Returns true if images |a| and |b| have the same pixel data.
bool DoImagesMatch(const gfx::Image& a, const gfx::Image& b) {
// Assume that if the 1x bitmaps match, the images match.
SkBitmap a_bitmap = a.AsBitmap();
SkBitmap b_bitmap = b.AsBitmap();
if (a_bitmap.width() != b_bitmap.width() ||
a_bitmap.height() != b_bitmap.height()) {
return false;
}
SkAutoLockPixels a_bitmap_lock(a_bitmap);
SkAutoLockPixels b_bitmap_lock(b_bitmap);
return memcmp(a_bitmap.getPixels(),
b_bitmap.getPixels(),
a_bitmap.getSize()) == 0;
}
class MockScreenshotManager : public content::WebContentsScreenshotManager {
public:
explicit MockScreenshotManager(content::NavigationControllerImpl* owner)
: content::WebContentsScreenshotManager(owner),
encoding_screenshot_in_progress_(false) {
}
virtual ~MockScreenshotManager() {
}
void TakeScreenshotFor(content::NavigationEntryImpl* entry) {
SkBitmap bitmap;
bitmap.setConfig(SkBitmap::kARGB_8888_Config, 1, 1);
bitmap.allocPixels();
bitmap.eraseRGB(0, 0, 0);
encoding_screenshot_in_progress_ = true;
OnScreenshotTaken(entry->GetUniqueID(), true, bitmap);
WaitUntilScreenshotIsReady();
}
int GetScreenshotCount() {
return content::WebContentsScreenshotManager::GetScreenshotCount();
}
void WaitUntilScreenshotIsReady() {
if (!encoding_screenshot_in_progress_)
return;
message_loop_runner_ = new content::MessageLoopRunner;
message_loop_runner_->Run();
}
private:
// Overridden from content::WebContentsScreenshotManager:
virtual void TakeScreenshotImpl(
content::RenderViewHost* host,
content::NavigationEntryImpl* entry) OVERRIDE {
}
virtual void OnScreenshotSet(content::NavigationEntryImpl* entry) OVERRIDE {
encoding_screenshot_in_progress_ = false;
WebContentsScreenshotManager::OnScreenshotSet(entry);
if (message_loop_runner_.get())
message_loop_runner_->Quit();
}
scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
bool encoding_screenshot_in_progress_;
DISALLOW_COPY_AND_ASSIGN(MockScreenshotManager);
};
} // namespace
namespace content {
// TimeSmoother tests ----------------------------------------------------------
// With no duplicates, GetSmoothedTime should be the identity
// function.
TEST(TimeSmoother, Basic) {
NavigationControllerImpl::TimeSmoother smoother;
for (int64 i = 1; i < 1000; ++i) {
base::Time t = base::Time::FromInternalValue(i);
EXPECT_EQ(t, smoother.GetSmoothedTime(t));
}
}
// With a single duplicate and timestamps thereafter increasing by one
// microsecond, the smoothed time should always be one behind.
TEST(TimeSmoother, SingleDuplicate) {
NavigationControllerImpl::TimeSmoother smoother;
base::Time t = base::Time::FromInternalValue(1);
EXPECT_EQ(t, smoother.GetSmoothedTime(t));
for (int64 i = 1; i < 1000; ++i) {
base::Time expected_t = base::Time::FromInternalValue(i + 1);
t = base::Time::FromInternalValue(i);
EXPECT_EQ(expected_t, smoother.GetSmoothedTime(t));
}
}
// With k duplicates and timestamps thereafter increasing by one
// microsecond, the smoothed time should always be k behind.
TEST(TimeSmoother, ManyDuplicates) {
const int64 kNumDuplicates = 100;
NavigationControllerImpl::TimeSmoother smoother;
base::Time t = base::Time::FromInternalValue(1);
for (int64 i = 0; i < kNumDuplicates; ++i) {
base::Time expected_t = base::Time::FromInternalValue(i + 1);
EXPECT_EQ(expected_t, smoother.GetSmoothedTime(t));
}
for (int64 i = 1; i < 1000; ++i) {
base::Time expected_t =
base::Time::FromInternalValue(i + kNumDuplicates);
t = base::Time::FromInternalValue(i);
EXPECT_EQ(expected_t, smoother.GetSmoothedTime(t));
}
}
// If the clock jumps far back enough after a run of duplicates, it
// should immediately jump to that value.
TEST(TimeSmoother, ClockBackwardsJump) {
const int64 kNumDuplicates = 100;
NavigationControllerImpl::TimeSmoother smoother;
base::Time t = base::Time::FromInternalValue(1000);
for (int64 i = 0; i < kNumDuplicates; ++i) {
base::Time expected_t = base::Time::FromInternalValue(i + 1000);
EXPECT_EQ(expected_t, smoother.GetSmoothedTime(t));
}
t = base::Time::FromInternalValue(500);
EXPECT_EQ(t, smoother.GetSmoothedTime(t));
}
// NavigationControllerTest ----------------------------------------------------
class NavigationControllerTest
: public RenderViewHostImplTestHarness,
public WebContentsObserver {
public:
NavigationControllerTest() : navigation_entry_committed_counter_(0) {
}
virtual void SetUp() OVERRIDE {
RenderViewHostImplTestHarness::SetUp();
WebContents* web_contents = RenderViewHostImplTestHarness::web_contents();
ASSERT_TRUE(web_contents); // The WebContents should be created by now.
WebContentsObserver::Observe(web_contents);
}
// WebContentsObserver:
virtual void NavigationEntryCommitted(
const LoadCommittedDetails& load_details) OVERRIDE {
navigation_entry_committed_counter_++;
}
NavigationControllerImpl& controller_impl() {
return static_cast<NavigationControllerImpl&>(controller());
}
protected:
size_t navigation_entry_committed_counter_;
};
void RegisterForAllNavNotifications(TestNotificationTracker* tracker,
NavigationController* controller) {
tracker->ListenFor(NOTIFICATION_NAV_LIST_PRUNED,
Source<NavigationController>(controller));
tracker->ListenFor(NOTIFICATION_NAV_ENTRY_CHANGED,
Source<NavigationController>(controller));
}
SiteInstance* GetSiteInstanceFromEntry(NavigationEntry* entry) {
return NavigationEntryImpl::FromNavigationEntry(entry)->site_instance();
}
class TestWebContentsDelegate : public WebContentsDelegate {
public:
explicit TestWebContentsDelegate() :
navigation_state_change_count_(0) {}
int navigation_state_change_count() {
return navigation_state_change_count_;
}
// Keep track of whether the tab has notified us of a navigation state change.
virtual void NavigationStateChanged(const WebContents* source,
unsigned changed_flags) OVERRIDE {
navigation_state_change_count_++;
}
private:
// The number of times NavigationStateChanged has been called.
int navigation_state_change_count_;
};
// -----------------------------------------------------------------------------
TEST_F(NavigationControllerTest, Defaults) {
NavigationControllerImpl& controller = controller_impl();
EXPECT_FALSE(controller.GetPendingEntry());
EXPECT_FALSE(controller.GetActiveEntry());
EXPECT_FALSE(controller.GetVisibleEntry());
EXPECT_FALSE(controller.GetLastCommittedEntry());
EXPECT_EQ(controller.GetPendingEntryIndex(), -1);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), -1);
EXPECT_EQ(controller.GetEntryCount(), 0);
EXPECT_FALSE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoForward());
}
TEST_F(NavigationControllerTest, GoToOffset) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
const int kNumUrls = 5;
std::vector<GURL> urls(kNumUrls);
for (int i = 0; i < kNumUrls; ++i) {
urls[i] = GURL(base::StringPrintf("http://www.a.com/%d", i));
}
test_rvh()->SendNavigate(0, urls[0]);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_EQ(urls[0], controller.GetActiveEntry()->GetVirtualURL());
EXPECT_FALSE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoForward());
EXPECT_FALSE(controller.CanGoToOffset(1));
for (int i = 1; i <= 4; ++i) {
test_rvh()->SendNavigate(i, urls[i]);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_EQ(urls[i], controller.GetActiveEntry()->GetVirtualURL());
EXPECT_TRUE(controller.CanGoToOffset(-i));
EXPECT_FALSE(controller.CanGoToOffset(-(i + 1)));
EXPECT_FALSE(controller.CanGoToOffset(1));
}
// We have loaded 5 pages, and are currently at the last-loaded page.
int url_index = 4;
enum Tests {
GO_TO_MIDDLE_PAGE = -2,
GO_FORWARDS = 1,
GO_BACKWARDS = -1,
GO_TO_BEGINNING = -2,
GO_TO_END = 4,
NUM_TESTS = 5,
};
const int test_offsets[NUM_TESTS] = {
GO_TO_MIDDLE_PAGE,
GO_FORWARDS,
GO_BACKWARDS,
GO_TO_BEGINNING,
GO_TO_END
};
for (int test = 0; test < NUM_TESTS; ++test) {
int offset = test_offsets[test];
controller.GoToOffset(offset);
url_index += offset;
// Check that the GoToOffset will land on the expected page.
EXPECT_EQ(urls[url_index], controller.GetPendingEntry()->GetVirtualURL());
test_rvh()->SendNavigate(url_index, urls[url_index]);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// Check that we can go to any valid offset into the history.
for (size_t j = 0; j < urls.size(); ++j)
EXPECT_TRUE(controller.CanGoToOffset(j - url_index));
// Check that we can't go beyond the beginning or end of the history.
EXPECT_FALSE(controller.CanGoToOffset(-(url_index + 1)));
EXPECT_FALSE(controller.CanGoToOffset(urls.size() - url_index));
}
}
TEST_F(NavigationControllerTest, LoadURL) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
const GURL url1("http://foo1");
const GURL url2("http://foo2");
controller.LoadURL(url1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
// Creating a pending notification should not have issued any of the
// notifications we're listening for.
EXPECT_EQ(0U, notifications.size());
// The load should now be pending.
EXPECT_EQ(controller.GetEntryCount(), 0);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), -1);
EXPECT_EQ(controller.GetPendingEntryIndex(), -1);
EXPECT_FALSE(controller.GetLastCommittedEntry());
ASSERT_TRUE(controller.GetPendingEntry());
EXPECT_EQ(controller.GetPendingEntry(), controller.GetActiveEntry());
EXPECT_EQ(controller.GetPendingEntry(), controller.GetVisibleEntry());
EXPECT_FALSE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoForward());
EXPECT_EQ(contents()->GetMaxPageID(), -1);
// Neither the timestamp nor the status code should have been set yet.
EXPECT_TRUE(controller.GetPendingEntry()->GetTimestamp().is_null());
EXPECT_EQ(0, controller.GetPendingEntry()->GetHttpStatusCode());
// We should have gotten no notifications from the preceeding checks.
EXPECT_EQ(0U, notifications.size());
test_rvh()->SendNavigate(0, url1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// The load should now be committed.
EXPECT_EQ(controller.GetEntryCount(), 1);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 0);
EXPECT_EQ(controller.GetPendingEntryIndex(), -1);
EXPECT_TRUE(controller.GetLastCommittedEntry());
EXPECT_FALSE(controller.GetPendingEntry());
ASSERT_TRUE(controller.GetActiveEntry());
EXPECT_EQ(controller.GetActiveEntry(), controller.GetVisibleEntry());
EXPECT_FALSE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoForward());
EXPECT_EQ(contents()->GetMaxPageID(), 0);
EXPECT_EQ(0, NavigationEntryImpl::FromNavigationEntry(
controller.GetLastCommittedEntry())->bindings());
// The timestamp should have been set.
EXPECT_FALSE(controller.GetActiveEntry()->GetTimestamp().is_null());
// Load another...
controller.LoadURL(url2, Referrer(), PAGE_TRANSITION_TYPED, std::string());
// The load should now be pending.
EXPECT_EQ(controller.GetEntryCount(), 1);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 0);
EXPECT_EQ(controller.GetPendingEntryIndex(), -1);
EXPECT_TRUE(controller.GetLastCommittedEntry());
ASSERT_TRUE(controller.GetPendingEntry());
EXPECT_EQ(controller.GetPendingEntry(), controller.GetActiveEntry());
EXPECT_EQ(controller.GetPendingEntry(), controller.GetVisibleEntry());
// TODO(darin): maybe this should really be true?
EXPECT_FALSE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoForward());
EXPECT_EQ(contents()->GetMaxPageID(), 0);
EXPECT_TRUE(controller.GetPendingEntry()->GetTimestamp().is_null());
// Simulate the beforeunload ack for the cross-site transition, and then the
// commit.
test_rvh()->SendShouldCloseACK(true);
static_cast<TestRenderViewHost*>(
contents()->GetPendingRenderViewHost())->SendNavigate(1, url2);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// The load should now be committed.
EXPECT_EQ(controller.GetEntryCount(), 2);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 1);
EXPECT_EQ(controller.GetPendingEntryIndex(), -1);
EXPECT_TRUE(controller.GetLastCommittedEntry());
EXPECT_FALSE(controller.GetPendingEntry());
ASSERT_TRUE(controller.GetActiveEntry());
EXPECT_EQ(controller.GetActiveEntry(), controller.GetVisibleEntry());
EXPECT_TRUE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoForward());
EXPECT_EQ(contents()->GetMaxPageID(), 1);
EXPECT_FALSE(controller.GetActiveEntry()->GetTimestamp().is_null());
}
namespace {
base::Time GetFixedTime(base::Time time) {
return time;
}
} // namespace
TEST_F(NavigationControllerTest, LoadURLSameTime) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
// Set the clock to always return a timestamp of 1.
controller.SetGetTimestampCallbackForTest(
base::Bind(&GetFixedTime, base::Time::FromInternalValue(1)));
const GURL url1("http://foo1");
const GURL url2("http://foo2");
controller.LoadURL(url1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(0, url1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// Load another...
controller.LoadURL(url2, Referrer(), PAGE_TRANSITION_TYPED, std::string());
// Simulate the beforeunload ack for the cross-site transition, and then the
// commit.
test_rvh()->SendShouldCloseACK(true);
test_rvh()->SendNavigate(1, url2);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// The two loads should now be committed.
ASSERT_EQ(controller.GetEntryCount(), 2);
// Timestamps should be distinct despite the clock returning the
// same value.
EXPECT_EQ(1u,
controller.GetEntryAtIndex(0)->GetTimestamp().ToInternalValue());
EXPECT_EQ(2u,
controller.GetEntryAtIndex(1)->GetTimestamp().ToInternalValue());
}
void CheckNavigationEntryMatchLoadParams(
NavigationController::LoadURLParams& load_params,
NavigationEntryImpl* entry) {
EXPECT_EQ(load_params.url, entry->GetURL());
EXPECT_EQ(load_params.referrer.url, entry->GetReferrer().url);
EXPECT_EQ(load_params.referrer.policy, entry->GetReferrer().policy);
EXPECT_EQ(load_params.transition_type, entry->GetTransitionType());
EXPECT_EQ(load_params.extra_headers, entry->extra_headers());
EXPECT_EQ(load_params.is_renderer_initiated, entry->is_renderer_initiated());
EXPECT_EQ(load_params.base_url_for_data_url, entry->GetBaseURLForDataURL());
if (!load_params.virtual_url_for_data_url.is_empty()) {
EXPECT_EQ(load_params.virtual_url_for_data_url, entry->GetVirtualURL());
}
if (NavigationController::UA_OVERRIDE_INHERIT !=
load_params.override_user_agent) {
bool should_override = (NavigationController::UA_OVERRIDE_TRUE ==
load_params.override_user_agent);
EXPECT_EQ(should_override, entry->GetIsOverridingUserAgent());
}
EXPECT_EQ(load_params.browser_initiated_post_data,
entry->GetBrowserInitiatedPostData());
EXPECT_EQ(load_params.transferred_global_request_id,
entry->transferred_global_request_id());
}
TEST_F(NavigationControllerTest, LoadURLWithParams) {
NavigationControllerImpl& controller = controller_impl();
NavigationController::LoadURLParams load_params(GURL("http://foo"));
load_params.referrer =
Referrer(GURL("http://referrer"), WebKit::WebReferrerPolicyDefault);
load_params.transition_type = PAGE_TRANSITION_GENERATED;
load_params.extra_headers = "content-type: text/plain";
load_params.load_type = NavigationController::LOAD_TYPE_DEFAULT;
load_params.is_renderer_initiated = true;
load_params.override_user_agent = NavigationController::UA_OVERRIDE_TRUE;
load_params.transferred_global_request_id = GlobalRequestID(2, 3);
controller.LoadURLWithParams(load_params);
NavigationEntryImpl* entry =
NavigationEntryImpl::FromNavigationEntry(
controller.GetPendingEntry());
// The timestamp should not have been set yet.
ASSERT_TRUE(entry);
EXPECT_TRUE(entry->GetTimestamp().is_null());
CheckNavigationEntryMatchLoadParams(load_params, entry);
}
TEST_F(NavigationControllerTest, LoadURLWithExtraParams_Data) {
NavigationControllerImpl& controller = controller_impl();
NavigationController::LoadURLParams load_params(
GURL("data:text/html,dataurl"));
load_params.load_type = NavigationController::LOAD_TYPE_DATA;
load_params.base_url_for_data_url = GURL("http://foo");
load_params.virtual_url_for_data_url = GURL(kAboutBlankURL);
load_params.override_user_agent = NavigationController::UA_OVERRIDE_FALSE;
controller.LoadURLWithParams(load_params);
NavigationEntryImpl* entry =
NavigationEntryImpl::FromNavigationEntry(
controller.GetPendingEntry());
CheckNavigationEntryMatchLoadParams(load_params, entry);
}
TEST_F(NavigationControllerTest, LoadURLWithExtraParams_HttpPost) {
NavigationControllerImpl& controller = controller_impl();
NavigationController::LoadURLParams load_params(GURL("https://posturl"));
load_params.transition_type = PAGE_TRANSITION_TYPED;
load_params.load_type =
NavigationController::LOAD_TYPE_BROWSER_INITIATED_HTTP_POST;
load_params.override_user_agent = NavigationController::UA_OVERRIDE_TRUE;
const unsigned char* raw_data =
reinterpret_cast<const unsigned char*>("d\n\0a2");
const int length = 5;
std::vector<unsigned char> post_data_vector(raw_data, raw_data+length);
scoped_refptr<base::RefCountedBytes> data =
base::RefCountedBytes::TakeVector(&post_data_vector);
load_params.browser_initiated_post_data = data.get();
controller.LoadURLWithParams(load_params);
NavigationEntryImpl* entry =
NavigationEntryImpl::FromNavigationEntry(
controller.GetPendingEntry());
CheckNavigationEntryMatchLoadParams(load_params, entry);
}
// Tests what happens when the same page is loaded again. Should not create a
// new session history entry. This is what happens when you press enter in the
// URL bar to reload: a pending entry is created and then it is discarded when
// the load commits (because WebCore didn't actually make a new entry).
TEST_F(NavigationControllerTest, LoadURL_SamePage) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
const GURL url1("http://foo1");
controller.LoadURL(url1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
EXPECT_EQ(0U, notifications.size());
test_rvh()->SendNavigate(0, url1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
ASSERT_TRUE(controller.GetActiveEntry());
const base::Time timestamp = controller.GetActiveEntry()->GetTimestamp();
EXPECT_FALSE(timestamp.is_null());
controller.LoadURL(url1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
EXPECT_EQ(0U, notifications.size());
test_rvh()->SendNavigate(0, url1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// We should not have produced a new session history entry.
EXPECT_EQ(controller.GetEntryCount(), 1);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 0);
EXPECT_EQ(controller.GetPendingEntryIndex(), -1);
EXPECT_TRUE(controller.GetLastCommittedEntry());
EXPECT_FALSE(controller.GetPendingEntry());
ASSERT_TRUE(controller.GetActiveEntry());
EXPECT_FALSE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoForward());
// The timestamp should have been updated.
//
// TODO(akalin): Change this EXPECT_GE (and other similar ones) to
// EXPECT_GT once we guarantee that timestamps are unique.
EXPECT_GE(controller.GetActiveEntry()->GetTimestamp(), timestamp);
}
// Tests loading a URL but discarding it before the load commits.
TEST_F(NavigationControllerTest, LoadURL_Discarded) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
const GURL url1("http://foo1");
const GURL url2("http://foo2");
controller.LoadURL(url1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
EXPECT_EQ(0U, notifications.size());
test_rvh()->SendNavigate(0, url1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
ASSERT_TRUE(controller.GetActiveEntry());
const base::Time timestamp = controller.GetActiveEntry()->GetTimestamp();
EXPECT_FALSE(timestamp.is_null());
controller.LoadURL(url2, Referrer(), PAGE_TRANSITION_TYPED, std::string());
controller.DiscardNonCommittedEntries();
EXPECT_EQ(0U, notifications.size());
// Should not have produced a new session history entry.
EXPECT_EQ(controller.GetEntryCount(), 1);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 0);
EXPECT_EQ(controller.GetPendingEntryIndex(), -1);
EXPECT_TRUE(controller.GetLastCommittedEntry());
EXPECT_FALSE(controller.GetPendingEntry());
ASSERT_TRUE(controller.GetActiveEntry());
EXPECT_FALSE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoForward());
// Timestamp should not have changed.
EXPECT_EQ(timestamp, controller.GetActiveEntry()->GetTimestamp());
}
// Tests navigations that come in unrequested. This happens when the user
// navigates from the web page, and here we test that there is no pending entry.
TEST_F(NavigationControllerTest, LoadURL_NoPending) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
// First make an existing committed entry.
const GURL kExistingURL1("http://eh");
controller.LoadURL(
kExistingURL1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(0, kExistingURL1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// Do a new navigation without making a pending one.
const GURL kNewURL("http://see");
test_rvh()->SendNavigate(99, kNewURL);
// There should no longer be any pending entry, and the third navigation we
// just made should be committed.
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
EXPECT_EQ(1, controller.GetLastCommittedEntryIndex());
EXPECT_EQ(kNewURL, controller.GetActiveEntry()->GetURL());
}
// Tests navigating to a new URL when there is a new pending navigation that is
// not the one that just loaded. This will happen if the user types in a URL to
// somewhere slow, and then navigates the current page before the typed URL
// commits.
TEST_F(NavigationControllerTest, LoadURL_NewPending) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
// First make an existing committed entry.
const GURL kExistingURL1("http://eh");
controller.LoadURL(
kExistingURL1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(0, kExistingURL1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// Make a pending entry to somewhere new.
const GURL kExistingURL2("http://bee");
controller.LoadURL(
kExistingURL2, Referrer(), PAGE_TRANSITION_TYPED, std::string());
EXPECT_EQ(0U, notifications.size());
// After the beforeunload but before it commits, do a new navigation.
test_rvh()->SendShouldCloseACK(true);
const GURL kNewURL("http://see");
static_cast<TestRenderViewHost*>(
contents()->GetPendingRenderViewHost())->SendNavigate(3, kNewURL);
// There should no longer be any pending entry, and the third navigation we
// just made should be committed.
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
EXPECT_EQ(1, controller.GetLastCommittedEntryIndex());
EXPECT_EQ(kNewURL, controller.GetActiveEntry()->GetURL());
}
// Tests navigating to a new URL when there is a pending back/forward
// navigation. This will happen if the user hits back, but before that commits,
// they navigate somewhere new.
TEST_F(NavigationControllerTest, LoadURL_ExistingPending) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
// First make some history.
const GURL kExistingURL1("http://foo/eh");
controller.LoadURL(
kExistingURL1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(0, kExistingURL1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
const GURL kExistingURL2("http://foo/bee");
controller.LoadURL(
kExistingURL2, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(1, kExistingURL2);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// Now make a pending back/forward navigation. The zeroth entry should be
// pending.
controller.GoBack();
EXPECT_EQ(0U, notifications.size());
EXPECT_EQ(0, controller.GetPendingEntryIndex());
EXPECT_EQ(1, controller.GetLastCommittedEntryIndex());
// Before that commits, do a new navigation.
const GURL kNewURL("http://foo/see");
LoadCommittedDetails details;
test_rvh()->SendNavigate(3, kNewURL);
// There should no longer be any pending entry, and the third navigation we
// just made should be committed.
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
EXPECT_EQ(2, controller.GetLastCommittedEntryIndex());
EXPECT_EQ(kNewURL, controller.GetActiveEntry()->GetURL());
}
// Tests navigating to a new URL when there is a pending back/forward
// navigation to a cross-process, privileged URL. This will happen if the user
// hits back, but before that commits, they navigate somewhere new.
TEST_F(NavigationControllerTest, LoadURL_PrivilegedPending) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
// First make some history, starting with a privileged URL.
const GURL kExistingURL1("http://privileged");
controller.LoadURL(
kExistingURL1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
// Pretend it has bindings so we can tell if we incorrectly copy it.
test_rvh()->AllowBindings(2);
test_rvh()->SendNavigate(0, kExistingURL1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// Navigate cross-process to a second URL.
const GURL kExistingURL2("http://foo/eh");
controller.LoadURL(
kExistingURL2, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendShouldCloseACK(true);
TestRenderViewHost* foo_rvh = static_cast<TestRenderViewHost*>(
contents()->GetPendingRenderViewHost());
foo_rvh->SendNavigate(1, kExistingURL2);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// Now make a pending back/forward navigation to a privileged entry.
// The zeroth entry should be pending.
controller.GoBack();
foo_rvh->SendShouldCloseACK(true);
EXPECT_EQ(0U, notifications.size());
EXPECT_EQ(0, controller.GetPendingEntryIndex());
EXPECT_EQ(1, controller.GetLastCommittedEntryIndex());
EXPECT_EQ(2, NavigationEntryImpl::FromNavigationEntry(
controller.GetPendingEntry())->bindings());
// Before that commits, do a new navigation.
const GURL kNewURL("http://foo/bee");
LoadCommittedDetails details;
foo_rvh->SendNavigate(3, kNewURL);
// There should no longer be any pending entry, and the third navigation we
// just made should be committed.
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
EXPECT_EQ(2, controller.GetLastCommittedEntryIndex());
EXPECT_EQ(kNewURL, controller.GetActiveEntry()->GetURL());
EXPECT_EQ(0, NavigationEntryImpl::FromNavigationEntry(
controller.GetLastCommittedEntry())->bindings());
}
// Tests navigating to an existing URL when there is a pending new navigation.
// This will happen if the user enters a URL, but before that commits, the
// current page fires history.back().
TEST_F(NavigationControllerTest, LoadURL_BackPreemptsPending) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
// First make some history.
const GURL kExistingURL1("http://foo/eh");
controller.LoadURL(
kExistingURL1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(0, kExistingURL1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
const GURL kExistingURL2("http://foo/bee");
controller.LoadURL(
kExistingURL2, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(1, kExistingURL2);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// Now make a pending new navigation.
const GURL kNewURL("http://foo/see");
controller.LoadURL(
kNewURL, Referrer(), PAGE_TRANSITION_TYPED, std::string());
EXPECT_EQ(0U, notifications.size());
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
EXPECT_EQ(1, controller.GetLastCommittedEntryIndex());
// Before that commits, a back navigation from the renderer commits.
test_rvh()->SendNavigate(0, kExistingURL1);
// There should no longer be any pending entry, and the back navigation we
// just made should be committed.
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
EXPECT_EQ(0, controller.GetLastCommittedEntryIndex());
EXPECT_EQ(kExistingURL1, controller.GetActiveEntry()->GetURL());
}
// Tests an ignored navigation when there is a pending new navigation.
// This will happen if the user enters a URL, but before that commits, the
// current blank page reloads. See http://crbug.com/77507.
TEST_F(NavigationControllerTest, LoadURL_IgnorePreemptsPending) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
// Set a WebContentsDelegate to listen for state changes.
scoped_ptr<TestWebContentsDelegate> delegate(new TestWebContentsDelegate());
EXPECT_FALSE(contents()->GetDelegate());
contents()->SetDelegate(delegate.get());
// Without any navigations, the renderer starts at about:blank.
const GURL kExistingURL(kAboutBlankURL);
// Now make a pending new navigation.
const GURL kNewURL("http://eh");
controller.LoadURL(
kNewURL, Referrer(), PAGE_TRANSITION_TYPED, std::string());
EXPECT_EQ(0U, notifications.size());
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
EXPECT_TRUE(controller.GetPendingEntry());
EXPECT_EQ(-1, controller.GetLastCommittedEntryIndex());
EXPECT_EQ(1, delegate->navigation_state_change_count());
// Before that commits, a document.write and location.reload can cause the
// renderer to send a FrameNavigate with page_id -1.
test_rvh()->SendNavigate(-1, kExistingURL);
// This should clear the pending entry and notify of a navigation state
// change, so that we do not keep displaying kNewURL.
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
EXPECT_FALSE(controller.GetPendingEntry());
EXPECT_EQ(-1, controller.GetLastCommittedEntryIndex());
EXPECT_EQ(2, delegate->navigation_state_change_count());
contents()->SetDelegate(NULL);
}
// Tests that the pending entry state is correct after an abort.
// We do not want to clear the pending entry, so that the user doesn't
// lose a typed URL. (See http://crbug.com/9682.)
TEST_F(NavigationControllerTest, LoadURL_AbortDoesntCancelPending) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
// Set a WebContentsDelegate to listen for state changes.
scoped_ptr<TestWebContentsDelegate> delegate(new TestWebContentsDelegate());
EXPECT_FALSE(contents()->GetDelegate());
contents()->SetDelegate(delegate.get());
// Start with a pending new navigation.
const GURL kNewURL("http://eh");
controller.LoadURL(
kNewURL, Referrer(), PAGE_TRANSITION_TYPED, std::string());
EXPECT_EQ(0U, notifications.size());
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
EXPECT_TRUE(controller.GetPendingEntry());
EXPECT_EQ(-1, controller.GetLastCommittedEntryIndex());
EXPECT_EQ(1, delegate->navigation_state_change_count());
// It may abort before committing, if it's a download or due to a stop or
// a new navigation from the user.
ViewHostMsg_DidFailProvisionalLoadWithError_Params params;
params.frame_id = 1;
params.is_main_frame = true;
params.error_code = net::ERR_ABORTED;
params.error_description = string16();
params.url = kNewURL;
params.showing_repost_interstitial = false;
test_rvh()->OnMessageReceived(
ViewHostMsg_DidFailProvisionalLoadWithError(0, // routing_id
params));
// This should not clear the pending entry or notify of a navigation state
// change, so that we keep displaying kNewURL (until the user clears it).
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
EXPECT_TRUE(controller.GetPendingEntry());
EXPECT_EQ(-1, controller.GetLastCommittedEntryIndex());
EXPECT_EQ(1, delegate->navigation_state_change_count());
NavigationEntry* pending_entry = controller.GetPendingEntry();
// Ensure that a reload keeps the same pending entry.
controller.Reload(true);
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
EXPECT_TRUE(controller.GetPendingEntry());
EXPECT_EQ(pending_entry, controller.GetPendingEntry());
EXPECT_EQ(-1, controller.GetLastCommittedEntryIndex());
contents()->SetDelegate(NULL);
}
// Tests that the pending URL is not visible during a renderer-initiated
// redirect and abort. See http://crbug.com/83031.
TEST_F(NavigationControllerTest, LoadURL_RedirectAbortDoesntShowPendingURL) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
// First make an existing committed entry.
const GURL kExistingURL("http://foo/eh");
controller.LoadURL(kExistingURL, content::Referrer(),
content::PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(0, kExistingURL);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// Set a WebContentsDelegate to listen for state changes.
scoped_ptr<TestWebContentsDelegate> delegate(new TestWebContentsDelegate());
EXPECT_FALSE(contents()->GetDelegate());
contents()->SetDelegate(delegate.get());
// Now make a pending new navigation, initiated by the renderer.
const GURL kNewURL("http://foo/bee");
NavigationController::LoadURLParams load_url_params(kNewURL);
load_url_params.transition_type = PAGE_TRANSITION_TYPED;
load_url_params.is_renderer_initiated = true;
controller.LoadURLWithParams(load_url_params);
EXPECT_EQ(0U, notifications.size());
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
EXPECT_TRUE(controller.GetPendingEntry());
EXPECT_EQ(0, controller.GetLastCommittedEntryIndex());
EXPECT_EQ(0, delegate->navigation_state_change_count());
// The visible entry should be the last committed URL, not the pending one.
EXPECT_EQ(kExistingURL, controller.GetVisibleEntry()->GetURL());
// Now the navigation redirects.
const GURL kRedirectURL("http://foo/see");
test_rvh()->OnMessageReceived(
ViewHostMsg_DidRedirectProvisionalLoad(0, // routing_id
-1, // pending page_id
kNewURL, // old url
kRedirectURL)); // new url
// We don't want to change the NavigationEntry's url, in case it cancels.
// Prevents regression of http://crbug.com/77786.
EXPECT_EQ(kNewURL, controller.GetPendingEntry()->GetURL());
// It may abort before committing, if it's a download or due to a stop or
// a new navigation from the user.
ViewHostMsg_DidFailProvisionalLoadWithError_Params params;
params.frame_id = 1;
params.is_main_frame = true;
params.error_code = net::ERR_ABORTED;
params.error_description = string16();
params.url = kRedirectURL;
params.showing_repost_interstitial = false;
test_rvh()->OnMessageReceived(
ViewHostMsg_DidFailProvisionalLoadWithError(0, // routing_id
params));
// Because the pending entry is renderer initiated and not visible, we
// clear it when it fails.
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
EXPECT_FALSE(controller.GetPendingEntry());
EXPECT_EQ(0, controller.GetLastCommittedEntryIndex());
EXPECT_EQ(0, delegate->navigation_state_change_count());
// The visible entry should be the last committed URL, not the pending one,
// so that no spoof is possible.
EXPECT_EQ(kExistingURL, controller.GetVisibleEntry()->GetURL());
contents()->SetDelegate(NULL);
}
// Ensure that NavigationEntries track which bindings their RenderViewHost had
// at the time they committed. http://crbug.com/173672.
TEST_F(NavigationControllerTest, LoadURL_WithBindings) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
const GURL url1("http://foo1");
const GURL url2("http://foo2");
// Navigate to a first, unprivileged URL.
controller.LoadURL(url1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
EXPECT_EQ(NavigationEntryImpl::kInvalidBindings,
NavigationEntryImpl::FromNavigationEntry(
controller.GetPendingEntry())->bindings());
// Commit.
TestRenderViewHost* orig_rvh = static_cast<TestRenderViewHost*>(test_rvh());
orig_rvh->SendNavigate(0, url1);
EXPECT_EQ(controller.GetEntryCount(), 1);
EXPECT_EQ(0, controller.GetLastCommittedEntryIndex());
EXPECT_EQ(0, NavigationEntryImpl::FromNavigationEntry(
controller.GetLastCommittedEntry())->bindings());
// Manually increase the number of active views in the SiteInstance
// that orig_rvh belongs to, to prevent it from being destroyed when
// it gets swapped out, so that we can reuse orig_rvh when the
// controller goes back.
static_cast<SiteInstanceImpl*>(orig_rvh->GetSiteInstance())->
increment_active_view_count();
// Navigate to a second URL, simulate the beforeunload ack for the cross-site
// transition, and set bindings on the pending RenderViewHost to simulate a
// privileged url.
controller.LoadURL(url2, Referrer(), PAGE_TRANSITION_TYPED, std::string());
orig_rvh->SendShouldCloseACK(true);
contents()->GetPendingRenderViewHost()->AllowBindings(1);
static_cast<TestRenderViewHost*>(
contents()->GetPendingRenderViewHost())->SendNavigate(1, url2);
// The second load should be committed, and bindings should be remembered.
EXPECT_EQ(controller.GetEntryCount(), 2);
EXPECT_EQ(1, controller.GetLastCommittedEntryIndex());
EXPECT_TRUE(controller.CanGoBack());
EXPECT_EQ(1, NavigationEntryImpl::FromNavigationEntry(
controller.GetLastCommittedEntry())->bindings());
// Going back, the first entry should still appear unprivileged.
controller.GoBack();
orig_rvh->SendNavigate(0, url1);
EXPECT_EQ(0, controller.GetLastCommittedEntryIndex());
EXPECT_EQ(0, NavigationEntryImpl::FromNavigationEntry(
controller.GetLastCommittedEntry())->bindings());
}
TEST_F(NavigationControllerTest, Reload) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
const GURL url1("http://foo1");
controller.LoadURL(url1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
EXPECT_EQ(0U, notifications.size());
test_rvh()->SendNavigate(0, url1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
ASSERT_TRUE(controller.GetActiveEntry());
controller.GetActiveEntry()->SetTitle(ASCIIToUTF16("Title"));
controller.Reload(true);
EXPECT_EQ(0U, notifications.size());
const base::Time timestamp = controller.GetActiveEntry()->GetTimestamp();
EXPECT_FALSE(timestamp.is_null());
// The reload is pending.
EXPECT_EQ(controller.GetEntryCount(), 1);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 0);
EXPECT_EQ(controller.GetPendingEntryIndex(), 0);
EXPECT_TRUE(controller.GetLastCommittedEntry());
EXPECT_TRUE(controller.GetPendingEntry());
EXPECT_FALSE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoForward());
// Make sure the title has been cleared (will be redrawn just after reload).
// Avoids a stale cached title when the new page being reloaded has no title.
// See http://crbug.com/96041.
EXPECT_TRUE(controller.GetActiveEntry()->GetTitle().empty());
test_rvh()->SendNavigate(0, url1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// Now the reload is committed.
EXPECT_EQ(controller.GetEntryCount(), 1);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 0);
EXPECT_EQ(controller.GetPendingEntryIndex(), -1);
EXPECT_TRUE(controller.GetLastCommittedEntry());
EXPECT_FALSE(controller.GetPendingEntry());
EXPECT_FALSE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoForward());
// The timestamp should have been updated.
ASSERT_TRUE(controller.GetActiveEntry());
EXPECT_GE(controller.GetActiveEntry()->GetTimestamp(), timestamp);
}
// Tests what happens when a reload navigation produces a new page.
TEST_F(NavigationControllerTest, Reload_GeneratesNewPage) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
const GURL url1("http://foo1");
const GURL url2("http://foo2");
controller.LoadURL(url1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(0, url1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
controller.Reload(true);
EXPECT_EQ(0U, notifications.size());
test_rvh()->SendNavigate(1, url2);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// Now the reload is committed.
EXPECT_EQ(controller.GetEntryCount(), 2);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 1);
EXPECT_EQ(controller.GetPendingEntryIndex(), -1);
EXPECT_TRUE(controller.GetLastCommittedEntry());
EXPECT_FALSE(controller.GetPendingEntry());
EXPECT_TRUE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoForward());
}
class TestNavigationObserver : public RenderViewHostObserver {
public:
explicit TestNavigationObserver(RenderViewHost* render_view_host)
: RenderViewHostObserver(render_view_host) {
}
const GURL& navigated_url() const {
return navigated_url_;
}
protected:
virtual void Navigate(const GURL& url) OVERRIDE {
navigated_url_ = url;
}
private:
GURL navigated_url_;
};
#if !defined(OS_ANDROID) // http://crbug.com/157428
TEST_F(NavigationControllerTest, ReloadOriginalRequestURL) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
TestNavigationObserver observer(test_rvh());
const GURL original_url("http://foo1");
const GURL final_url("http://foo2");
// Load up the original URL, but get redirected.
controller.LoadURL(
original_url, Referrer(), PAGE_TRANSITION_TYPED, std::string());
EXPECT_EQ(0U, notifications.size());
test_rvh()->SendNavigateWithOriginalRequestURL(0, final_url, original_url);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// The NavigationEntry should save both the original URL and the final
// redirected URL.
EXPECT_EQ(original_url, controller.GetActiveEntry()->GetOriginalRequestURL());
EXPECT_EQ(final_url, controller.GetActiveEntry()->GetURL());
// Reload using the original URL.
controller.GetActiveEntry()->SetTitle(ASCIIToUTF16("Title"));
controller.ReloadOriginalRequestURL(false);
EXPECT_EQ(0U, notifications.size());
// The reload is pending. The request should point to the original URL.
EXPECT_EQ(original_url, observer.navigated_url());
EXPECT_EQ(controller.GetEntryCount(), 1);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 0);
EXPECT_EQ(controller.GetPendingEntryIndex(), 0);
EXPECT_TRUE(controller.GetLastCommittedEntry());
EXPECT_TRUE(controller.GetPendingEntry());
EXPECT_FALSE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoForward());
// Make sure the title has been cleared (will be redrawn just after reload).
// Avoids a stale cached title when the new page being reloaded has no title.
// See http://crbug.com/96041.
EXPECT_TRUE(controller.GetActiveEntry()->GetTitle().empty());
// Send that the navigation has proceeded; say it got redirected again.
test_rvh()->SendNavigate(0, final_url);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// Now the reload is committed.
EXPECT_EQ(controller.GetEntryCount(), 1);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 0);
EXPECT_EQ(controller.GetPendingEntryIndex(), -1);
EXPECT_TRUE(controller.GetLastCommittedEntry());
EXPECT_FALSE(controller.GetPendingEntry());
EXPECT_FALSE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoForward());
}
#endif // !defined(OS_ANDROID)
// Tests what happens when we navigate back successfully
TEST_F(NavigationControllerTest, Back) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
const GURL url1("http://foo1");
test_rvh()->SendNavigate(0, url1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
const GURL url2("http://foo2");
test_rvh()->SendNavigate(1, url2);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
controller.GoBack();
EXPECT_EQ(0U, notifications.size());
// We should now have a pending navigation to go back.
EXPECT_EQ(controller.GetEntryCount(), 2);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 1);
EXPECT_EQ(controller.GetPendingEntryIndex(), 0);
EXPECT_TRUE(controller.GetLastCommittedEntry());
EXPECT_TRUE(controller.GetPendingEntry());
EXPECT_FALSE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoToOffset(-1));
EXPECT_TRUE(controller.CanGoForward());
EXPECT_TRUE(controller.CanGoToOffset(1));
EXPECT_FALSE(controller.CanGoToOffset(2)); // Cannot go foward 2 steps.
// Timestamp for entry 1 should be on or after that of entry 0.
EXPECT_FALSE(controller.GetEntryAtIndex(0)->GetTimestamp().is_null());
EXPECT_GE(controller.GetEntryAtIndex(1)->GetTimestamp(),
controller.GetEntryAtIndex(0)->GetTimestamp());
test_rvh()->SendNavigate(0, url2);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// The back navigation completed successfully.
EXPECT_EQ(controller.GetEntryCount(), 2);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 0);
EXPECT_EQ(controller.GetPendingEntryIndex(), -1);
EXPECT_TRUE(controller.GetLastCommittedEntry());
EXPECT_FALSE(controller.GetPendingEntry());
EXPECT_FALSE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoToOffset(-1));
EXPECT_TRUE(controller.CanGoForward());
EXPECT_TRUE(controller.CanGoToOffset(1));
EXPECT_FALSE(controller.CanGoToOffset(2)); // Cannot go foward 2 steps.
// Timestamp for entry 0 should be on or after that of entry 1
// (since we went back to it).
EXPECT_GE(controller.GetEntryAtIndex(0)->GetTimestamp(),
controller.GetEntryAtIndex(1)->GetTimestamp());
}
// Tests what happens when a back navigation produces a new page.
TEST_F(NavigationControllerTest, Back_GeneratesNewPage) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
const GURL url1("http://foo/1");
const GURL url2("http://foo/2");
const GURL url3("http://foo/3");
controller.LoadURL(
url1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(0, url1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
controller.LoadURL(url2, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(1, url2);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
controller.GoBack();
EXPECT_EQ(0U, notifications.size());
// We should now have a pending navigation to go back.
EXPECT_EQ(controller.GetEntryCount(), 2);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 1);
EXPECT_EQ(controller.GetPendingEntryIndex(), 0);
EXPECT_TRUE(controller.GetLastCommittedEntry());
EXPECT_TRUE(controller.GetPendingEntry());
EXPECT_FALSE(controller.CanGoBack());
EXPECT_TRUE(controller.CanGoForward());
test_rvh()->SendNavigate(2, url3);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// The back navigation resulted in a completely new navigation.
// TODO(darin): perhaps this behavior will be confusing to users?
EXPECT_EQ(controller.GetEntryCount(), 3);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 2);
EXPECT_EQ(controller.GetPendingEntryIndex(), -1);
EXPECT_TRUE(controller.GetLastCommittedEntry());
EXPECT_FALSE(controller.GetPendingEntry());
EXPECT_TRUE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoForward());
}
// Receives a back message when there is a new pending navigation entry.
TEST_F(NavigationControllerTest, Back_NewPending) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
const GURL kUrl1("http://foo1");
const GURL kUrl2("http://foo2");
const GURL kUrl3("http://foo3");
// First navigate two places so we have some back history.
test_rvh()->SendNavigate(0, kUrl1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// controller.LoadURL(kUrl2, PAGE_TRANSITION_TYPED);
test_rvh()->SendNavigate(1, kUrl2);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// Now start a new pending navigation and go back before it commits.
controller.LoadURL(kUrl3, Referrer(), PAGE_TRANSITION_TYPED, std::string());
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
EXPECT_EQ(kUrl3, controller.GetPendingEntry()->GetURL());
controller.GoBack();
// The pending navigation should now be the "back" item and the new one
// should be gone.
EXPECT_EQ(0, controller.GetPendingEntryIndex());
EXPECT_EQ(kUrl1, controller.GetPendingEntry()->GetURL());
}
// Receives a back message when there is a different renavigation already
// pending.
TEST_F(NavigationControllerTest, Back_OtherBackPending) {
NavigationControllerImpl& controller = controller_impl();
const GURL kUrl1("http://foo/1");
const GURL kUrl2("http://foo/2");
const GURL kUrl3("http://foo/3");
// First navigate three places so we have some back history.
test_rvh()->SendNavigate(0, kUrl1);
test_rvh()->SendNavigate(1, kUrl2);
test_rvh()->SendNavigate(2, kUrl3);
// With nothing pending, say we get a navigation to the second entry.
test_rvh()->SendNavigate(1, kUrl2);
// We know all the entries have the same site instance, so we can just grab
// a random one for looking up other entries.
SiteInstance* site_instance =
NavigationEntryImpl::FromNavigationEntry(
controller.GetLastCommittedEntry())->site_instance();
// That second URL should be the last committed and it should have gotten the
// new title.
EXPECT_EQ(kUrl2, controller.GetEntryWithPageID(site_instance, 1)->GetURL());
EXPECT_EQ(1, controller.GetLastCommittedEntryIndex());
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
// Now go forward to the last item again and say it was committed.
controller.GoForward();
test_rvh()->SendNavigate(2, kUrl3);
// Now start going back one to the second page. It will be pending.
controller.GoBack();
EXPECT_EQ(1, controller.GetPendingEntryIndex());
EXPECT_EQ(2, controller.GetLastCommittedEntryIndex());
// Not synthesize a totally new back event to the first page. This will not
// match the pending one.
test_rvh()->SendNavigate(0, kUrl1);
// The committed navigation should clear the pending entry.
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
// But the navigated entry should be the last committed.
EXPECT_EQ(0, controller.GetLastCommittedEntryIndex());
EXPECT_EQ(kUrl1, controller.GetLastCommittedEntry()->GetURL());
}
// Tests what happens when we navigate forward successfully.
TEST_F(NavigationControllerTest, Forward) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
const GURL url1("http://foo1");
const GURL url2("http://foo2");
test_rvh()->SendNavigate(0, url1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
test_rvh()->SendNavigate(1, url2);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
controller.GoBack();
test_rvh()->SendNavigate(0, url1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
controller.GoForward();
// We should now have a pending navigation to go forward.
EXPECT_EQ(controller.GetEntryCount(), 2);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 0);
EXPECT_EQ(controller.GetPendingEntryIndex(), 1);
EXPECT_TRUE(controller.GetLastCommittedEntry());
EXPECT_TRUE(controller.GetPendingEntry());
EXPECT_TRUE(controller.CanGoBack());
EXPECT_TRUE(controller.CanGoToOffset(-1));
EXPECT_FALSE(controller.CanGoToOffset(-2)); // Cannot go back 2 steps.
EXPECT_FALSE(controller.CanGoForward());
EXPECT_FALSE(controller.CanGoToOffset(1));
// Timestamp for entry 0 should be on or after that of entry 1
// (since we went back to it).
EXPECT_FALSE(controller.GetEntryAtIndex(0)->GetTimestamp().is_null());
EXPECT_GE(controller.GetEntryAtIndex(0)->GetTimestamp(),
controller.GetEntryAtIndex(1)->GetTimestamp());
test_rvh()->SendNavigate(1, url2);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// The forward navigation completed successfully.
EXPECT_EQ(controller.GetEntryCount(), 2);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 1);
EXPECT_EQ(controller.GetPendingEntryIndex(), -1);
EXPECT_TRUE(controller.GetLastCommittedEntry());
EXPECT_FALSE(controller.GetPendingEntry());
EXPECT_TRUE(controller.CanGoBack());
EXPECT_TRUE(controller.CanGoToOffset(-1));
EXPECT_FALSE(controller.CanGoToOffset(-2)); // Cannot go back 2 steps.
EXPECT_FALSE(controller.CanGoForward());
EXPECT_FALSE(controller.CanGoToOffset(1));
// Timestamp for entry 1 should be on or after that of entry 0
// (since we went forward to it).
EXPECT_GE(controller.GetEntryAtIndex(1)->GetTimestamp(),
controller.GetEntryAtIndex(0)->GetTimestamp());
}
// Tests what happens when a forward navigation produces a new page.
TEST_F(NavigationControllerTest, Forward_GeneratesNewPage) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
const GURL url1("http://foo1");
const GURL url2("http://foo2");
const GURL url3("http://foo3");
test_rvh()->SendNavigate(0, url1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
test_rvh()->SendNavigate(1, url2);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
controller.GoBack();
test_rvh()->SendNavigate(0, url1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
controller.GoForward();
EXPECT_EQ(0U, notifications.size());
// Should now have a pending navigation to go forward.
EXPECT_EQ(controller.GetEntryCount(), 2);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 0);
EXPECT_EQ(controller.GetPendingEntryIndex(), 1);
EXPECT_TRUE(controller.GetLastCommittedEntry());
EXPECT_TRUE(controller.GetPendingEntry());
EXPECT_TRUE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoForward());
test_rvh()->SendNavigate(2, url3);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_TRUE(notifications.Check1AndReset(NOTIFICATION_NAV_LIST_PRUNED));
EXPECT_EQ(controller.GetEntryCount(), 2);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 1);
EXPECT_EQ(controller.GetPendingEntryIndex(), -1);
EXPECT_TRUE(controller.GetLastCommittedEntry());
EXPECT_FALSE(controller.GetPendingEntry());
EXPECT_TRUE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoForward());
}
// Two consequent navigation for the same URL entered in should be considered
// as SAME_PAGE navigation even when we are redirected to some other page.
TEST_F(NavigationControllerTest, Redirect) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
const GURL url1("http://foo1");
const GURL url2("http://foo2"); // Redirection target
// First request
controller.LoadURL(url1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
EXPECT_EQ(0U, notifications.size());
test_rvh()->SendNavigate(0, url2);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// Second request
controller.LoadURL(url1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
EXPECT_TRUE(controller.GetPendingEntry());
EXPECT_EQ(controller.GetPendingEntryIndex(), -1);
EXPECT_EQ(url1, controller.GetActiveEntry()->GetURL());
ViewHostMsg_FrameNavigate_Params params;
params.page_id = 0;
params.url = url2;
params.transition = PAGE_TRANSITION_SERVER_REDIRECT;
params.redirects.push_back(GURL("http://foo1"));
params.redirects.push_back(GURL("http://foo2"));
params.should_update_history = false;
params.gesture = NavigationGestureAuto;
params.is_post = false;
params.page_state = PageState::CreateFromURL(url2);
LoadCommittedDetails details;
EXPECT_EQ(0U, notifications.size());
EXPECT_TRUE(controller.RendererDidNavigate(params, &details));
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_TRUE(details.type == NAVIGATION_TYPE_SAME_PAGE);
EXPECT_EQ(controller.GetEntryCount(), 1);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 0);
EXPECT_TRUE(controller.GetLastCommittedEntry());
EXPECT_EQ(controller.GetPendingEntryIndex(), -1);
EXPECT_FALSE(controller.GetPendingEntry());
EXPECT_EQ(url2, controller.GetActiveEntry()->GetURL());
EXPECT_FALSE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoForward());
}
// Similar to Redirect above, but the first URL is requested by POST,
// the second URL is requested by GET. NavigationEntry::has_post_data_
// must be cleared. http://crbug.com/21245
TEST_F(NavigationControllerTest, PostThenRedirect) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
const GURL url1("http://foo1");
const GURL url2("http://foo2"); // Redirection target
// First request as POST
controller.LoadURL(url1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
controller.GetActiveEntry()->SetHasPostData(true);
EXPECT_EQ(0U, notifications.size());
test_rvh()->SendNavigate(0, url2);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// Second request
controller.LoadURL(url1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
EXPECT_TRUE(controller.GetPendingEntry());
EXPECT_EQ(controller.GetPendingEntryIndex(), -1);
EXPECT_EQ(url1, controller.GetActiveEntry()->GetURL());
ViewHostMsg_FrameNavigate_Params params;
params.page_id = 0;
params.url = url2;
params.transition = PAGE_TRANSITION_SERVER_REDIRECT;
params.redirects.push_back(GURL("http://foo1"));
params.redirects.push_back(GURL("http://foo2"));
params.should_update_history = false;
params.gesture = NavigationGestureAuto;
params.is_post = false;
params.page_state = PageState::CreateFromURL(url2);
LoadCommittedDetails details;
EXPECT_EQ(0U, notifications.size());
EXPECT_TRUE(controller.RendererDidNavigate(params, &details));
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_TRUE(details.type == NAVIGATION_TYPE_SAME_PAGE);
EXPECT_EQ(controller.GetEntryCount(), 1);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 0);
EXPECT_TRUE(controller.GetLastCommittedEntry());
EXPECT_EQ(controller.GetPendingEntryIndex(), -1);
EXPECT_FALSE(controller.GetPendingEntry());
EXPECT_EQ(url2, controller.GetActiveEntry()->GetURL());
EXPECT_FALSE(controller.GetActiveEntry()->GetHasPostData());
EXPECT_FALSE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoForward());
}
// A redirect right off the bat should be a NEW_PAGE.
TEST_F(NavigationControllerTest, ImmediateRedirect) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
const GURL url1("http://foo1");
const GURL url2("http://foo2"); // Redirection target
// First request
controller.LoadURL(url1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
EXPECT_TRUE(controller.GetPendingEntry());
EXPECT_EQ(controller.GetPendingEntryIndex(), -1);
EXPECT_EQ(url1, controller.GetActiveEntry()->GetURL());
ViewHostMsg_FrameNavigate_Params params;
params.page_id = 0;
params.url = url2;
params.transition = PAGE_TRANSITION_SERVER_REDIRECT;
params.redirects.push_back(GURL("http://foo1"));
params.redirects.push_back(GURL("http://foo2"));
params.should_update_history = false;
params.gesture = NavigationGestureAuto;
params.is_post = false;
params.page_state = PageState::CreateFromURL(url2);
LoadCommittedDetails details;
EXPECT_EQ(0U, notifications.size());
EXPECT_TRUE(controller.RendererDidNavigate(params, &details));
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_TRUE(details.type == NAVIGATION_TYPE_NEW_PAGE);
EXPECT_EQ(controller.GetEntryCount(), 1);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 0);
EXPECT_TRUE(controller.GetLastCommittedEntry());
EXPECT_EQ(controller.GetPendingEntryIndex(), -1);
EXPECT_FALSE(controller.GetPendingEntry());
EXPECT_EQ(url2, controller.GetActiveEntry()->GetURL());
EXPECT_FALSE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoForward());
}
// Tests navigation via link click within a subframe. A new navigation entry
// should be created.
TEST_F(NavigationControllerTest, NewSubframe) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
const GURL url1("http://foo1");
test_rvh()->SendNavigate(0, url1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
const GURL url2("http://foo2");
ViewHostMsg_FrameNavigate_Params params;
params.page_id = 1;
params.url = url2;
params.transition = PAGE_TRANSITION_MANUAL_SUBFRAME;
params.should_update_history = false;
params.gesture = NavigationGestureUser;
params.is_post = false;
params.page_state = PageState::CreateFromURL(url2);
LoadCommittedDetails details;
EXPECT_TRUE(controller.RendererDidNavigate(params, &details));
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_EQ(url1, details.previous_url);
EXPECT_FALSE(details.is_in_page);
EXPECT_FALSE(details.is_main_frame);
// The new entry should be appended.
EXPECT_EQ(2, controller.GetEntryCount());
// New entry should refer to the new page, but the old URL (entries only
// reflect the toplevel URL).
EXPECT_EQ(url1, details.entry->GetURL());
EXPECT_EQ(params.page_id, details.entry->GetPageID());
}
// Some pages create a popup, then write an iframe into it. This causes a
// subframe navigation without having any committed entry. Such navigations
// just get thrown on the ground, but we shouldn't crash.
TEST_F(NavigationControllerTest, SubframeOnEmptyPage) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
// Navigation controller currently has no entries.
const GURL url("http://foo2");
ViewHostMsg_FrameNavigate_Params params;
params.page_id = 1;
params.url = url;
params.transition = PAGE_TRANSITION_AUTO_SUBFRAME;
params.should_update_history = false;
params.gesture = NavigationGestureAuto;
params.is_post = false;
params.page_state = PageState::CreateFromURL(url);
LoadCommittedDetails details;
EXPECT_FALSE(controller.RendererDidNavigate(params, &details));
EXPECT_EQ(0U, notifications.size());
}
// Auto subframes are ones the page loads automatically like ads. They should
// not create new navigation entries.
TEST_F(NavigationControllerTest, AutoSubframe) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
const GURL url1("http://foo1");
test_rvh()->SendNavigate(0, url1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
const GURL url2("http://foo2");
ViewHostMsg_FrameNavigate_Params params;
params.page_id = 0;
params.url = url2;
params.transition = PAGE_TRANSITION_AUTO_SUBFRAME;
params.should_update_history = false;
params.gesture = NavigationGestureUser;
params.is_post = false;
params.page_state = PageState::CreateFromURL(url2);
// Navigating should do nothing.
LoadCommittedDetails details;
EXPECT_FALSE(controller.RendererDidNavigate(params, &details));
EXPECT_EQ(0U, notifications.size());
// There should still be only one entry.
EXPECT_EQ(1, controller.GetEntryCount());
}
// Tests navigation and then going back to a subframe navigation.
TEST_F(NavigationControllerTest, BackSubframe) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
// Main page.
const GURL url1("http://foo1");
test_rvh()->SendNavigate(0, url1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// First manual subframe navigation.
const GURL url2("http://foo2");
ViewHostMsg_FrameNavigate_Params params;
params.page_id = 1;
params.url = url2;
params.transition = PAGE_TRANSITION_MANUAL_SUBFRAME;
params.should_update_history = false;
params.gesture = NavigationGestureUser;
params.is_post = false;
params.page_state = PageState::CreateFromURL(url2);
// This should generate a new entry.
LoadCommittedDetails details;
EXPECT_TRUE(controller.RendererDidNavigate(params, &details));
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_EQ(2, controller.GetEntryCount());
// Second manual subframe navigation should also make a new entry.
const GURL url3("http://foo3");
params.page_id = 2;
params.url = url3;
EXPECT_TRUE(controller.RendererDidNavigate(params, &details));
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_EQ(3, controller.GetEntryCount());
EXPECT_EQ(2, controller.GetCurrentEntryIndex());
// Go back one.
controller.GoBack();
params.url = url2;
params.page_id = 1;
EXPECT_TRUE(controller.RendererDidNavigate(params, &details));
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_EQ(3, controller.GetEntryCount());
EXPECT_EQ(1, controller.GetCurrentEntryIndex());
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
EXPECT_FALSE(controller.GetPendingEntry());
// Go back one more.
controller.GoBack();
params.url = url1;
params.page_id = 0;
EXPECT_TRUE(controller.RendererDidNavigate(params, &details));
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_EQ(3, controller.GetEntryCount());
EXPECT_EQ(0, controller.GetCurrentEntryIndex());
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
EXPECT_FALSE(controller.GetPendingEntry());
}
TEST_F(NavigationControllerTest, LinkClick) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
const GURL url1("http://foo1");
const GURL url2("http://foo2");
test_rvh()->SendNavigate(0, url1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
test_rvh()->SendNavigate(1, url2);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// Should not have produced a new session history entry.
EXPECT_EQ(controller.GetEntryCount(), 2);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 1);
EXPECT_EQ(controller.GetPendingEntryIndex(), -1);
EXPECT_TRUE(controller.GetLastCommittedEntry());
EXPECT_FALSE(controller.GetPendingEntry());
EXPECT_TRUE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoForward());
}
TEST_F(NavigationControllerTest, InPage) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
// Main page.
const GURL url1("http://foo");
test_rvh()->SendNavigate(0, url1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// Ensure main page navigation to same url respects the was_within_same_page
// hint provided in the params.
ViewHostMsg_FrameNavigate_Params self_params;
self_params.page_id = 0;
self_params.url = url1;
self_params.transition = PAGE_TRANSITION_LINK;
self_params.should_update_history = false;
self_params.gesture = NavigationGestureUser;
self_params.is_post = false;
self_params.page_state = PageState::CreateFromURL(url1);
self_params.was_within_same_page = true;
LoadCommittedDetails details;
EXPECT_TRUE(controller.RendererDidNavigate(self_params, &details));
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_TRUE(details.is_in_page);
EXPECT_TRUE(details.did_replace_entry);
EXPECT_EQ(1, controller.GetEntryCount());
// Fragment navigation to a new page_id.
const GURL url2("http://foo#a");
ViewHostMsg_FrameNavigate_Params params;
params.page_id = 1;
params.url = url2;
params.transition = PAGE_TRANSITION_LINK;
params.should_update_history = false;
params.gesture = NavigationGestureUser;
params.is_post = false;
params.page_state = PageState::CreateFromURL(url2);
params.was_within_same_page = true;
// This should generate a new entry.
EXPECT_TRUE(controller.RendererDidNavigate(params, &details));
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_TRUE(details.is_in_page);
EXPECT_FALSE(details.did_replace_entry);
EXPECT_EQ(2, controller.GetEntryCount());
// Go back one.
ViewHostMsg_FrameNavigate_Params back_params(params);
controller.GoBack();
back_params.url = url1;
back_params.page_id = 0;
EXPECT_TRUE(controller.RendererDidNavigate(back_params, &details));
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_TRUE(details.is_in_page);
EXPECT_EQ(2, controller.GetEntryCount());
EXPECT_EQ(0, controller.GetCurrentEntryIndex());
EXPECT_EQ(back_params.url, controller.GetActiveEntry()->GetURL());
// Go forward
ViewHostMsg_FrameNavigate_Params forward_params(params);
controller.GoForward();
forward_params.url = url2;
forward_params.page_id = 1;
EXPECT_TRUE(controller.RendererDidNavigate(forward_params, &details));
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_TRUE(details.is_in_page);
EXPECT_EQ(2, controller.GetEntryCount());
EXPECT_EQ(1, controller.GetCurrentEntryIndex());
EXPECT_EQ(forward_params.url,
controller.GetActiveEntry()->GetURL());
// Now go back and forward again. This is to work around a bug where we would
// compare the incoming URL with the last committed entry rather than the
// one identified by an existing page ID. This would result in the second URL
// losing the reference fragment when you navigate away from it and then back.
controller.GoBack();
EXPECT_TRUE(controller.RendererDidNavigate(back_params, &details));
controller.GoForward();
EXPECT_TRUE(controller.RendererDidNavigate(forward_params, &details));
EXPECT_EQ(forward_params.url,
controller.GetActiveEntry()->GetURL());
// Finally, navigate to an unrelated URL to make sure in_page is not sticky.
const GURL url3("http://bar");
params.page_id = 2;
params.url = url3;
navigation_entry_committed_counter_ = 0;
EXPECT_TRUE(controller.RendererDidNavigate(params, &details));
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_FALSE(details.is_in_page);
EXPECT_EQ(3, controller.GetEntryCount());
EXPECT_EQ(2, controller.GetCurrentEntryIndex());
}
TEST_F(NavigationControllerTest, InPage_Replace) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
// Main page.
const GURL url1("http://foo");
test_rvh()->SendNavigate(0, url1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// First navigation.
const GURL url2("http://foo#a");
ViewHostMsg_FrameNavigate_Params params;
params.page_id = 0; // Same page_id
params.url = url2;
params.transition = PAGE_TRANSITION_LINK;
params.should_update_history = false;
params.gesture = NavigationGestureUser;
params.is_post = false;
params.page_state = PageState::CreateFromURL(url2);
// This should NOT generate a new entry, nor prune the list.
LoadCommittedDetails details;
EXPECT_TRUE(controller.RendererDidNavigate(params, &details));
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_TRUE(details.is_in_page);
EXPECT_TRUE(details.did_replace_entry);
EXPECT_EQ(1, controller.GetEntryCount());
}
// Tests for http://crbug.com/40395
// Simulates this:
// <script>
// window.location.replace("#a");
// window.location='http://foo3/';
// </script>
TEST_F(NavigationControllerTest, ClientRedirectAfterInPageNavigation) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
// Load an initial page.
{
const GURL url("http://foo/");
test_rvh()->SendNavigate(0, url);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
}
// Navigate to a new page.
{
const GURL url("http://foo2/");
test_rvh()->SendNavigate(1, url);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
}
// Navigate within the page.
{
const GURL url("http://foo2/#a");
ViewHostMsg_FrameNavigate_Params params;
params.page_id = 1; // Same page_id
params.url = url;
params.transition = PAGE_TRANSITION_LINK;
params.redirects.push_back(url);
params.should_update_history = true;
params.gesture = NavigationGestureUnknown;
params.is_post = false;
params.page_state = PageState::CreateFromURL(url);
// This should NOT generate a new entry, nor prune the list.
LoadCommittedDetails details;
EXPECT_TRUE(controller.RendererDidNavigate(params, &details));
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_TRUE(details.is_in_page);
EXPECT_TRUE(details.did_replace_entry);
EXPECT_EQ(2, controller.GetEntryCount());
}
// Perform a client redirect to a new page.
{
const GURL url("http://foo3/");
ViewHostMsg_FrameNavigate_Params params;
params.page_id = 2; // New page_id
params.url = url;
params.transition = PAGE_TRANSITION_CLIENT_REDIRECT;
params.redirects.push_back(GURL("http://foo2/#a"));
params.redirects.push_back(url);
params.should_update_history = true;
params.gesture = NavigationGestureUnknown;
params.is_post = false;
params.page_state = PageState::CreateFromURL(url);
// This SHOULD generate a new entry.
LoadCommittedDetails details;
EXPECT_TRUE(controller.RendererDidNavigate(params, &details));
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_FALSE(details.is_in_page);
EXPECT_EQ(3, controller.GetEntryCount());
}
// Verify that BACK brings us back to http://foo2/.
{
const GURL url("http://foo2/");
controller.GoBack();
test_rvh()->SendNavigate(1, url);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_EQ(url, controller.GetActiveEntry()->GetURL());
}
}
// NotificationObserver implementation used in verifying we've received the
// NOTIFICATION_NAV_LIST_PRUNED method.
class PrunedListener : public NotificationObserver {
public:
explicit PrunedListener(NavigationControllerImpl* controller)
: notification_count_(0) {
registrar_.Add(this, NOTIFICATION_NAV_LIST_PRUNED,
Source<NavigationController>(controller));
}
virtual void Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) OVERRIDE {
if (type == NOTIFICATION_NAV_LIST_PRUNED) {
notification_count_++;
details_ = *(Details<PrunedDetails>(details).ptr());
}
}
// Number of times NAV_LIST_PRUNED has been observed.
int notification_count_;
// Details from the last NAV_LIST_PRUNED.
PrunedDetails details_;
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(PrunedListener);
};
// Tests that we limit the number of navigation entries created correctly.
TEST_F(NavigationControllerTest, EnforceMaxNavigationCount) {
NavigationControllerImpl& controller = controller_impl();
size_t original_count = NavigationControllerImpl::max_entry_count();
const int kMaxEntryCount = 5;
NavigationControllerImpl::set_max_entry_count_for_testing(kMaxEntryCount);
int url_index;
// Load up to the max count, all entries should be there.
for (url_index = 0; url_index < kMaxEntryCount; url_index++) {
GURL url(base::StringPrintf("http://www.a.com/%d", url_index));
controller.LoadURL(
url, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(url_index, url);
}
EXPECT_EQ(controller.GetEntryCount(), kMaxEntryCount);
// Created a PrunedListener to observe prune notifications.
PrunedListener listener(&controller);
// Navigate some more.
GURL url(base::StringPrintf("http://www.a.com/%d", url_index));
controller.LoadURL(
url, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(url_index, url);
url_index++;
// We should have got a pruned navigation.
EXPECT_EQ(1, listener.notification_count_);
EXPECT_TRUE(listener.details_.from_front);
EXPECT_EQ(1, listener.details_.count);
// We expect http://www.a.com/0 to be gone.
EXPECT_EQ(controller.GetEntryCount(), kMaxEntryCount);
EXPECT_EQ(controller.GetEntryAtIndex(0)->GetURL(),
GURL("http:////www.a.com/1"));
// More navigations.
for (int i = 0; i < 3; i++) {
url = GURL(base::StringPrintf("http:////www.a.com/%d", url_index));
controller.LoadURL(
url, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(url_index, url);
url_index++;
}
EXPECT_EQ(controller.GetEntryCount(), kMaxEntryCount);
EXPECT_EQ(controller.GetEntryAtIndex(0)->GetURL(),
GURL("http:////www.a.com/4"));
NavigationControllerImpl::set_max_entry_count_for_testing(original_count);
}
// Tests that we can do a restore and navigate to the restored entries and
// everything is updated properly. This can be tricky since there is no
// SiteInstance for the entries created initially.
TEST_F(NavigationControllerTest, RestoreNavigate) {
// Create a NavigationController with a restored set of tabs.
GURL url("http://foo");
std::vector<NavigationEntry*> entries;
NavigationEntry* entry = NavigationControllerImpl::CreateNavigationEntry(
url, Referrer(), PAGE_TRANSITION_RELOAD, false, std::string(),
browser_context());
entry->SetPageID(0);
entry->SetTitle(ASCIIToUTF16("Title"));
entry->SetPageState(PageState::CreateFromEncodedData("state"));
const base::Time timestamp = base::Time::Now();
entry->SetTimestamp(timestamp);
entries.push_back(entry);
scoped_ptr<WebContentsImpl> our_contents(static_cast<WebContentsImpl*>(
WebContents::Create(WebContents::CreateParams(browser_context()))));
NavigationControllerImpl& our_controller = our_contents->GetController();
our_controller.Restore(
0,
NavigationController::RESTORE_LAST_SESSION_EXITED_CLEANLY,
&entries);
ASSERT_EQ(0u, entries.size());
// Before navigating to the restored entry, it should have a restore_type
// and no SiteInstance.
ASSERT_EQ(1, our_controller.GetEntryCount());
EXPECT_EQ(NavigationEntryImpl::RESTORE_LAST_SESSION_EXITED_CLEANLY,
NavigationEntryImpl::FromNavigationEntry(
our_controller.GetEntryAtIndex(0))->restore_type());
EXPECT_FALSE(NavigationEntryImpl::FromNavigationEntry(
our_controller.GetEntryAtIndex(0))->site_instance());
// After navigating, we should have one entry, and it should be "pending".
// It should now have a SiteInstance and no restore_type.
our_controller.GoToIndex(0);
EXPECT_EQ(1, our_controller.GetEntryCount());
EXPECT_EQ(our_controller.GetEntryAtIndex(0),
our_controller.GetPendingEntry());
EXPECT_EQ(0, our_controller.GetEntryAtIndex(0)->GetPageID());
EXPECT_EQ(NavigationEntryImpl::RESTORE_NONE,
NavigationEntryImpl::FromNavigationEntry
(our_controller.GetEntryAtIndex(0))->restore_type());
EXPECT_TRUE(NavigationEntryImpl::FromNavigationEntry(
our_controller.GetEntryAtIndex(0))->site_instance());
// Timestamp should remain the same before the navigation finishes.
EXPECT_EQ(timestamp, our_controller.GetEntryAtIndex(0)->GetTimestamp());
// Say we navigated to that entry.
ViewHostMsg_FrameNavigate_Params params;
params.page_id = 0;
params.url = url;
params.transition = PAGE_TRANSITION_LINK;
params.should_update_history = false;
params.gesture = NavigationGestureUser;
params.is_post = false;
params.page_state = PageState::CreateFromURL(url);
LoadCommittedDetails details;
our_controller.RendererDidNavigate(params, &details);
// There should be no longer any pending entry and one committed one. This
// means that we were able to locate the entry, assign its site instance, and
// commit it properly.
EXPECT_EQ(1, our_controller.GetEntryCount());
EXPECT_EQ(0, our_controller.GetLastCommittedEntryIndex());
EXPECT_FALSE(our_controller.GetPendingEntry());
EXPECT_EQ(url,
NavigationEntryImpl::FromNavigationEntry(
our_controller.GetLastCommittedEntry())->site_instance()->
GetSiteURL());
EXPECT_EQ(NavigationEntryImpl::RESTORE_NONE,
NavigationEntryImpl::FromNavigationEntry(
our_controller.GetEntryAtIndex(0))->restore_type());
// Timestamp should have been updated.
EXPECT_GE(our_controller.GetEntryAtIndex(0)->GetTimestamp(), timestamp);
}
// Tests that we can still navigate to a restored entry after a different
// navigation fails and clears the pending entry. http://crbug.com/90085
TEST_F(NavigationControllerTest, RestoreNavigateAfterFailure) {
// Create a NavigationController with a restored set of tabs.
GURL url("http://foo");
std::vector<NavigationEntry*> entries;
NavigationEntry* entry = NavigationControllerImpl::CreateNavigationEntry(
url, Referrer(), PAGE_TRANSITION_RELOAD, false, std::string(),
browser_context());
entry->SetPageID(0);
entry->SetTitle(ASCIIToUTF16("Title"));
entry->SetPageState(PageState::CreateFromEncodedData("state"));
entries.push_back(entry);
scoped_ptr<WebContentsImpl> our_contents(static_cast<WebContentsImpl*>(
WebContents::Create(WebContents::CreateParams(browser_context()))));
NavigationControllerImpl& our_controller = our_contents->GetController();
our_controller.Restore(
0, NavigationController::RESTORE_LAST_SESSION_EXITED_CLEANLY, &entries);
ASSERT_EQ(0u, entries.size());
// Before navigating to the restored entry, it should have a restore_type
// and no SiteInstance.
EXPECT_EQ(NavigationEntryImpl::RESTORE_LAST_SESSION_EXITED_CLEANLY,
NavigationEntryImpl::FromNavigationEntry(
our_controller.GetEntryAtIndex(0))->restore_type());
EXPECT_FALSE(NavigationEntryImpl::FromNavigationEntry(
our_controller.GetEntryAtIndex(0))->site_instance());
// After navigating, we should have one entry, and it should be "pending".
// It should now have a SiteInstance and no restore_type.
our_controller.GoToIndex(0);
EXPECT_EQ(1, our_controller.GetEntryCount());
EXPECT_EQ(our_controller.GetEntryAtIndex(0),
our_controller.GetPendingEntry());
EXPECT_EQ(0, our_controller.GetEntryAtIndex(0)->GetPageID());
EXPECT_EQ(NavigationEntryImpl::RESTORE_NONE,
NavigationEntryImpl::FromNavigationEntry(
our_controller.GetEntryAtIndex(0))->restore_type());
EXPECT_TRUE(NavigationEntryImpl::FromNavigationEntry(
our_controller.GetEntryAtIndex(0))->site_instance());
// This pending navigation may have caused a different navigation to fail,
// which causes the pending entry to be cleared.
TestRenderViewHost* rvh =
static_cast<TestRenderViewHost*>(our_contents->GetRenderViewHost());
ViewHostMsg_DidFailProvisionalLoadWithError_Params fail_load_params;
fail_load_params.frame_id = 1;
fail_load_params.is_main_frame = true;
fail_load_params.error_code = net::ERR_ABORTED;
fail_load_params.error_description = string16();
fail_load_params.url = url;
fail_load_params.showing_repost_interstitial = false;
rvh->OnMessageReceived(
ViewHostMsg_DidFailProvisionalLoadWithError(0, // routing_id
fail_load_params));
// Now the pending restored entry commits.
ViewHostMsg_FrameNavigate_Params params;
params.page_id = 0;
params.url = url;
params.transition = PAGE_TRANSITION_LINK;
params.should_update_history = false;
params.gesture = NavigationGestureUser;
params.is_post = false;
params.page_state = PageState::CreateFromURL(url);
LoadCommittedDetails details;
our_controller.RendererDidNavigate(params, &details);
// There should be no pending entry and one committed one.
EXPECT_EQ(1, our_controller.GetEntryCount());
EXPECT_EQ(0, our_controller.GetLastCommittedEntryIndex());
EXPECT_FALSE(our_controller.GetPendingEntry());
EXPECT_EQ(url,
NavigationEntryImpl::FromNavigationEntry(
our_controller.GetLastCommittedEntry())->site_instance()->
GetSiteURL());
EXPECT_EQ(NavigationEntryImpl::RESTORE_NONE,
NavigationEntryImpl::FromNavigationEntry(
our_controller.GetEntryAtIndex(0))->restore_type());
}
// Make sure that the page type and stuff is correct after an interstitial.
TEST_F(NavigationControllerTest, Interstitial) {
NavigationControllerImpl& controller = controller_impl();
// First navigate somewhere normal.
const GURL url1("http://foo");
controller.LoadURL(
url1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(0, url1);
// Now navigate somewhere with an interstitial.
const GURL url2("http://bar");
controller.LoadURL(
url1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
NavigationEntryImpl::FromNavigationEntry(controller.GetPendingEntry())->
set_page_type(PAGE_TYPE_INTERSTITIAL);
// At this point the interstitial will be displayed and the load will still
// be pending. If the user continues, the load will commit.
test_rvh()->SendNavigate(1, url2);
// The page should be a normal page again.
EXPECT_EQ(url2, controller.GetLastCommittedEntry()->GetURL());
EXPECT_EQ(PAGE_TYPE_NORMAL,
controller.GetLastCommittedEntry()->GetPageType());
}
TEST_F(NavigationControllerTest, RemoveEntry) {
NavigationControllerImpl& controller = controller_impl();
const GURL url1("http://foo/1");
const GURL url2("http://foo/2");
const GURL url3("http://foo/3");
const GURL url4("http://foo/4");
const GURL url5("http://foo/5");
const GURL pending_url("http://foo/pending");
const GURL default_url("http://foo/default");
controller.LoadURL(
url1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(0, url1);
controller.LoadURL(
url2, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(1, url2);
controller.LoadURL(
url3, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(2, url3);
controller.LoadURL(
url4, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(3, url4);
controller.LoadURL(
url5, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(4, url5);
// Try to remove the last entry. Will fail because it is the current entry.
EXPECT_FALSE(controller.RemoveEntryAtIndex(controller.GetEntryCount() - 1));
EXPECT_EQ(5, controller.GetEntryCount());
EXPECT_EQ(4, controller.GetLastCommittedEntryIndex());
// Go back, but don't commit yet. Check that we can't delete the current
// and pending entries.
controller.GoBack();
EXPECT_FALSE(controller.RemoveEntryAtIndex(controller.GetEntryCount() - 1));
EXPECT_FALSE(controller.RemoveEntryAtIndex(controller.GetEntryCount() - 2));
// Now commit and delete the last entry.
test_rvh()->SendNavigate(3, url4);
EXPECT_TRUE(controller.RemoveEntryAtIndex(controller.GetEntryCount() - 1));
EXPECT_EQ(4, controller.GetEntryCount());
EXPECT_EQ(3, controller.GetLastCommittedEntryIndex());
EXPECT_FALSE(controller.GetPendingEntry());
// Remove an entry which is not the last committed one.
EXPECT_TRUE(controller.RemoveEntryAtIndex(0));
EXPECT_EQ(3, controller.GetEntryCount());
EXPECT_EQ(2, controller.GetLastCommittedEntryIndex());
EXPECT_FALSE(controller.GetPendingEntry());
// Remove the 2 remaining entries.
controller.RemoveEntryAtIndex(1);
controller.RemoveEntryAtIndex(0);
// This should leave us with only the last committed entry.
EXPECT_EQ(1, controller.GetEntryCount());
EXPECT_EQ(0, controller.GetLastCommittedEntryIndex());
}
// Tests the transient entry, making sure it goes away with all navigations.
TEST_F(NavigationControllerTest, TransientEntry) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
const GURL url0("http://foo/0");
const GURL url1("http://foo/1");
const GURL url2("http://foo/2");
const GURL url3("http://foo/3");
const GURL url3_ref("http://foo/3#bar");
const GURL url4("http://foo/4");
const GURL transient_url("http://foo/transient");
controller.LoadURL(
url0, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(0, url0);
controller.LoadURL(
url1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(1, url1);
notifications.Reset();
// Adding a transient with no pending entry.
NavigationEntryImpl* transient_entry = new NavigationEntryImpl;
transient_entry->SetURL(transient_url);
controller.SetTransientEntry(transient_entry);
// We should not have received any notifications.
EXPECT_EQ(0U, notifications.size());
// Check our state.
EXPECT_EQ(transient_url, controller.GetActiveEntry()->GetURL());
EXPECT_EQ(controller.GetEntryCount(), 3);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 1);
EXPECT_EQ(controller.GetPendingEntryIndex(), -1);
EXPECT_TRUE(controller.GetLastCommittedEntry());
EXPECT_FALSE(controller.GetPendingEntry());
EXPECT_TRUE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoForward());
EXPECT_EQ(contents()->GetMaxPageID(), 1);
// Navigate.
controller.LoadURL(
url2, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(2, url2);
// We should have navigated, transient entry should be gone.
EXPECT_EQ(url2, controller.GetActiveEntry()->GetURL());
EXPECT_EQ(controller.GetEntryCount(), 3);
// Add a transient again, then navigate with no pending entry this time.
transient_entry = new NavigationEntryImpl;
transient_entry->SetURL(transient_url);
controller.SetTransientEntry(transient_entry);
EXPECT_EQ(transient_url, controller.GetActiveEntry()->GetURL());
test_rvh()->SendNavigate(3, url3);
// Transient entry should be gone.
EXPECT_EQ(url3, controller.GetActiveEntry()->GetURL());
EXPECT_EQ(controller.GetEntryCount(), 4);
// Initiate a navigation, add a transient then commit navigation.
controller.LoadURL(
url4, Referrer(), PAGE_TRANSITION_TYPED, std::string());
transient_entry = new NavigationEntryImpl;
transient_entry->SetURL(transient_url);
controller.SetTransientEntry(transient_entry);
EXPECT_EQ(transient_url, controller.GetActiveEntry()->GetURL());
test_rvh()->SendNavigate(4, url4);
EXPECT_EQ(url4, controller.GetActiveEntry()->GetURL());
EXPECT_EQ(controller.GetEntryCount(), 5);
// Add a transient and go back. This should simply remove the transient.
transient_entry = new NavigationEntryImpl;
transient_entry->SetURL(transient_url);
controller.SetTransientEntry(transient_entry);
EXPECT_EQ(transient_url, controller.GetActiveEntry()->GetURL());
EXPECT_TRUE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoForward());
controller.GoBack();
// Transient entry should be gone.
EXPECT_EQ(url4, controller.GetActiveEntry()->GetURL());
EXPECT_EQ(controller.GetEntryCount(), 5);
test_rvh()->SendNavigate(3, url3);
// Add a transient and go to an entry before the current one.
transient_entry = new NavigationEntryImpl;
transient_entry->SetURL(transient_url);
controller.SetTransientEntry(transient_entry);
EXPECT_EQ(transient_url, controller.GetActiveEntry()->GetURL());
controller.GoToIndex(1);
// The navigation should have been initiated, transient entry should be gone.
EXPECT_EQ(url1, controller.GetActiveEntry()->GetURL());
// Visible entry does not update for history navigations until commit.
EXPECT_EQ(url3, controller.GetVisibleEntry()->GetURL());
test_rvh()->SendNavigate(1, url1);
EXPECT_EQ(url1, controller.GetVisibleEntry()->GetURL());
// Add a transient and go to an entry after the current one.
transient_entry = new NavigationEntryImpl;
transient_entry->SetURL(transient_url);
controller.SetTransientEntry(transient_entry);
EXPECT_EQ(transient_url, controller.GetActiveEntry()->GetURL());
controller.GoToIndex(3);
// The navigation should have been initiated, transient entry should be gone.
// Because of the transient entry that is removed, going to index 3 makes us
// land on url2 (which is visible after the commit).
EXPECT_EQ(url2, controller.GetActiveEntry()->GetURL());
EXPECT_EQ(url1, controller.GetVisibleEntry()->GetURL());
test_rvh()->SendNavigate(2, url2);
EXPECT_EQ(url2, controller.GetVisibleEntry()->GetURL());
// Add a transient and go forward.
transient_entry = new NavigationEntryImpl;
transient_entry->SetURL(transient_url);
controller.SetTransientEntry(transient_entry);
EXPECT_EQ(transient_url, controller.GetActiveEntry()->GetURL());
EXPECT_TRUE(controller.CanGoForward());
controller.GoForward();
// We should have navigated, transient entry should be gone.
EXPECT_EQ(url3, controller.GetActiveEntry()->GetURL());
EXPECT_EQ(url2, controller.GetVisibleEntry()->GetURL());
test_rvh()->SendNavigate(3, url3);
EXPECT_EQ(url3, controller.GetVisibleEntry()->GetURL());
// Add a transient and do an in-page navigation, replacing the current entry.
transient_entry = new NavigationEntryImpl;
transient_entry->SetURL(transient_url);
controller.SetTransientEntry(transient_entry);
EXPECT_EQ(transient_url, controller.GetActiveEntry()->GetURL());
test_rvh()->SendNavigate(3, url3_ref);
// Transient entry should be gone.
EXPECT_EQ(url3_ref, controller.GetActiveEntry()->GetURL());
// Ensure the URLs are correct.
EXPECT_EQ(controller.GetEntryCount(), 5);
EXPECT_EQ(controller.GetEntryAtIndex(0)->GetURL(), url0);
EXPECT_EQ(controller.GetEntryAtIndex(1)->GetURL(), url1);
EXPECT_EQ(controller.GetEntryAtIndex(2)->GetURL(), url2);
EXPECT_EQ(controller.GetEntryAtIndex(3)->GetURL(), url3_ref);
EXPECT_EQ(controller.GetEntryAtIndex(4)->GetURL(), url4);
}
// Test that Reload initiates a new navigation to a transient entry's URL.
TEST_F(NavigationControllerTest, ReloadTransient) {
NavigationControllerImpl& controller = controller_impl();
const GURL url0("http://foo/0");
const GURL url1("http://foo/1");
const GURL transient_url("http://foo/transient");
// Load |url0|, and start a pending navigation to |url1|.
controller.LoadURL(
url0, Referrer(), PAGE_TRANSITION_TYPED, std::string());
test_rvh()->SendNavigate(0, url0);
controller.LoadURL(
url1, Referrer(), PAGE_TRANSITION_TYPED, std::string());
// A transient entry is added, interrupting the navigation.
NavigationEntryImpl* transient_entry = new NavigationEntryImpl;
transient_entry->SetURL(transient_url);
controller.SetTransientEntry(transient_entry);
EXPECT_TRUE(controller.GetTransientEntry());
EXPECT_EQ(transient_url, controller.GetActiveEntry()->GetURL());
// The page is reloaded, which should remove the pending entry for |url1| and
// the transient entry for |transient_url|, and start a navigation to
// |transient_url|.
controller.Reload(true);
EXPECT_FALSE(controller.GetTransientEntry());
EXPECT_TRUE(controller.GetPendingEntry());
EXPECT_EQ(transient_url, controller.GetActiveEntry()->GetURL());
ASSERT_EQ(controller.GetEntryCount(), 1);
EXPECT_EQ(controller.GetEntryAtIndex(0)->GetURL(), url0);
// Load of |transient_url| completes.
test_rvh()->SendNavigate(1, transient_url);
ASSERT_EQ(controller.GetEntryCount(), 2);
EXPECT_EQ(controller.GetEntryAtIndex(0)->GetURL(), url0);
EXPECT_EQ(controller.GetEntryAtIndex(1)->GetURL(), transient_url);
}
// Ensure that renderer initiated pending entries get replaced, so that we
// don't show a stale virtual URL when a navigation commits.
// See http://crbug.com/266922.
TEST_F(NavigationControllerTest, RendererInitiatedPendingEntries) {
NavigationControllerImpl& controller = controller_impl();
const GURL url1("nonexistent:12121");
const GURL url1_fixed("http://nonexistent:12121/");
const GURL url2("http://foo");
// We create pending entries for renderer-initiated navigations so that we
// can show them in new tabs when it is safe.
contents()->DidStartProvisionalLoadForFrame(
test_rvh(), 1, -1, true, url1);
// Simulate what happens if a BrowserURLHandler rewrites the URL, causing
// the virtual URL to differ from the URL.
controller.GetPendingEntry()->SetURL(url1_fixed);
controller.GetPendingEntry()->SetVirtualURL(url1);
EXPECT_EQ(url1_fixed, controller.GetPendingEntry()->GetURL());
EXPECT_EQ(url1, controller.GetPendingEntry()->GetVirtualURL());
EXPECT_TRUE(
NavigationEntryImpl::FromNavigationEntry(controller.GetPendingEntry())->
is_renderer_initiated());
// If the user clicks another link, we should replace the pending entry.
contents()->DidStartProvisionalLoadForFrame(
test_rvh(), 1, -1, true, url2);
EXPECT_EQ(url2, controller.GetPendingEntry()->GetURL());
EXPECT_EQ(url2, controller.GetPendingEntry()->GetVirtualURL());
// Once it commits, the URL and virtual URL should reflect the actual page.
test_rvh()->SendNavigate(0, url2);
EXPECT_EQ(url2, controller.GetLastCommittedEntry()->GetURL());
EXPECT_EQ(url2, controller.GetLastCommittedEntry()->GetVirtualURL());
// We should not replace the pending entry for an error URL.
contents()->DidStartProvisionalLoadForFrame(
test_rvh(), 1, -1, true, url1);
EXPECT_EQ(url1, controller.GetPendingEntry()->GetURL());
contents()->DidStartProvisionalLoadForFrame(
test_rvh(), 1, -1, true, GURL(kUnreachableWebDataURL));
EXPECT_EQ(url1, controller.GetPendingEntry()->GetURL());
}
// Tests that the URLs for renderer-initiated navigations are not displayed to
// the user until the navigation commits, to prevent URL spoof attacks.
// See http://crbug.com/99016.
TEST_F(NavigationControllerTest, DontShowRendererURLUntilCommit) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
const GURL url0("http://foo/0");
const GURL url1("http://foo/1");
// For typed navigations (browser-initiated), both active and visible entries
// should update before commit.
controller.LoadURL(url0, Referrer(), PAGE_TRANSITION_TYPED, std::string());
EXPECT_EQ(url0, controller.GetActiveEntry()->GetURL());
EXPECT_EQ(url0, controller.GetVisibleEntry()->GetURL());
test_rvh()->SendNavigate(0, url0);
// For link clicks (renderer-initiated navigations), the active entry should
// update before commit but the visible should not.
NavigationController::LoadURLParams load_url_params(url1);
load_url_params.is_renderer_initiated = true;
controller.LoadURLWithParams(load_url_params);
EXPECT_EQ(url1, controller.GetActiveEntry()->GetURL());
EXPECT_EQ(url0, controller.GetVisibleEntry()->GetURL());
EXPECT_TRUE(
NavigationEntryImpl::FromNavigationEntry(controller.GetPendingEntry())->
is_renderer_initiated());
// After commit, both should be updated, and we should no longer treat the
// entry as renderer-initiated.
test_rvh()->SendNavigate(1, url1);
EXPECT_EQ(url1, controller.GetActiveEntry()->GetURL());
EXPECT_EQ(url1, controller.GetVisibleEntry()->GetURL());
EXPECT_FALSE(
NavigationEntryImpl::FromNavigationEntry(
controller.GetLastCommittedEntry())->is_renderer_initiated());
notifications.Reset();
}
// Tests that the URLs for renderer-initiated navigations in new tabs are
// displayed to the user before commit, as long as the initial about:blank
// page has not been modified. If so, we must revert to showing about:blank.
// See http://crbug.com/9682.
TEST_F(NavigationControllerTest, ShowRendererURLInNewTabUntilModified) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
const GURL url("http://foo");
// For renderer-initiated navigations in new tabs (with no committed entries),
// we show the pending entry's URL as long as the about:blank page is not
// modified.
NavigationController::LoadURLParams load_url_params(url);
load_url_params.transition_type = PAGE_TRANSITION_LINK;
load_url_params.is_renderer_initiated = true;
controller.LoadURLWithParams(load_url_params);
EXPECT_EQ(url, controller.GetActiveEntry()->GetURL());
EXPECT_EQ(url, controller.GetVisibleEntry()->GetURL());
EXPECT_TRUE(
NavigationEntryImpl::FromNavigationEntry(controller.GetPendingEntry())->
is_renderer_initiated());
EXPECT_TRUE(controller.IsInitialNavigation());
EXPECT_FALSE(test_rvh()->has_accessed_initial_document());
// There should be no title yet.
EXPECT_TRUE(contents()->GetTitle().empty());
// If something else modifies the contents of the about:blank page, then
// we must revert to showing about:blank to avoid a URL spoof.
test_rvh()->OnMessageReceived(
ViewHostMsg_DidAccessInitialDocument(0));
EXPECT_TRUE(test_rvh()->has_accessed_initial_document());
EXPECT_FALSE(controller.GetVisibleEntry());
EXPECT_EQ(url, controller.GetActiveEntry()->GetURL());
notifications.Reset();
}
TEST_F(NavigationControllerTest, DontShowRendererURLInNewTabAfterCommit) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
const GURL url1("http://foo/eh");
const GURL url2("http://foo/bee");
// For renderer-initiated navigations in new tabs (with no committed entries),
// we show the pending entry's URL as long as the about:blank page is not
// modified.
NavigationController::LoadURLParams load_url_params(url1);
load_url_params.transition_type = PAGE_TRANSITION_LINK;
load_url_params.is_renderer_initiated = true;
controller.LoadURLWithParams(load_url_params);
EXPECT_EQ(url1, controller.GetActiveEntry()->GetURL());
EXPECT_EQ(url1, controller.GetVisibleEntry()->GetURL());
EXPECT_TRUE(
NavigationEntryImpl::FromNavigationEntry(controller.GetPendingEntry())->
is_renderer_initiated());
EXPECT_TRUE(controller.IsInitialNavigation());
EXPECT_FALSE(test_rvh()->has_accessed_initial_document());
// Simulate a commit and then starting a new pending navigation.
test_rvh()->SendNavigate(0, url1);
NavigationController::LoadURLParams load_url2_params(url2);
load_url2_params.transition_type = PAGE_TRANSITION_LINK;
load_url2_params.is_renderer_initiated = true;
controller.LoadURLWithParams(load_url2_params);
// We should not consider this an initial navigation, and thus should
// not show the pending URL.
EXPECT_FALSE(test_rvh()->has_accessed_initial_document());
EXPECT_FALSE(controller.IsInitialNavigation());
EXPECT_TRUE(controller.GetVisibleEntry());
EXPECT_EQ(url1, controller.GetVisibleEntry()->GetURL());
notifications.Reset();
}
// Tests that IsInPageNavigation returns appropriate results. Prevents
// regression for bug 1126349.
TEST_F(NavigationControllerTest, IsInPageNavigation) {
NavigationControllerImpl& controller = controller_impl();
// Navigate to URL with no refs.
const GURL url("http://www.google.com/home.html");
test_rvh()->SendNavigate(0, url);
// Reloading the page is not an in-page navigation.
EXPECT_FALSE(controller.IsURLInPageNavigation(url));
const GURL other_url("http://www.google.com/add.html");
EXPECT_FALSE(controller.IsURLInPageNavigation(other_url));
const GURL url_with_ref("http://www.google.com/home.html#my_ref");
EXPECT_TRUE(controller.IsURLInPageNavigation(url_with_ref));
// Navigate to URL with refs.
test_rvh()->SendNavigate(1, url_with_ref);
// Reloading the page is not an in-page navigation.
EXPECT_FALSE(controller.IsURLInPageNavigation(url_with_ref));
EXPECT_FALSE(controller.IsURLInPageNavigation(url));
EXPECT_FALSE(controller.IsURLInPageNavigation(other_url));
const GURL other_url_with_ref("http://www.google.com/home.html#my_other_ref");
EXPECT_TRUE(controller.IsURLInPageNavigation(other_url_with_ref));
// Going to the same url again will be considered in-page
// if the renderer says it is even if the navigation type isn't IN_PAGE.
EXPECT_TRUE(controller.IsURLInPageNavigation(url_with_ref, true,
NAVIGATION_TYPE_UNKNOWN));
// Going back to the non ref url will be considered in-page if the navigation
// type is IN_PAGE.
EXPECT_TRUE(controller.IsURLInPageNavigation(url, true,
NAVIGATION_TYPE_IN_PAGE));
}
// Some pages can have subframes with the same base URL (minus the reference) as
// the main page. Even though this is hard, it can happen, and we don't want
// these subframe navigations to affect the toplevel document. They should
// instead be ignored. http://crbug.com/5585
TEST_F(NavigationControllerTest, SameSubframe) {
NavigationControllerImpl& controller = controller_impl();
// Navigate the main frame.
const GURL url("http://www.google.com/");
test_rvh()->SendNavigate(0, url);
// We should be at the first navigation entry.
EXPECT_EQ(controller.GetEntryCount(), 1);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 0);
// Navigate a subframe that would normally count as in-page.
const GURL subframe("http://www.google.com/#");
ViewHostMsg_FrameNavigate_Params params;
params.page_id = 0;
params.url = subframe;
params.transition = PAGE_TRANSITION_AUTO_SUBFRAME;
params.should_update_history = false;
params.gesture = NavigationGestureAuto;
params.is_post = false;
params.page_state = PageState::CreateFromURL(subframe);
LoadCommittedDetails details;
EXPECT_FALSE(controller.RendererDidNavigate(params, &details));
// Nothing should have changed.
EXPECT_EQ(controller.GetEntryCount(), 1);
EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 0);
}
// Make sure that on cloning a WebContentsImpl and going back needs_reload is
// false.
TEST_F(NavigationControllerTest, CloneAndGoBack) {
NavigationControllerImpl& controller = controller_impl();
const GURL url1("http://foo1");
const GURL url2("http://foo2");
const string16 title(ASCIIToUTF16("Title"));
NavigateAndCommit(url1);
controller.GetActiveEntry()->SetTitle(title);
NavigateAndCommit(url2);
scoped_ptr<WebContents> clone(controller.GetWebContents()->Clone());
ASSERT_EQ(2, clone->GetController().GetEntryCount());
EXPECT_TRUE(clone->GetController().NeedsReload());
clone->GetController().GoBack();
// Navigating back should have triggered needs_reload_ to go false.
EXPECT_FALSE(clone->GetController().NeedsReload());
// Ensure that the pending URL and its title are visible.
EXPECT_EQ(url1, clone->GetController().GetVisibleEntry()->GetURL());
EXPECT_EQ(title, clone->GetTitle());
}
// Make sure that reloading a cloned tab doesn't change its pending entry index.
// See http://crbug.com/234491.
TEST_F(NavigationControllerTest, CloneAndReload) {
NavigationControllerImpl& controller = controller_impl();
const GURL url1("http://foo1");
const GURL url2("http://foo2");
const string16 title(ASCIIToUTF16("Title"));
NavigateAndCommit(url1);
controller.GetActiveEntry()->SetTitle(title);
NavigateAndCommit(url2);
scoped_ptr<WebContents> clone(controller.GetWebContents()->Clone());
clone->GetController().LoadIfNecessary();
ASSERT_EQ(2, clone->GetController().GetEntryCount());
EXPECT_EQ(1, clone->GetController().GetPendingEntryIndex());
clone->GetController().Reload(true);
EXPECT_EQ(1, clone->GetController().GetPendingEntryIndex());
}
// Make sure that cloning a WebContentsImpl doesn't copy interstitials.
TEST_F(NavigationControllerTest, CloneOmitsInterstitials) {
NavigationControllerImpl& controller = controller_impl();
const GURL url1("http://foo1");
const GURL url2("http://foo2");
NavigateAndCommit(url1);
NavigateAndCommit(url2);
// Add an interstitial entry. Should be deleted with controller.
NavigationEntryImpl* interstitial_entry = new NavigationEntryImpl();
interstitial_entry->set_page_type(PAGE_TYPE_INTERSTITIAL);
controller.SetTransientEntry(interstitial_entry);
scoped_ptr<WebContents> clone(controller.GetWebContents()->Clone());
ASSERT_EQ(2, clone->GetController().GetEntryCount());
}
// Tests a subframe navigation while a toplevel navigation is pending.
// http://crbug.com/43967
TEST_F(NavigationControllerTest, SubframeWhilePending) {
NavigationControllerImpl& controller = controller_impl();
// Load the first page.
const GURL url1("http://foo/");
NavigateAndCommit(url1);
// Now start a pending load to a totally different page, but don't commit it.
const GURL url2("http://bar/");
controller.LoadURL(
url2, Referrer(), PAGE_TRANSITION_TYPED, std::string());
// Send a subframe update from the first page, as if one had just
// automatically loaded. Auto subframes don't increment the page ID.
const GURL url1_sub("http://foo/subframe");
ViewHostMsg_FrameNavigate_Params params;
params.page_id = controller.GetLastCommittedEntry()->GetPageID();
params.url = url1_sub;
params.transition = PAGE_TRANSITION_AUTO_SUBFRAME;
params.should_update_history = false;
params.gesture = NavigationGestureAuto;
params.is_post = false;
params.page_state = PageState::CreateFromURL(url1_sub);
LoadCommittedDetails details;
// This should return false meaning that nothing was actually updated.
EXPECT_FALSE(controller.RendererDidNavigate(params, &details));
// The notification should have updated the last committed one, and not
// the pending load.
EXPECT_EQ(url1, controller.GetLastCommittedEntry()->GetURL());
// The active entry should be unchanged by the subframe load.
EXPECT_EQ(url2, controller.GetActiveEntry()->GetURL());
}
// Test CopyStateFrom with 2 urls, the first selected and nothing in the target.
TEST_F(NavigationControllerTest, CopyStateFrom) {
NavigationControllerImpl& controller = controller_impl();
const GURL url1("http://foo1");
const GURL url2("http://foo2");
NavigateAndCommit(url1);
NavigateAndCommit(url2);
controller.GoBack();
contents()->CommitPendingNavigation();
scoped_ptr<TestWebContents> other_contents(
static_cast<TestWebContents*>(CreateTestWebContents()));
NavigationControllerImpl& other_controller = other_contents->GetController();
other_controller.CopyStateFrom(controller);
// other_controller should now contain 2 urls.
ASSERT_EQ(2, other_controller.GetEntryCount());
// We should be looking at the first one.
ASSERT_EQ(0, other_controller.GetCurrentEntryIndex());
EXPECT_EQ(url1, other_controller.GetEntryAtIndex(0)->GetURL());
EXPECT_EQ(0, other_controller.GetEntryAtIndex(0)->GetPageID());
EXPECT_EQ(url2, other_controller.GetEntryAtIndex(1)->GetURL());
// This is a different site than url1, so the IDs start again at 0.
EXPECT_EQ(0, other_controller.GetEntryAtIndex(1)->GetPageID());
// The max page ID map should be copied over and updated with the max page ID
// from the current tab.
SiteInstance* instance1 =
GetSiteInstanceFromEntry(other_controller.GetEntryAtIndex(0));
EXPECT_EQ(0, other_contents->GetMaxPageIDForSiteInstance(instance1));
// Ensure the SessionStorageNamespaceMaps are the same size and have
// the same partitons loaded.
//
// TODO(ajwong): We should load a url from a different partition earlier
// to make sure this map has more than one entry.
const SessionStorageNamespaceMap& session_storage_namespace_map =
controller.GetSessionStorageNamespaceMap();
const SessionStorageNamespaceMap& other_session_storage_namespace_map =
other_controller.GetSessionStorageNamespaceMap();
EXPECT_EQ(session_storage_namespace_map.size(),
other_session_storage_namespace_map.size());
for (SessionStorageNamespaceMap::const_iterator it =
session_storage_namespace_map.begin();
it != session_storage_namespace_map.end();
++it) {
SessionStorageNamespaceMap::const_iterator other =
other_session_storage_namespace_map.find(it->first);
EXPECT_TRUE(other != other_session_storage_namespace_map.end());
}
}
// Tests CopyStateFromAndPrune with 2 urls in source, 1 in dest.
TEST_F(NavigationControllerTest, CopyStateFromAndPrune) {
NavigationControllerImpl& controller = controller_impl();
const GURL url1("http://foo/1");
const GURL url2("http://foo/2");
const GURL url3("http://foo/3");
NavigateAndCommit(url1);
NavigateAndCommit(url2);
// First two entries should have the same SiteInstance.
SiteInstance* instance1 =
GetSiteInstanceFromEntry(controller.GetEntryAtIndex(0));
SiteInstance* instance2 =
GetSiteInstanceFromEntry(controller.GetEntryAtIndex(1));
EXPECT_EQ(instance1, instance2);
EXPECT_EQ(0, controller.GetEntryAtIndex(0)->GetPageID());
EXPECT_EQ(1, controller.GetEntryAtIndex(1)->GetPageID());
EXPECT_EQ(1, contents()->GetMaxPageIDForSiteInstance(instance1));
scoped_ptr<TestWebContents> other_contents(
static_cast<TestWebContents*>(CreateTestWebContents()));
NavigationControllerImpl& other_controller = other_contents->GetController();
other_contents->NavigateAndCommit(url3);
other_contents->ExpectSetHistoryLengthAndPrune(
GetSiteInstanceFromEntry(other_controller.GetEntryAtIndex(0)), 2,
other_controller.GetEntryAtIndex(0)->GetPageID());
other_controller.CopyStateFromAndPrune(&controller);
// other_controller should now contain the 3 urls: url1, url2 and url3.
ASSERT_EQ(3, other_controller.GetEntryCount());
ASSERT_EQ(2, other_controller.GetCurrentEntryIndex());
EXPECT_EQ(url1, other_controller.GetEntryAtIndex(0)->GetURL());
EXPECT_EQ(url2, other_controller.GetEntryAtIndex(1)->GetURL());
EXPECT_EQ(url3, other_controller.GetEntryAtIndex(2)->GetURL());
EXPECT_EQ(0, other_controller.GetEntryAtIndex(0)->GetPageID());
EXPECT_EQ(1, other_controller.GetEntryAtIndex(1)->GetPageID());
EXPECT_EQ(0, other_controller.GetEntryAtIndex(2)->GetPageID());
// A new SiteInstance should be used for the new tab.
SiteInstance* instance3 =
GetSiteInstanceFromEntry(other_controller.GetEntryAtIndex(2));
EXPECT_NE(instance3, instance1);
// The max page ID map should be copied over and updated with the max page ID
// from the current tab.
EXPECT_EQ(1, other_contents->GetMaxPageIDForSiteInstance(instance1));
EXPECT_EQ(0, other_contents->GetMaxPageIDForSiteInstance(instance3));
}
// Test CopyStateFromAndPrune with 2 urls, the first selected and 1 entry in
// the target.
TEST_F(NavigationControllerTest, CopyStateFromAndPrune2) {
NavigationControllerImpl& controller = controller_impl();
const GURL url1("http://foo1");
const GURL url2("http://foo2");
const GURL url3("http://foo3");
NavigateAndCommit(url1);
NavigateAndCommit(url2);
controller.GoBack();
contents()->CommitPendingNavigation();
scoped_ptr<TestWebContents> other_contents(
static_cast<TestWebContents*>(CreateTestWebContents()));
NavigationControllerImpl& other_controller = other_contents->GetController();
other_contents->NavigateAndCommit(url3);
other_contents->ExpectSetHistoryLengthAndPrune(
GetSiteInstanceFromEntry(other_controller.GetEntryAtIndex(0)), 1,
other_controller.GetEntryAtIndex(0)->GetPageID());
other_controller.CopyStateFromAndPrune(&controller);
// other_controller should now contain: url1, url3
ASSERT_EQ(2, other_controller.GetEntryCount());
ASSERT_EQ(1, other_controller.GetCurrentEntryIndex());
EXPECT_EQ(url1, other_controller.GetEntryAtIndex(0)->GetURL());
EXPECT_EQ(url3, other_controller.GetEntryAtIndex(1)->GetURL());
EXPECT_EQ(0, other_controller.GetEntryAtIndex(1)->GetPageID());
// The max page ID map should be copied over and updated with the max page ID
// from the current tab.
SiteInstance* instance1 =
GetSiteInstanceFromEntry(other_controller.GetEntryAtIndex(1));
EXPECT_EQ(0, other_contents->GetMaxPageIDForSiteInstance(instance1));
}
// Test CopyStateFromAndPrune with 2 urls, the last selected and 2 entries in
// the target.
TEST_F(NavigationControllerTest, CopyStateFromAndPrune3) {
NavigationControllerImpl& controller = controller_impl();
const GURL url1("http://foo1");
const GURL url2("http://foo2");
const GURL url3("http://foo3");
const GURL url4("http://foo4");
NavigateAndCommit(url1);
NavigateAndCommit(url2);
scoped_ptr<TestWebContents> other_contents(
static_cast<TestWebContents*>(CreateTestWebContents()));
NavigationControllerImpl& other_controller = other_contents->GetController();
other_contents->NavigateAndCommit(url3);
other_contents->NavigateAndCommit(url4);
other_contents->ExpectSetHistoryLengthAndPrune(
GetSiteInstanceFromEntry(other_controller.GetEntryAtIndex(1)), 2,
other_controller.GetEntryAtIndex(0)->GetPageID());
other_controller.CopyStateFromAndPrune(&controller);
// other_controller should now contain: url1, url2, url4
ASSERT_EQ(3, other_controller.GetEntryCount());
ASSERT_EQ(2, other_controller.GetCurrentEntryIndex());
EXPECT_EQ(url1, other_controller.GetEntryAtIndex(0)->GetURL());
EXPECT_EQ(url2, other_controller.GetEntryAtIndex(1)->GetURL());
EXPECT_EQ(url4, other_controller.GetEntryAtIndex(2)->GetURL());
// The max page ID map should be copied over and updated with the max page ID
// from the current tab.
SiteInstance* instance1 =
GetSiteInstanceFromEntry(other_controller.GetEntryAtIndex(2));
EXPECT_EQ(0, other_contents->GetMaxPageIDForSiteInstance(instance1));
}
// Test CopyStateFromAndPrune with 2 urls, 2 entries in the target, with
// not the last entry selected in the target.
TEST_F(NavigationControllerTest, CopyStateFromAndPruneNotLast) {
NavigationControllerImpl& controller = controller_impl();
const GURL url1("http://foo1");
const GURL url2("http://foo2");
const GURL url3("http://foo3");
const GURL url4("http://foo4");
NavigateAndCommit(url1);
NavigateAndCommit(url2);
scoped_ptr<TestWebContents> other_contents(
static_cast<TestWebContents*>(CreateTestWebContents()));
NavigationControllerImpl& other_controller = other_contents->GetController();
other_contents->NavigateAndCommit(url3);
other_contents->NavigateAndCommit(url4);
other_controller.GoBack();
other_contents->CommitPendingNavigation();
other_contents->ExpectSetHistoryLengthAndPrune(
GetSiteInstanceFromEntry(other_controller.GetEntryAtIndex(0)), 2,
other_controller.GetEntryAtIndex(0)->GetPageID());
other_controller.CopyStateFromAndPrune(&controller);
// other_controller should now contain: url1, url2, url3
ASSERT_EQ(3, other_controller.GetEntryCount());
ASSERT_EQ(2, other_controller.GetCurrentEntryIndex());
EXPECT_EQ(url1, other_controller.GetEntryAtIndex(0)->GetURL());
EXPECT_EQ(url2, other_controller.GetEntryAtIndex(1)->GetURL());
EXPECT_EQ(url3, other_controller.GetEntryAtIndex(2)->GetURL());
// The max page ID map should be copied over and updated with the max page ID
// from the current tab.
SiteInstance* instance1 =
GetSiteInstanceFromEntry(other_controller.GetEntryAtIndex(2));
EXPECT_EQ(0, other_contents->GetMaxPageIDForSiteInstance(instance1));
}
// Test CopyStateFromAndPrune with 2 urls, the first selected and 1 entry plus
// a pending entry in the target.
TEST_F(NavigationControllerTest, CopyStateFromAndPruneTargetPending) {
NavigationControllerImpl& controller = controller_impl();
const GURL url1("http://foo1");
const GURL url2("http://foo2");
const GURL url3("http://foo3");
const GURL url4("http://foo4");
NavigateAndCommit(url1);
NavigateAndCommit(url2);
controller.GoBack();
contents()->CommitPendingNavigation();
scoped_ptr<TestWebContents> other_contents(
static_cast<TestWebContents*>(CreateTestWebContents()));
NavigationControllerImpl& other_controller = other_contents->GetController();
other_contents->NavigateAndCommit(url3);
other_controller.LoadURL(
url4, Referrer(), PAGE_TRANSITION_TYPED, std::string());
other_contents->ExpectSetHistoryLengthAndPrune(
GetSiteInstanceFromEntry(other_controller.GetEntryAtIndex(0)), 1,
other_controller.GetEntryAtIndex(0)->GetPageID());
other_controller.CopyStateFromAndPrune(&controller);
// other_controller should now contain url1, url3, and a pending entry
// for url4.
ASSERT_EQ(2, other_controller.GetEntryCount());
EXPECT_EQ(1, other_controller.GetCurrentEntryIndex());
EXPECT_EQ(url1, other_controller.GetEntryAtIndex(0)->GetURL());
EXPECT_EQ(url3, other_controller.GetEntryAtIndex(1)->GetURL());
// And there should be a pending entry for url4.
ASSERT_TRUE(other_controller.GetPendingEntry());
EXPECT_EQ(url4, other_controller.GetPendingEntry()->GetURL());
// The max page ID map should be copied over and updated with the max page ID
// from the current tab.
SiteInstance* instance1 =
GetSiteInstanceFromEntry(other_controller.GetEntryAtIndex(0));
EXPECT_EQ(0, other_contents->GetMaxPageIDForSiteInstance(instance1));
}
// Test CopyStateFromAndPrune with 1 url in the source, 1 entry and a pending
// client redirect entry (with the same page ID) in the target. This used to
// crash because the last committed entry would be pruned but max_page_id
// remembered the page ID (http://crbug.com/234809).
TEST_F(NavigationControllerTest, CopyStateFromAndPruneTargetPending2) {
NavigationControllerImpl& controller = controller_impl();
const GURL url1("http://foo1");
const GURL url2a("http://foo2/a");
const GURL url2b("http://foo2/b");
NavigateAndCommit(url1);
scoped_ptr<TestWebContents> other_contents(
static_cast<TestWebContents*>(CreateTestWebContents()));
NavigationControllerImpl& other_controller = other_contents->GetController();
other_contents->NavigateAndCommit(url2a);
// Simulate a client redirect, which has the same page ID as entry 2a.
other_controller.LoadURL(
url2b, Referrer(), PAGE_TRANSITION_LINK, std::string());
other_controller.GetPendingEntry()->SetPageID(
other_controller.GetLastCommittedEntry()->GetPageID());
other_contents->ExpectSetHistoryLengthAndPrune(
GetSiteInstanceFromEntry(other_controller.GetEntryAtIndex(0)), 1,
other_controller.GetEntryAtIndex(0)->GetPageID());
other_controller.CopyStateFromAndPrune(&controller);
// other_controller should now contain url1, url2a, and a pending entry
// for url2b.
ASSERT_EQ(2, other_controller.GetEntryCount());
EXPECT_EQ(1, other_controller.GetCurrentEntryIndex());
EXPECT_EQ(url1, other_controller.GetEntryAtIndex(0)->GetURL());
EXPECT_EQ(url2a, other_controller.GetEntryAtIndex(1)->GetURL());
// And there should be a pending entry for url4.
ASSERT_TRUE(other_controller.GetPendingEntry());
EXPECT_EQ(url2b, other_controller.GetPendingEntry()->GetURL());
// Let the pending entry commit.
other_contents->CommitPendingNavigation();
// The max page ID map should be copied over and updated with the max page ID
// from the current tab.
SiteInstance* instance1 =
GetSiteInstanceFromEntry(other_controller.GetEntryAtIndex(1));
EXPECT_EQ(0, other_contents->GetMaxPageIDForSiteInstance(instance1));
}
// Test CopyStateFromAndPrune with 2 urls, a back navigation pending in the
// source, and 1 entry in the target. The back pending entry should be ignored.
TEST_F(NavigationControllerTest, CopyStateFromAndPruneSourcePending) {
NavigationControllerImpl& controller = controller_impl();
const GURL url1("http://foo1");
const GURL url2("http://foo2");
const GURL url3("http://foo3");
NavigateAndCommit(url1);
NavigateAndCommit(url2);
controller.GoBack();
scoped_ptr<TestWebContents> other_contents(
static_cast<TestWebContents*>(CreateTestWebContents()));
NavigationControllerImpl& other_controller = other_contents->GetController();
other_contents->NavigateAndCommit(url3);
other_contents->ExpectSetHistoryLengthAndPrune(
GetSiteInstanceFromEntry(other_controller.GetEntryAtIndex(0)), 2,
other_controller.GetEntryAtIndex(0)->GetPageID());
other_controller.CopyStateFromAndPrune(&controller);
// other_controller should now contain: url1, url2, url3
ASSERT_EQ(3, other_controller.GetEntryCount());
ASSERT_EQ(2, other_controller.GetCurrentEntryIndex());
EXPECT_EQ(url1, other_controller.GetEntryAtIndex(0)->GetURL());
EXPECT_EQ(url2, other_controller.GetEntryAtIndex(1)->GetURL());
EXPECT_EQ(url3, other_controller.GetEntryAtIndex(2)->GetURL());
EXPECT_EQ(0, other_controller.GetEntryAtIndex(2)->GetPageID());
// The max page ID map should be copied over and updated with the max page ID
// from the current tab.
SiteInstance* instance1 =
GetSiteInstanceFromEntry(other_controller.GetEntryAtIndex(2));
EXPECT_EQ(0, other_contents->GetMaxPageIDForSiteInstance(instance1));
}
// Tests CopyStateFromAndPrune with 3 urls in source, 1 in dest,
// when the max entry count is 3. We should prune one entry.
TEST_F(NavigationControllerTest, CopyStateFromAndPruneMaxEntries) {
NavigationControllerImpl& controller = controller_impl();
size_t original_count = NavigationControllerImpl::max_entry_count();
const int kMaxEntryCount = 3;
NavigationControllerImpl::set_max_entry_count_for_testing(kMaxEntryCount);
const GURL url1("http://foo/1");
const GURL url2("http://foo/2");
const GURL url3("http://foo/3");
const GURL url4("http://foo/4");
// Create a PrunedListener to observe prune notifications.
PrunedListener listener(&controller);
NavigateAndCommit(url1);
NavigateAndCommit(url2);
NavigateAndCommit(url3);
scoped_ptr<TestWebContents> other_contents(
static_cast<TestWebContents*>(CreateTestWebContents()));
NavigationControllerImpl& other_controller = other_contents->GetController();
other_contents->NavigateAndCommit(url4);
other_contents->ExpectSetHistoryLengthAndPrune(
GetSiteInstanceFromEntry(other_controller.GetEntryAtIndex(0)), 2,
other_controller.GetEntryAtIndex(0)->GetPageID());
other_controller.CopyStateFromAndPrune(&controller);
// We should have received a pruned notification.
EXPECT_EQ(1, listener.notification_count_);
EXPECT_TRUE(listener.details_.from_front);
EXPECT_EQ(1, listener.details_.count);
// other_controller should now contain only 3 urls: url2, url3 and url4.
ASSERT_EQ(3, other_controller.GetEntryCount());
ASSERT_EQ(2, other_controller.GetCurrentEntryIndex());
EXPECT_EQ(url2, other_controller.GetEntryAtIndex(0)->GetURL());
EXPECT_EQ(url3, other_controller.GetEntryAtIndex(1)->GetURL());
EXPECT_EQ(url4, other_controller.GetEntryAtIndex(2)->GetURL());
EXPECT_EQ(1, other_controller.GetEntryAtIndex(0)->GetPageID());
EXPECT_EQ(2, other_controller.GetEntryAtIndex(1)->GetPageID());
EXPECT_EQ(0, other_controller.GetEntryAtIndex(2)->GetPageID());
NavigationControllerImpl::set_max_entry_count_for_testing(original_count);
}
// Tests that navigations initiated from the page (with the history object)
// work as expected without navigation entries.
TEST_F(NavigationControllerTest, HistoryNavigate) {
NavigationControllerImpl& controller = controller_impl();
const GURL url1("http://foo/1");
const GURL url2("http://foo/2");
const GURL url3("http://foo/3");
NavigateAndCommit(url1);
NavigateAndCommit(url2);
NavigateAndCommit(url3);
controller.GoBack();
contents()->CommitPendingNavigation();
// Simulate the page calling history.back(), it should not create a pending
// entry.
contents()->OnGoToEntryAtOffset(-1);
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
// The actual cross-navigation is suspended until the current RVH tells us
// it unloaded, simulate that.
contents()->ProceedWithCrossSiteNavigation();
// Also make sure we told the page to navigate.
const IPC::Message* message =
process()->sink().GetFirstMessageMatching(ViewMsg_Navigate::ID);
ASSERT_TRUE(message != NULL);
Tuple1<ViewMsg_Navigate_Params> nav_params;
ViewMsg_Navigate::Read(message, &nav_params);
EXPECT_EQ(url1, nav_params.a.url);
process()->sink().ClearMessages();
// Now test history.forward()
contents()->OnGoToEntryAtOffset(1);
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
// The actual cross-navigation is suspended until the current RVH tells us
// it unloaded, simulate that.
contents()->ProceedWithCrossSiteNavigation();
message = process()->sink().GetFirstMessageMatching(ViewMsg_Navigate::ID);
ASSERT_TRUE(message != NULL);
ViewMsg_Navigate::Read(message, &nav_params);
EXPECT_EQ(url3, nav_params.a.url);
process()->sink().ClearMessages();
// Make sure an extravagant history.go() doesn't break.
contents()->OnGoToEntryAtOffset(120); // Out of bounds.
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
message = process()->sink().GetFirstMessageMatching(ViewMsg_Navigate::ID);
EXPECT_TRUE(message == NULL);
}
// Test call to PruneAllButVisible for the only entry.
TEST_F(NavigationControllerTest, PruneAllButVisibleForSingle) {
NavigationControllerImpl& controller = controller_impl();
const GURL url1("http://foo1");
NavigateAndCommit(url1);
contents()->ExpectSetHistoryLengthAndPrune(
GetSiteInstanceFromEntry(controller.GetEntryAtIndex(0)), 0,
controller.GetEntryAtIndex(0)->GetPageID());
controller.PruneAllButVisible();
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
EXPECT_EQ(controller.GetEntryAtIndex(0)->GetURL(), url1);
}
// Test call to PruneAllButVisible for first entry.
TEST_F(NavigationControllerTest, PruneAllButVisibleForFirst) {
NavigationControllerImpl& controller = controller_impl();
const GURL url1("http://foo/1");
const GURL url2("http://foo/2");
const GURL url3("http://foo/3");
NavigateAndCommit(url1);
NavigateAndCommit(url2);
NavigateAndCommit(url3);
controller.GoBack();
controller.GoBack();
contents()->CommitPendingNavigation();
contents()->ExpectSetHistoryLengthAndPrune(
GetSiteInstanceFromEntry(controller.GetEntryAtIndex(0)), 0,
controller.GetEntryAtIndex(0)->GetPageID());
controller.PruneAllButVisible();
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
EXPECT_EQ(controller.GetEntryAtIndex(0)->GetURL(), url1);
}
// Test call to PruneAllButVisible for intermediate entry.
TEST_F(NavigationControllerTest, PruneAllButVisibleForIntermediate) {
NavigationControllerImpl& controller = controller_impl();
const GURL url1("http://foo/1");
const GURL url2("http://foo/2");
const GURL url3("http://foo/3");
NavigateAndCommit(url1);
NavigateAndCommit(url2);
NavigateAndCommit(url3);
controller.GoBack();
contents()->CommitPendingNavigation();
contents()->ExpectSetHistoryLengthAndPrune(
GetSiteInstanceFromEntry(controller.GetEntryAtIndex(1)), 0,
controller.GetEntryAtIndex(1)->GetPageID());
controller.PruneAllButVisible();
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
EXPECT_EQ(controller.GetEntryAtIndex(0)->GetURL(), url2);
}
// Test call to PruneAllButVisible for a pending entry that is not yet in the
// list of entries.
TEST_F(NavigationControllerTest, PruneAllButVisibleForPendingNotInList) {
NavigationControllerImpl& controller = controller_impl();
const GURL url1("http://foo/1");
const GURL url2("http://foo/2");
const GURL url3("http://foo/3");
NavigateAndCommit(url1);
NavigateAndCommit(url2);
// Create a pending entry that is not in the entry list.
controller.LoadURL(
url3, Referrer(), PAGE_TRANSITION_TYPED, std::string());
EXPECT_TRUE(controller.GetPendingEntry());
EXPECT_EQ(2, controller.GetEntryCount());
contents()->ExpectSetHistoryLengthAndPrune(
NULL, 0, controller.GetPendingEntry()->GetPageID());
controller.PruneAllButVisible();
// We should only have the last committed and pending entries at this point,
// and the pending entry should still not be in the entry list.
EXPECT_EQ(0, controller.GetLastCommittedEntryIndex());
EXPECT_EQ(url2, controller.GetEntryAtIndex(0)->GetURL());
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
EXPECT_TRUE(controller.GetPendingEntry());
EXPECT_EQ(1, controller.GetEntryCount());
// Try to commit the pending entry.
test_rvh()->SendNavigate(2, url3);
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
EXPECT_FALSE(controller.GetPendingEntry());
EXPECT_EQ(2, controller.GetEntryCount());
EXPECT_EQ(url3, controller.GetEntryAtIndex(1)->GetURL());
}
// Test to ensure that when we do a history navigation back to the current
// committed page (e.g., going forward to a slow-loading page, then pressing
// the back button), we just stop the navigation to prevent the throbber from
// running continuously. Otherwise, the RenderViewHost forces the throbber to
// start, but WebKit essentially ignores the navigation and never sends a
// message to stop the throbber.
TEST_F(NavigationControllerTest, StopOnHistoryNavigationToCurrentPage) {
NavigationControllerImpl& controller = controller_impl();
const GURL url0("http://foo/0");
const GURL url1("http://foo/1");
NavigateAndCommit(url0);
NavigateAndCommit(url1);
// Go back to the original page, then forward to the slow page, then back
controller.GoBack();
contents()->CommitPendingNavigation();
controller.GoForward();
EXPECT_EQ(1, controller.GetPendingEntryIndex());
controller.GoBack();
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
}
TEST_F(NavigationControllerTest, IsInitialNavigation) {
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
// Initial state.
EXPECT_TRUE(controller.IsInitialNavigation());
// After commit, it stays false.
const GURL url1("http://foo1");
test_rvh()->SendNavigate(0, url1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
EXPECT_FALSE(controller.IsInitialNavigation());
// After starting a new navigation, it stays false.
const GURL url2("http://foo2");
controller.LoadURL(
url2, Referrer(), PAGE_TRANSITION_TYPED, std::string());
}
// Check that the favicon is not reused across a client redirect.
// (crbug.com/28515)
TEST_F(NavigationControllerTest, ClearFaviconOnRedirect) {
const GURL kPageWithFavicon("http://withfavicon.html");
const GURL kPageWithoutFavicon("http://withoutfavicon.html");
const GURL kIconURL("http://withfavicon.ico");
const gfx::Image kDefaultFavicon = FaviconStatus().image;
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
test_rvh()->SendNavigate(0, kPageWithFavicon);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
NavigationEntry* entry = controller.GetLastCommittedEntry();
EXPECT_TRUE(entry);
EXPECT_EQ(kPageWithFavicon, entry->GetURL());
// Simulate Chromium having set the favicon for |kPageWithFavicon|.
content::FaviconStatus& favicon_status = entry->GetFavicon();
favicon_status.image = CreateImage(SK_ColorWHITE);
favicon_status.url = kIconURL;
favicon_status.valid = true;
EXPECT_FALSE(DoImagesMatch(kDefaultFavicon, entry->GetFavicon().image));
test_rvh()->SendNavigateWithTransition(
0, // same page ID.
kPageWithoutFavicon,
PAGE_TRANSITION_CLIENT_REDIRECT);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
entry = controller.GetLastCommittedEntry();
EXPECT_TRUE(entry);
EXPECT_EQ(kPageWithoutFavicon, entry->GetURL());
EXPECT_TRUE(DoImagesMatch(kDefaultFavicon, entry->GetFavicon().image));
}
// Check that the favicon is not cleared for NavigationEntries which were
// previously navigated to.
TEST_F(NavigationControllerTest, BackNavigationDoesNotClearFavicon) {
const GURL kUrl1("http://www.a.com/1");
const GURL kUrl2("http://www.a.com/2");
const GURL kIconURL("http://www.a.com/1/favicon.ico");
NavigationControllerImpl& controller = controller_impl();
TestNotificationTracker notifications;
RegisterForAllNavNotifications(¬ifications, &controller);
test_rvh()->SendNavigate(0, kUrl1);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// Simulate Chromium having set the favicon for |kUrl1|.
gfx::Image favicon_image = CreateImage(SK_ColorWHITE);
content::NavigationEntry* entry = controller.GetLastCommittedEntry();
EXPECT_TRUE(entry);
content::FaviconStatus& favicon_status = entry->GetFavicon();
favicon_status.image = favicon_image;
favicon_status.url = kIconURL;
favicon_status.valid = true;
// Navigate to another page and go back to the original page.
test_rvh()->SendNavigate(1, kUrl2);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
test_rvh()->SendNavigateWithTransition(
0,
kUrl1,
PAGE_TRANSITION_FORWARD_BACK);
EXPECT_EQ(1U, navigation_entry_committed_counter_);
navigation_entry_committed_counter_ = 0;
// Verify that the favicon for the page at |kUrl1| was not cleared.
entry = controller.GetEntryAtIndex(0);
EXPECT_TRUE(entry);
EXPECT_EQ(kUrl1, entry->GetURL());
EXPECT_TRUE(DoImagesMatch(favicon_image, entry->GetFavicon().image));
}
// The test crashes on android: http://crbug.com/170449
#if defined(OS_ANDROID)
#define MAYBE_PurgeScreenshot DISABLED_PurgeScreenshot
#else
#define MAYBE_PurgeScreenshot PurgeScreenshot
#endif
// Tests that screenshot are purged correctly.
TEST_F(NavigationControllerTest, MAYBE_PurgeScreenshot) {
NavigationControllerImpl& controller = controller_impl();
NavigationEntryImpl* entry;
// Navigate enough times to make sure that some screenshots are purged.
for (int i = 0; i < 12; ++i) {
const GURL url(base::StringPrintf("http://foo%d/", i));
NavigateAndCommit(url);
EXPECT_EQ(i, controller.GetCurrentEntryIndex());
}
MockScreenshotManager* screenshot_manager =
new MockScreenshotManager(&controller);
controller.SetScreenshotManager(screenshot_manager);
for (int i = 0; i < controller.GetEntryCount(); ++i) {
entry = NavigationEntryImpl::FromNavigationEntry(
controller.GetEntryAtIndex(i));
screenshot_manager->TakeScreenshotFor(entry);
EXPECT_TRUE(entry->screenshot().get());
}
NavigateAndCommit(GURL("https://foo/"));
EXPECT_EQ(13, controller.GetEntryCount());
entry = NavigationEntryImpl::FromNavigationEntry(
controller.GetEntryAtIndex(11));
screenshot_manager->TakeScreenshotFor(entry);
for (int i = 0; i < 2; ++i) {
entry = NavigationEntryImpl::FromNavigationEntry(
controller.GetEntryAtIndex(i));
EXPECT_FALSE(entry->screenshot().get()) << "Screenshot " << i
<< " not purged";
}
for (int i = 2; i < controller.GetEntryCount() - 1; ++i) {
entry = NavigationEntryImpl::FromNavigationEntry(
controller.GetEntryAtIndex(i));
EXPECT_TRUE(entry->screenshot().get()) << "Screenshot not found for " << i;
}
// Navigate to index 5 and then try to assign screenshot to all entries.
controller.GoToIndex(5);
contents()->CommitPendingNavigation();
EXPECT_EQ(5, controller.GetCurrentEntryIndex());
for (int i = 0; i < controller.GetEntryCount() - 1; ++i) {
entry = NavigationEntryImpl::FromNavigationEntry(
controller.GetEntryAtIndex(i));
screenshot_manager->TakeScreenshotFor(entry);
}
for (int i = 10; i <= 12; ++i) {
entry = NavigationEntryImpl::FromNavigationEntry(
controller.GetEntryAtIndex(i));
EXPECT_FALSE(entry->screenshot().get()) << "Screenshot " << i
<< " not purged";
screenshot_manager->TakeScreenshotFor(entry);
}
// Navigate to index 7 and assign screenshot to all entries.
controller.GoToIndex(7);
contents()->CommitPendingNavigation();
EXPECT_EQ(7, controller.GetCurrentEntryIndex());
for (int i = 0; i < controller.GetEntryCount() - 1; ++i) {
entry = NavigationEntryImpl::FromNavigationEntry(
controller.GetEntryAtIndex(i));
screenshot_manager->TakeScreenshotFor(entry);
}
for (int i = 0; i < 2; ++i) {
entry = NavigationEntryImpl::FromNavigationEntry(
controller.GetEntryAtIndex(i));
EXPECT_FALSE(entry->screenshot().get()) << "Screenshot " << i
<< " not purged";
}
// Clear all screenshots.
EXPECT_EQ(13, controller.GetEntryCount());
EXPECT_EQ(10, screenshot_manager->GetScreenshotCount());
controller.ClearAllScreenshots();
EXPECT_EQ(0, screenshot_manager->GetScreenshotCount());
for (int i = 0; i < controller.GetEntryCount(); ++i) {
entry = NavigationEntryImpl::FromNavigationEntry(
controller.GetEntryAtIndex(i));
EXPECT_FALSE(entry->screenshot().get()) << "Screenshot " << i
<< " not cleared";
}
}
// Test that the navigation controller clears its session history when a
// navigation commits with the clear history list flag set.
TEST_F(NavigationControllerTest, ClearHistoryList) {
const GURL url1("http://foo1");
const GURL url2("http://foo2");
const GURL url3("http://foo3");
const GURL url4("http://foo4");
NavigationControllerImpl& controller = controller_impl();
// Create a session history with three entries, second entry is active.
NavigateAndCommit(url1);
NavigateAndCommit(url2);
NavigateAndCommit(url3);
controller.GoBack();
contents()->CommitPendingNavigation();
EXPECT_EQ(3, controller.GetEntryCount());
EXPECT_EQ(1, controller.GetCurrentEntryIndex());
// Create a new pending navigation, and indicate that the session history
// should be cleared.
NavigationController::LoadURLParams params(url4);
params.should_clear_history_list = true;
controller.LoadURLWithParams(params);
// Verify that the pending entry correctly indicates that the session history
// should be cleared.
NavigationEntryImpl* entry =
NavigationEntryImpl::FromNavigationEntry(
controller.GetPendingEntry());
ASSERT_TRUE(entry);
EXPECT_TRUE(entry->should_clear_history_list());
// Assume that the RV correctly cleared its history and commit the navigation.
static_cast<TestRenderViewHost*>(contents()->GetPendingRenderViewHost())->
set_simulate_history_list_was_cleared(true);
contents()->CommitPendingNavigation();
// Verify that the NavigationController's session history was correctly
// cleared.
EXPECT_EQ(1, controller.GetEntryCount());
EXPECT_EQ(0, controller.GetCurrentEntryIndex());
EXPECT_EQ(0, controller.GetLastCommittedEntryIndex());
EXPECT_EQ(-1, controller.GetPendingEntryIndex());
EXPECT_FALSE(controller.CanGoBack());
EXPECT_FALSE(controller.CanGoForward());
EXPECT_EQ(url4, controller.GetActiveEntry()->GetURL());
}
/* TODO(brettw) These test pass on my local machine but fail on the XP buildbot
(but not Vista) cleaning up the directory after they run.
This should be fixed.
// NavigationControllerHistoryTest ---------------------------------------------
class NavigationControllerHistoryTest : public NavigationControllerTest {
public:
NavigationControllerHistoryTest()
: url0("http://foo1"),
url1("http://foo1"),
url2("http://foo1"),
profile_manager_(NULL) {
}
virtual ~NavigationControllerHistoryTest() {
// Prevent our base class from deleting the profile since profile's
// lifetime is managed by profile_manager_.
STLDeleteElements(&windows_);
}
// testing::Test overrides.
virtual void SetUp() {
NavigationControllerTest::SetUp();
// Force the session service to be created.
SessionService* service = new SessionService(profile());
SessionServiceFactory::SetForTestProfile(profile(), service);
service->SetWindowType(window_id, Browser::TYPE_TABBED);
service->SetWindowBounds(window_id, gfx::Rect(0, 1, 2, 3), false);
service->SetTabIndexInWindow(window_id,
controller.session_id(), 0);
controller.SetWindowID(window_id);
session_helper_.SetService(service);
}
virtual void TearDown() {
// Release profile's reference to the session service. Otherwise the file
// will still be open and we won't be able to delete the directory below.
session_helper_.ReleaseService(); // profile owns this
SessionServiceFactory::SetForTestProfile(profile(), NULL);
// Make sure we wait for history to shut down before continuing. The task
// we add will cause our message loop to quit once it is destroyed.
HistoryService* history = HistoryServiceFactory::GetForProfiles(
profile(), Profile::IMPLICIT_ACCESS);
if (history) {
history->SetOnBackendDestroyTask(base::MessageLoop::QuitClosure());
base::MessageLoop::current()->Run();
}
// Do normal cleanup before deleting the profile directory below.
NavigationControllerTest::TearDown();
ASSERT_TRUE(base::DeleteFile(test_dir_, true));
ASSERT_FALSE(base::PathExists(test_dir_));
}
// Deletes the current profile manager and creates a new one. Indirectly this
// shuts down the history database and reopens it.
void ReopenDatabase() {
session_helper_.SetService(NULL);
SessionServiceFactory::SetForTestProfile(profile(), NULL);
SessionService* service = new SessionService(profile());
SessionServiceFactory::SetForTestProfile(profile(), service);
session_helper_.SetService(service);
}
void GetLastSession() {
SessionServiceFactory::GetForProfile(profile())->TabClosed(
controller.window_id(), controller.session_id(), false);
ReopenDatabase();
Time close_time;
session_helper_.ReadWindows(&windows_);
}
CancelableRequestConsumer consumer;
// URLs for testing.
const GURL url0;
const GURL url1;
const GURL url2;
std::vector<SessionWindow*> windows_;
SessionID window_id;
SessionServiceTestHelper session_helper_;
private:
ProfileManager* profile_manager_;
base::FilePath test_dir_;
};
// A basic test case. Navigates to a single url, and make sure the history
// db matches.
TEST_F(NavigationControllerHistoryTest, Basic) {
NavigationControllerImpl& controller = controller_impl();
controller.LoadURL(url0, GURL(), PAGE_TRANSITION_LINK);
test_rvh()->SendNavigate(0, url0);
GetLastSession();
session_helper_.AssertSingleWindowWithSingleTab(windows_, 1);
session_helper_.AssertTabEquals(0, 0, 1, *(windows_[0]->tabs[0]));
TabNavigation nav1(0, url0, GURL(), string16(),
webkit_glue::CreateHistoryStateForURL(url0),
PAGE_TRANSITION_LINK);
session_helper_.AssertNavigationEquals(nav1,
windows_[0]->tabs[0]->navigations[0]);
}
// Navigates to three urls, then goes back and make sure the history database
// is in sync.
TEST_F(NavigationControllerHistoryTest, NavigationThenBack) {
NavigationControllerImpl& controller = controller_impl();
test_rvh()->SendNavigate(0, url0);
test_rvh()->SendNavigate(1, url1);
test_rvh()->SendNavigate(2, url2);
controller.GoBack();
test_rvh()->SendNavigate(1, url1);
GetLastSession();
session_helper_.AssertSingleWindowWithSingleTab(windows_, 3);
session_helper_.AssertTabEquals(0, 1, 3, *(windows_[0]->tabs[0]));
TabNavigation nav(0, url0, GURL(), string16(),
webkit_glue::CreateHistoryStateForURL(url0),
PAGE_TRANSITION_LINK);
session_helper_.AssertNavigationEquals(nav,
windows_[0]->tabs[0]->navigations[0]);
nav.set_url(url1);
session_helper_.AssertNavigationEquals(nav,
windows_[0]->tabs[0]->navigations[1]);
nav.set_url(url2);
session_helper_.AssertNavigationEquals(nav,
windows_[0]->tabs[0]->navigations[2]);
}
// Navigates to three urls, then goes back twice, then loads a new url.
TEST_F(NavigationControllerHistoryTest, NavigationPruning) {
NavigationControllerImpl& controller = controller_impl();
test_rvh()->SendNavigate(0, url0);
test_rvh()->SendNavigate(1, url1);
test_rvh()->SendNavigate(2, url2);
controller.GoBack();
test_rvh()->SendNavigate(1, url1);
controller.GoBack();
test_rvh()->SendNavigate(0, url0);
test_rvh()->SendNavigate(3, url2);
// Now have url0, and url2.
GetLastSession();
session_helper_.AssertSingleWindowWithSingleTab(windows_, 2);
session_helper_.AssertTabEquals(0, 1, 2, *(windows_[0]->tabs[0]));
TabNavigation nav(0, url0, GURL(), string16(),
webkit_glue::CreateHistoryStateForURL(url0),
PAGE_TRANSITION_LINK);
session_helper_.AssertNavigationEquals(nav,
windows_[0]->tabs[0]->navigations[0]);
nav.set_url(url2);
session_helper_.AssertNavigationEquals(nav,
windows_[0]->tabs[0]->navigations[1]);
}
*/
} // namespace content
|
#include <Eigen/Eigen>
#include <iostream>
#ifndef M_PI
#define M_PI 3.1415926535897932384626433832795
#endif
using namespace Eigen;
using namespace std;
int main(int, char**)
{
cout.precision(3);
Array3d v(1,-2,-3);
cout << v.abs() << endl;
return 0;
}
|
//////////////////////////////////////////////
// Cai Gwatkin //
//////////////////////////////////////////////
// This program reads in numbers from //
// text files, sorts adds them to a Heap, //
// and sorts them into ascending order //
//////////////////////////////////////////////
#include "HeapSort.h"
int main(int argc, char** argv)
{
// Check that 3 file names have been passed
if (argc != 4) return ErrorArguments(argc);
// Declare vectors
vector<int> vectorRandomOrder;
vector<int> vectorReversedOrder;
vector<int> vectorSortedOrder;
// Create vectors from files
int error = CreateVectors(argv[1], argv[2], argv[3], vectorRandomOrder, vectorReversedOrder, vectorSortedOrder);
if (error) return error;
// Heap sort all vectors and output results
HeapSortAllVectors(argv[1], argv[2], argv[3], vectorRandomOrder, vectorReversedOrder, vectorSortedOrder);
return 0;
}
// Heap construcor
Heap::Heap(unsigned int elements)
{
for (unsigned int i = 0; i < elements; i++) data.push_back(0);
last = -1;
}
// Insert a new element in the Heap
void Heap::Insert(int newElement, int &comparisons)
{
// Add newElement to the end of the Heap
last = last + 1;
data[last] = newElement;
if (last == 0) return;
// Sort Element into Heap
int childIndex = last, parentIndex = 0;
bool swapping = true;
while (swapping == true)
{
swapping = false;
// Check if right child or left child
if (childIndex % 2 == 0) parentIndex = childIndex / 2 - 1; // Right child
else parentIndex = childIndex / 2; // Left child
// Check if swapping must occur
if (parentIndex >= 0)
{
if (data[childIndex] > data[parentIndex])
{
// Swap data between child and parent
swap(data[childIndex], data[parentIndex]);
swapping = true;
childIndex = parentIndex;
}
comparisons++;
}
}
}
// Returns the value of the root element of the Heap
int Heap::RootData()
{
return data[0];
}
// Deletes the root from the Heap
void Heap::DeleteRoot(int &comparisons)
{
// Check that there are elements in the Heap
if (last < 0) return;
// Copy data[last] to data[root]
data[0] = data[last];
// Delete data[last]
data[last] = 0;
last = last - 1;
// Fix the Heap
int parentIndex = 0, leftChildIndex = parentIndex * 2 + 1, rightChildIndex = parentIndex * 2 + 2;
bool swapping = true;
while (swapping == true)
{
swapping = false;
int swapChildIndex = 0;
// Check which child is larger
if (data[leftChildIndex] > data[rightChildIndex]) swapChildIndex = leftChildIndex;
else swapChildIndex = rightChildIndex;
comparisons++;
// Check if swap child is larger than parent
if (data[swapChildIndex] > data[parentIndex])
{
// Swap child with parent
swap(data[swapChildIndex], data[parentIndex]);
parentIndex = swapChildIndex;
swapping = true;
}
comparisons++;
// Update children
leftChildIndex = parentIndex * 2 + 1;
rightChildIndex = parentIndex * 2 + 2;
// Check if end of Heap
if (leftChildIndex > last) break;
else if(rightChildIndex > last)
{
// Check if data needs to be swapped
if (data[leftChildIndex] > data[parentIndex])
{
swap(data[leftChildIndex], data[parentIndex]);
}
comparisons++;
break;
}
}
}
// Deletes the root from the Heap
void Heap::DeleteRootChanged(int &comparisons)
{
// Check that there are elements in the Heap
if (last < 0) return;
// Copy data[last] to data[root]
data[0] = data[last];
// Delete data[last]
data[last] = 0;
last --;
// Fix the Heap
int parentIndex = 0, leftChildIndex = parentIndex * 2 + 1, rightChildIndex = parentIndex * 2 + 2;
bool swapping = true;
// While left child exists
while (leftChildIndex < last)
{
int swapChildIndex = 0;
// Check if right child exists to find which child to use for swap
if (rightChildIndex < last)
{
// Check which child is larger and increment comparisons
if (data[leftChildIndex] > data[rightChildIndex]) swapChildIndex = leftChildIndex;
else swapChildIndex = rightChildIndex;
comparisons++;
}
else swapChildIndex = leftChildIndex;
// Check if swap should occur (child larger than parent) and increment comparisons
if (data[swapChildIndex] > data[parentIndex]) swap(data[swapChildIndex], data[parentIndex]);
comparisons++;
// Update indices
parentIndex = swapChildIndex;
leftChildIndex = parentIndex * 2 + 1;
rightChildIndex = parentIndex * 2 + 2;
}
}
// Prints elements of a Heap; should only be called on a full Heap
void Heap::PrintHeap()
{
for (unsigned int i = 0; i < data.size(); i++) cout << data[i] << ' ';
cout << endl;
}
// Prints elements of a Vector
void PrintVector(vector<int> vector)
{
for (unsigned int i = 0; i < vector.size(); i++) cout << vector[i] << ' ';
cout << endl;
}
// Error: Could not open file
int ErrorFile(char *file)
{
cout << "Error: Could not open file (" << file << ")" << endl;
return 2;
}
// Creates a vector from an input file
int CreateVectorFromFile(char *file, vector<int> &vector)
{
// Open file and check that it opens correctly
ifstream inFile(file);
if (!inFile) return ErrorFile(file);
while (!inFile.eof())
{
// Get line from file
string line;
getline(inFile, line);
// Make sure not at end of file
if (inFile.eof()) break;
// Convert line to integer and push back to vector
int number;
number = stoi(line);
//cout << number << ' '; // DEBUG: check that the file can be read
vector.push_back(number);
}
/* DEBUG: check that the array was copied
cout << endl << "File " << file << ":" << endl;
for (unsigned int count = 0; count < vector.size(); count++)
{
cout << vector[count] << ' ';
}
cout << endl;
/* END DEBUG */
return 0;
}
// Open files and load numbers into vectors
int CreateVectors(char *fileRandomOrder, char *fileReversedOrder, char *fileSortedOrder, vector<int> &vectorRandomOrder, vector<int> &vectorReversedOrder, vector<int> &vectorSortedOrder)
{
// Create random order vector
int error = CreateVectorFromFile(fileRandomOrder, vectorRandomOrder);
if (error) return error;
// Create reversed order vector
error = CreateVectorFromFile(fileReversedOrder, vectorReversedOrder);
if (error) return error;
// Create sorted order vector
error = CreateVectorFromFile(fileSortedOrder, vectorSortedOrder);
if (error) return error;
return 0;
}
// Error: Not enough arguments passed to program
int ErrorArguments(int arguments)
{
cout << "Error: Incorrect number of arguments passed to HeapSort (" << arguments << " arguments passed)" << endl;
return 1;
}
// Inserts elements from vector into a Heap and deletes elements from Heap, counting comparisons for each
void HeapSort(vector<int> &sortingVector, char *fileName)
{
Heap heap(sortingVector.size());
int comparisons = 0;
// Insert elements into the Heap
for (unsigned int i = 0; i < sortingVector.size(); i++) heap.Insert(sortingVector[i], comparisons);
// Print the state of the Heap and the number of comparisons for insertion
cout << "Heap before sorting: " << fileName << endl;
heap.PrintHeap();
cout << "InsertHeap: " << comparisons << " comparisons" << endl;
// For all elements of the Heap copy the root of the Heap to last index of the sortingVector and delete the root
comparisons = 0;
for (int i = sortingVector.size() - 1; i >= 0; i--)
{
sortingVector[i] = heap.RootData();
heap.DeleteRootChanged(comparisons);
}
// Print the number of comparisons for deletion and the state of the sortingVector
cout << "DeleteRoot: " << comparisons << " comparisons" << endl;
cout << "Vector after sorting:" << endl;
PrintVector(sortingVector);
}
// Heap sort all vectors and output results
void HeapSortAllVectors(char *fileRandomOrder, char *fileReversedOrder, char *fileSortedOrder, vector<int> &vectorRandomOrder, vector<int> &vectorReversedOrder, vector<int> &vectorSortedOrder)
{
// Sort random order vector
HeapSort(vectorRandomOrder, fileRandomOrder);
cout << endl;
// Sort reversed order vector
HeapSort(vectorReversedOrder, fileReversedOrder);
cout << endl;
// Sort sorted order vector
HeapSort(vectorSortedOrder, fileSortedOrder);
}
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <limits>
#include <random>
#include <string>
#include <fstream>
#include <chrono>
#include <dirent.h>
bool finished(std::vector<std::vector<bool>> &striked);
void print_table(
std::vector<std::vector<int>> &cost_table,
std::vector<int> &supply,
std::vector<int> &demand,
std::vector<int> &shallow_supply,
std::vector<int> &shallow_demand,
std::ofstream &out,
int &counter,
std::vector<std::pair<int, int>> &chosen,
std::vector<int> &allocation
);
int main()
{
// PRNG
std::random_device rd;
std::mt19937_64 mt(rd());
const std::string soal = ".\\soal";
struct dirent *entry;
DIR *dp = opendir(soal.c_str());
// std::cout << "Membaca folder soal. . .\n";
while ((entry = readdir(dp)))
{
int counter = 0;
auto begin = std::chrono::steady_clock::now();
std::string nama(entry->d_name);
if (nama == "." || nama == "..")
continue;
std::cout << "Membaca soal " << nama << '\n';
std::ifstream inp(soal + "\\" + nama);
std::ofstream out(".\\jawab\\" + nama);
// Baris = supply, kolom = demand
int rows, columns;
inp >> rows;
inp >> columns;
std::vector<std::vector<int>> cost_table(rows, std::vector<int>(columns, 0));
std::vector<std::vector<bool>> striked(rows, std::vector<bool>(columns, 0));
std::vector<std::pair<int, int>> answer(0);
// Isi tabel dengan cost
for (auto &row : cost_table)
for (auto &column : row)
inp >> column;
std::vector<int> supply(rows);
std::vector<int> demand(columns);
// Isi supply dan demand
for (auto &x : supply)
inp >> x;
for (auto &x : demand)
inp >> x;
std::vector<int> shallow_supply(supply);
std::vector<int> shallow_demand(demand);
out << "Tabel awal\n";
for (int i = 0; i < cost_table.size(); i++)
{
for (int j = 0; j < cost_table.at(i).size(); j++)
{
out << cost_table.at(i).at(j) << '\t';
}
out << supply.at(i) << '\n';
}
for (auto it = demand.begin(); it != demand.end(); it++)
out << *it << '\t';
out << "\n\n";
std::vector<std::pair<int, int>> chosen(0);
std::vector<int> allocation(0);
while (!finished(striked))
{
// Cari cost terendah
int lowest = std::numeric_limits<int>::max();
for (size_t i = 0; i < cost_table.size(); i++)
for (size_t j = 0; j < cost_table.at(i).size(); j++)
if (!striked.at(i).at(j) && cost_table.at(i).at(j) <= lowest)
lowest = cost_table.at(i).at(j);
// Cari index cost terendah
std::vector<std::pair<int, int>> possibles(0);
for (size_t i = 0; i < cost_table.size(); i++)
for (size_t j = 0; j < cost_table.at(i).size(); j++)
if (!striked.at(i).at(j) && cost_table.at(i).at(j) == lowest)
possibles.push_back(std::make_pair(i, j));
// Jika cost minimum tidak unik, pilih secara random mana yang dipakai
if (possibles.size() > 1)
{
std::uniform_int_distribution<> distrib(0, possibles.size() - 1);
chosen.push_back(possibles.at(distrib(mt)));
}
else
{
chosen.push_back(possibles.at(0));
}
allocation.push_back(std::min(supply.at(chosen.at(counter).first), demand.at(chosen.at(counter).second)));
int row = chosen.at(counter).first;
int column = chosen.at(counter).second;
// Kurangi supply dan demand
supply.at(row) -= allocation.at(counter);
demand.at(column) -= allocation.at(counter);
// Coret jika sudah 0
if (supply.at(row) == 0)
for (auto it = striked.at(row).begin(); it != striked.at(row).end(); it++)
*it = true;
if (demand.at(column) == 0)
for (auto it = striked.begin(); it != striked.end(); it++)
it->at(column) = true;
// Masukkan ke penyelesaian
answer.push_back(std::make_pair(cost_table.at(row).at(column), allocation.at(counter)));
print_table(cost_table, supply, demand, shallow_supply, shallow_demand, out, ++counter, chosen, allocation);
}
int total = 0;
for (const std::pair<int, int> &i : answer)
total += (i.first * i.second);
out << "Solusi: " << total << '\n';
// std::cout << total << '\n';
auto end = std::chrono::steady_clock::now();
auto elapsed = end - begin;
out << "Runtime: " << std::chrono::duration<float, std::milli>(elapsed).count() << "ms\n";
}
closedir(dp);
std::cout << "Jawaban per soal ada di folder 'jawab'";
return 0;
}
bool finished(std::vector<std::vector<bool>> &striked)
{
// Jika sudah distrike semua, berarti sudah selesai
for (auto i = striked.begin(); i != striked.end(); i++)
for (auto j = i->begin(); j != i->end(); j++)
if (*j == false)
return false;
return true;
}
void print_table(
std::vector<std::vector<int>> &cost_table,
std::vector<int> &supply,
std::vector<int> &demand,
std::vector<int> &shallow_supply,
std::vector<int> &shallow_demand,
std::ofstream &out,
int &counter,
std::vector<std::pair<int, int>> &chosen,
std::vector<int> &allocation
){
out << "Iterasi ke-" << counter << '\n';
for (int i = 0; i < cost_table.size(); i++)
{
for (int j = 0; j < cost_table.at(i).size(); j++)
{
auto it = std::find(chosen.begin(), chosen.end(), std::pair<int, int>(i, j));
if (it != chosen.end())
out << '(' << cost_table.at(i).at(j) << "," << allocation.at(it - chosen.begin()) << ")\t";
else
out << cost_table.at(i).at(j) << '\t';
}
out << shallow_supply.at(i) << ' ';
bool in_chosen = false;
for (auto it = chosen.begin(); it != chosen.end(); it++)
{
if (it->first == i)
{
in_chosen = true;
break;
}
}
if (in_chosen)
{
out << "(" << supply.at(i) << ")";
}
out << '\n';
}
for (int i = 0; i < shallow_demand.size(); i++)
{
out << shallow_demand.at(i) << ' ';
bool in_chosen = false;
for (auto it = chosen.begin(); it != chosen.end(); it++)
{
if (it->second == i)
{
in_chosen = true;
break;
}
}
if (in_chosen)
{
out << "(" << demand.at(i) << ")\t";
}
else
{
out << '\t';
}
}
out << "\n\n";
}
|
/*
*
* Copyright 2019 Asylo authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "asylo/platform/system_call/message.h"
#include <algorithm>
#include <cstddef>
#include <string>
#include <vector>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "asylo/platform/system_call/metadata.h"
#include "asylo/util/status_macros.h"
namespace asylo {
namespace system_call {
namespace {
// Returns the smallest multiple of 8 greater than or equal to |value|, or 0 on
// integer overflow.
uint64_t RoundUpToMultipleOf8(uint64_t value) {
return value + (8 - value % 8) % 8;
}
// Returns the largest multiple of 8 less than or equal to |value|.
uint64_t RoundDownToMultipleOf8(uint64_t value) { return (value / 8) * 8; }
// Returns true if the sum of two input values overflow, after round up to
// multiple of 8.
bool SumOverflowOnRoundUpToMultipleOf8(uint64_t v1, uint64_t v2) {
return v2 > RoundDownToMultipleOf8(SIZE_MAX) ||
v1 > RoundDownToMultipleOf8(SIZE_MAX) - v2;
}
} // namespace
std::string FormatMessage(primitives::Extent extent) {
MessageReader reader(extent);
std::string result;
absl::StrAppend(&result, reader.is_request() ? "request: " : "response: ");
SystemCallDescriptor descriptor(reader.sysno());
absl::StrAppend(&result, descriptor.name());
if (reader.is_response()) {
absl::StrAppend(&result, " [returns: ", reader.result(), "] ");
absl::StrAppend(&result, " [errno: ", reader.error_number(), "] ");
}
std::vector<std::string> formatted;
for (int i = 0; i < descriptor.parameter_count(); i++) {
if (!reader.parameter_is_used(i)) continue;
ParameterDescriptor parameter = descriptor.parameter(i);
std::string str = absl::StrCat(i, ": ", parameter.name());
if (parameter.is_scalar()) {
absl::StrAppend(&str, " [scalar ", reader.parameter<uint64_t>(i), "]");
} else if (reader.parameter_size(i) == 0) {
absl::StrAppend(&str, " [nullptr]");
} else if (parameter.is_string()) {
absl::StrAppend(&str, " [string \"",
reader.parameter_address<const char *>(i), "\"]");
} else if (parameter.is_fixed()) {
absl::StrAppend(&str, " [fixed ", reader.parameter_size(i), "]");
} else if (parameter.is_bounded()) {
absl::StrAppend(&str, " [bounded ", reader.parameter_size(i), "]");
} else {
str = " <unexpected value>";
}
formatted.push_back(str);
}
absl::StrAppend(&result, "(", absl::StrJoin(formatted, ", "), ")");
return result;
}
bool MessageReader::IsValidParameterSize(int index) const {
if (!parameter_is_used(index)) {
return true;
}
SystemCallDescriptor syscall(sysno());
ParameterDescriptor parameter = syscall.parameter(index);
if (parameter.is_scalar()) {
return header()->size[index] == sizeof(uint64_t);
}
if (parameter.is_fixed()) {
return header()->size[index] == parameter.size();
}
if (header()->size[index] == 0) {
return true;
}
if (parameter.is_string()) {
const char *value =
this->parameter_address<const char *>(parameter.index());
if (value[header()->size[index] - 1] != '\0') {
return false;
}
return header()->size[index] == strlen(value) + 1;
}
// Bounded parameter size could not be verified here, simply return true.
// The general validations that checks parameter size does not extend outside
// the message still apply.
if (parameter.is_bounded()) {
return true;
}
// The following line is expected to be unreachable.
abort();
}
primitives::PrimitiveStatus MessageReader::invalid_argument_status(
const std::string &reason) const {
return primitives::PrimitiveStatus{error::GoogleError::INVALID_ARGUMENT,
reason};
}
primitives::PrimitiveStatus MessageReader::ValidateMessageHeader() const {
size_t next_offset = sizeof(MessageHeader);
if (extent_.size() < next_offset) {
return invalid_argument_status(
"Message malformed: no completed header present");
}
if (header()->magic != kMessageMagic) {
return invalid_argument_status(
"Message malformed: magic number mismatched");
}
if (is_request() == is_response()) {
return invalid_argument_status(
"Message malformed: should be either a request or a response");
}
SystemCallDescriptor syscall(sysno());
if (!syscall.is_valid()) {
return invalid_argument_status(
absl::StrCat("Message malformed: sysno ", sysno(), " is invalid"));
}
return primitives::PrimitiveStatus::OkStatus();
}
primitives::PrimitiveStatus MessageReader::Validate() const {
ASYLO_RETURN_IF_ERROR(ValidateMessageHeader());
size_t next_offset = sizeof(MessageHeader);
SystemCallDescriptor syscall(sysno());
for (int i = 0; i < kParameterMax; i++) {
ParameterDescriptor parameter = syscall.parameter(i);
if (!parameter_is_used(parameter)) {
continue;
}
if (header()->offset[i] != next_offset) {
return invalid_argument_status(
absl::StrCat("Message malformed: parameter under index ", i,
" has drifted offset"));
}
if (SumOverflowOnRoundUpToMultipleOf8(header()->size[i], next_offset)) {
return invalid_argument_status(
absl::StrCat("Message malformed: parameter under index ", i,
" resides above max offset"));
}
next_offset = RoundUpToMultipleOf8(next_offset + header()->size[i]);
if (next_offset > extent_.size()) {
return invalid_argument_status(
absl::StrCat("Message malformed: parameter under index ", i,
" overflowed from buffer memory"));
}
if (!IsValidParameterSize(i)) {
return invalid_argument_status(absl::StrCat(
"Message malformed: parameter under index ", i, " size mismatched"));
}
}
return primitives::PrimitiveStatus::OkStatus();
}
bool MessageReader::parameter_is_used(ParameterDescriptor parameter) const {
if (!parameter.is_valid()) {
return false;
}
// Output-only parameters are not included in the encoding of requests.
if (is_request() && !parameter.is_in()) {
return false;
}
// Input-only parameters are not included in the encoding of responses.
if (is_response() && !parameter.is_out()) {
return false;
}
return true;
}
bool MessageReader::parameter_is_used(int index) const {
SystemCallDescriptor syscall(sysno());
ParameterDescriptor parameter = syscall.parameter(index);
return parameter_is_used(parameter);
}
MessageWriter::MessageWriter(
int sysno, uint64_t result, uint64_t error_number, bool is_request,
const std::array<uint64_t, kParameterMax> ¶meters)
: sysno_(sysno),
result_(result),
error_number_(error_number),
is_request_(is_request),
parameters_(parameters) {
SystemCallDescriptor syscall{sysno};
for (int i = 0; i < kParameterMax; i++) {
parameter_size_[i] = ParameterSize(syscall.parameter(i));
}
}
MessageWriter MessageWriter::RequestWriter(
int sysno, const std::array<uint64_t, kParameterMax> ¶meters) {
return MessageWriter(sysno, 0, 0, true, parameters);
}
MessageWriter MessageWriter::ResponseWriter(
int sysno, uint64_t result, uint64_t error_number,
const std::array<uint64_t, kParameterMax> ¶meters) {
return MessageWriter(sysno, result, error_number, false, parameters);
}
size_t MessageWriter::MessageSize() const {
size_t result = sizeof(MessageHeader);
for (int i = 0; i < kParameterMax; i++) {
result += RoundUpToMultipleOf8(parameter_size_[i]);
}
return result;
}
bool MessageWriter::parameter_is_used(ParameterDescriptor parameter) const {
if (!parameter.is_valid()) {
return false;
}
// Output-only parameters are not included in the encoding of requests.
if (is_request() && !parameter.is_in()) {
return false;
}
// Input-only parameters are not included in the encoding of responses.
if (is_response() && !parameter.is_out()) {
return false;
}
return true;
}
bool MessageWriter::parameter_is_used(int index) const {
SystemCallDescriptor syscall(sysno_);
ParameterDescriptor parameter = syscall.parameter(index);
return parameter_is_used(parameter);
}
size_t MessageWriter::ParameterSize(ParameterDescriptor parameter) const {
SystemCallDescriptor syscall(sysno_);
// Return a size of zero for unused parameters.
if (!parameter_is_used(parameter)) {
return 0;
}
// All scalar values are encoded using 64 bits.
if (parameter.is_scalar()) {
return sizeof(uint64_t);
}
uint64_t value = parameters_[parameter.index()];
// Null pointer parameters are encoded as zero size fields.
if (value == 0) {
return 0;
}
if (parameter.is_fixed()) {
return parameter.size();
}
if (parameter.is_string()) {
return strlen(reinterpret_cast<const char *>(value)) + 1;
}
if (parameter.is_bounded()) {
return parameters_[parameter.bounding_parameter().index()] *
parameter.element_size();
}
// The following line is expected to be unreachable.
abort();
}
bool MessageWriter::Write(primitives::Extent *message) const {
auto *header = reinterpret_cast<MessageHeader *>(message->data());
header->magic = kMessageMagic;
header->flags = is_request_ ? kSystemCallRequest : kSystemCallResponse;
header->sysno = sysno_;
// If this is a response message, add the result value to the message header.
if (is_response()) {
header->result = result_;
header->error_number = error_number_;
}
// Write each parameter value into the buffer.
size_t next_offset = sizeof(MessageHeader);
SystemCallDescriptor syscall(sysno_);
for (int i = 0; i < kParameterMax; i++) {
ParameterDescriptor parameter = syscall.parameter(i);
if (!parameter_is_used(parameter)) {
continue;
}
// If this parameter is a pointer and not null, then copy its contents into
// the body of the message. Null pointers are encoded as having a size of
// zero.
if (parameter.is_pointer()) {
if (void *src = reinterpret_cast<void *>(parameters_[i])) {
memcpy(message->As<uint8_t>() + next_offset, src, parameter_size_[i]);
}
} else {
// Otherwise, this is a scalar value which is zero-extended to 64-bits and
// written into the message body.
*reinterpret_cast<uint64_t *>(message->As<uint8_t>() + next_offset) =
parameters_[i];
}
header->offset[i] = next_offset;
header->size[i] = parameter_size_[i];
next_offset = RoundUpToMultipleOf8(next_offset + parameter_size_[i]);
}
return true;
}
} // namespace system_call
} // namespace asylo
|
/*=============================================================================
Library: CppMicroServices
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=============================================================================*/
#include <usModuleActivator.h>
#include <usModulePropsInterface.h>
#include <usServiceTracker.h>
#include <usServiceTrackerCustomizer.h>
#include "usFooService.h"
US_BEGIN_NAMESPACE
class ActivatorSL1 :
public ModuleActivator, public ModulePropsInterface,
public ServiceTrackerCustomizer<FooService>
{
public:
ActivatorSL1()
: tracker(0), context(0)
{
}
~ActivatorSL1()
{
delete tracker;
}
void Load(ModuleContext* context)
{
this->context = context;
InterfaceMap im = MakeInterfaceMap<ModulePropsInterface>(this);
im.insert(std::make_pair(std::string("ActivatorSL1"), this));
sr = context->RegisterService(im);
delete tracker;
tracker = new FooTracker(context, this);
tracker->Open();
}
void Unload(ModuleContext* /*context*/)
{
tracker->Close();
}
const Properties& GetProperties() const
{
return props;
}
FooService* AddingService(const ServiceReferenceT& reference)
{
props["serviceAdded"] = true;
FooService* fooService = context->GetService<FooService>(reference);
fooService->foo();
return fooService;
}
void ModifiedService(const ServiceReferenceT& /*reference*/, FooService* /*service*/)
{}
void RemovedService(const ServiceReferenceT& /*reference*/, FooService* /*service*/)
{
props["serviceRemoved"] = true;
}
private:
ModulePropsInterface::Properties props;
ServiceRegistrationU sr;
typedef ServiceTracker<FooService> FooTracker;
FooTracker* tracker;
ModuleContext* context;
}; // ActivatorSL1
US_END_NAMESPACE
US_EXPORT_MODULE_ACTIVATOR(TestModuleSL1, US_PREPEND_NAMESPACE(ActivatorSL1))
|
//
// Created by MarcasRealAccount on 31. Oct. 2020
//
#include "Engine/Renderer/Apis/Vulkan/Mesh/VulkanStaticMeshData.h"
namespace gp1::renderer::apis::vulkan::mesh
{
VulkanStaticMeshData::VulkanStaticMeshData(renderer::mesh::StaticMesh* mesh)
: VulkanMeshData(mesh) {}
} // namespace gp1::renderer::apis::vulkan::mesh
|
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) 2015-2019, Lawrence Livermore National Security, LLC.
//
// Produced at the Lawrence Livermore National Laboratory
//
// LLNL-CODE-716457
//
// All rights reserved.
//
// This file is part of Ascent.
//
// For details, see: http://ascent.readthedocs.io/.
//
// Please also read ascent/LICENSE
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the disclaimer below.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the disclaimer (as noted below) in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the LLNS/LLNL nor the names of its contributors may
// be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY,
// LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//-----------------------------------------------------------------------------
///
/// file: ascent_runtime_trigger_filters.cpp
///
//-----------------------------------------------------------------------------
#include "ascent_runtime_trigger_filters.hpp"
//-----------------------------------------------------------------------------
// thirdparty includes
//-----------------------------------------------------------------------------
// conduit includes
#include <conduit.hpp>
#include <conduit_blueprint.hpp>
//-----------------------------------------------------------------------------
// ascent includes
//-----------------------------------------------------------------------------
#include <ascent_expression_eval.hpp>
#include <ascent_logging.hpp>
#include <ascent_runtime_param_check.hpp>
#include <flow_graph.hpp>
#include <flow_workspace.hpp>
using namespace conduit;
using namespace std;
using namespace flow;
//-----------------------------------------------------------------------------
// -- begin ascent:: --
//-----------------------------------------------------------------------------
namespace ascent
{
//-----------------------------------------------------------------------------
// -- begin ascent::runtime --
//-----------------------------------------------------------------------------
namespace runtime
{
//-----------------------------------------------------------------------------
// -- begin ascent::runtime::filters --
//-----------------------------------------------------------------------------
namespace filters
{
//-----------------------------------------------------------------------------
BasicTrigger::BasicTrigger()
:Filter()
{
// empty
}
//-----------------------------------------------------------------------------
BasicTrigger::~BasicTrigger()
{
// empty
}
//-----------------------------------------------------------------------------
void
BasicTrigger::declare_interface(Node &i)
{
i["type_name"] = "basic_trigger";
i["port_names"].append() = "in";
i["output_port"] = "false";
}
//-----------------------------------------------------------------------------
bool
BasicTrigger::verify_params(const conduit::Node ¶ms,
conduit::Node &info)
{
info.reset();
bool res = check_string("condition",params, info, true);
res &= check_string("actions_file",params, info, true);
std::vector<std::string> valid_paths;
valid_paths.push_back("condition");
valid_paths.push_back("actions_file");
return res;
}
//-----------------------------------------------------------------------------
void
BasicTrigger::execute()
{
if(!input(0).check_type<Node>())
{
ASCENT_ERROR("Trigger input must be a conduit node");
}
std::string expression = params()["condition"].as_string();
std::string actions_file = params()["actions_file"].as_string();
conduit::Node actions;
Node v_info;
Node *n_input = input<Node>(0);
runtime::expressions::ExpressionEval eval(n_input);
conduit::Node res = eval.evaluate(expression);
if(res["type"].as_string() != "bool")
{
ASCENT_ERROR("result of expression '"<<expression<<"' is not an bool");
}
bool fire = res["value"].to_uint8() != 0;
if(fire)
{
Ascent ascent;
Node ascent_opts;
ascent_opts["runtime/type"] = "ascent";
#ifdef ASCENT_MPI_ENABLED
ascent_opts["mpi_comm"] = Workspace::default_mpi_comm();
#endif
ascent_opts["actions_file"] = actions_file;
ascent.open(ascent_opts);
ascent.publish(*n_input);
ascent.execute(actions);
ascent.close();
}
}
//-----------------------------------------------------------------------------
};
//-----------------------------------------------------------------------------
// -- end ascent::runtime::filters --
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
};
//-----------------------------------------------------------------------------
// -- end ascent::runtime --
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
};
//-----------------------------------------------------------------------------
// -- end ascent:: --
//-----------------------------------------------------------------------------
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/passwords/password_dialog_controller_impl.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chrome/browser/ui/passwords/account_chooser_prompt.h"
#include "chrome/browser/ui/passwords/manage_passwords_view_utils.h"
#include "components/autofill/core/common/password_form.h"
#include "components/browser_sync/browser/profile_sync_service.h"
#include "components/password_manager/core/browser/password_bubble_experiment.h"
namespace {
bool IsSmartLockBrandingEnabled(Profile* profile) {
const ProfileSyncService* sync_service =
ProfileSyncServiceFactory::GetForProfile(profile);
return password_bubble_experiment::IsSmartLockBrandingEnabled(sync_service);
}
} // namespace
PasswordDialogControllerImpl::PasswordDialogControllerImpl(Profile* profle)
: profile_(profle),
current_dialog_(nullptr) {
}
PasswordDialogControllerImpl::~PasswordDialogControllerImpl() = default;
void PasswordDialogControllerImpl::ShowAccountChooser(
AccountChooserPrompt* dialog,
std::vector<scoped_ptr<autofill::PasswordForm>> locals,
std::vector<scoped_ptr<autofill::PasswordForm>> federations) {
DCHECK(!current_dialog_);
local_credentials_.swap(locals);
federated_credentials_.swap(federations);
current_dialog_ = dialog;
current_dialog_->Show();
}
const PasswordDialogController::FormsVector&
PasswordDialogControllerImpl::GetLocalForms() const {
return local_credentials_;
}
const PasswordDialogController::FormsVector&
PasswordDialogControllerImpl::GetFederationsForms() const {
return federated_credentials_;
}
std::pair<base::string16, gfx::Range>
PasswordDialogControllerImpl::GetAccoutChooserTitle() const {
std::pair<base::string16, gfx::Range> result;
GetAccountChooserDialogTitleTextAndLinkRange(
IsSmartLockBrandingEnabled(profile_),
&result.first,
&result.second);
return result;
}
void PasswordDialogControllerImpl::OnSmartLockLinkClicked() {
// TODO(vasilii): notify the UI controller.
}
void PasswordDialogControllerImpl::OnChooseCredentials(
const autofill::PasswordForm& password_form,
password_manager::CredentialType credential_type) {
ResetDialog();
// TODO(vasilii): notify the UI controller.
}
void PasswordDialogControllerImpl::ResetDialog() {
if (current_dialog_) {
current_dialog_->ControllerGone();
current_dialog_ = nullptr;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.