本文整理汇总了C++中Ref类的典型用法代码示例。如果您正苦于以下问题:C++ Ref类的具体用法?C++ Ref怎么用?C++ Ref使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Ref类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: _parse_obj
static Error _parse_obj(const String &p_path, List<Ref<Mesh> > &r_meshes, bool p_single_mesh, bool p_generate_tangents, Vector3 p_scale_mesh, List<String> *r_missing_deps) {
FileAccessRef f = FileAccess::open(p_path, FileAccess::READ);
ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
Ref<ArrayMesh> mesh;
mesh.instance();
bool generate_tangents = p_generate_tangents;
Vector3 scale_mesh = p_scale_mesh;
bool flip_faces = false;
//bool flip_faces = p_options["force/flip_faces"];
//bool force_smooth = p_options["force/smooth_shading"];
//bool weld_vertices = p_options["force/weld_vertices"];
//float weld_tolerance = p_options["force/weld_tolerance"];
Vector<Vector3> vertices;
Vector<Vector3> normals;
Vector<Vector2> uvs;
String name;
Map<String, Map<String, Ref<SpatialMaterial> > > material_map;
Ref<SurfaceTool> surf_tool = memnew(SurfaceTool);
surf_tool->begin(Mesh::PRIMITIVE_TRIANGLES);
String current_material_library;
String current_material;
String current_group;
while (true) {
String l = f->get_line().strip_edges();
if (l.begins_with("v ")) {
//vertex
Vector<String> v = l.split(" ", false);
ERR_FAIL_COND_V(v.size() < 4, ERR_FILE_CORRUPT);
Vector3 vtx;
vtx.x = v[1].to_float() * scale_mesh.x;
vtx.y = v[2].to_float() * scale_mesh.y;
vtx.z = v[3].to_float() * scale_mesh.z;
vertices.push_back(vtx);
} else if (l.begins_with("vt ")) {
//uv
Vector<String> v = l.split(" ", false);
ERR_FAIL_COND_V(v.size() < 3, ERR_FILE_CORRUPT);
Vector2 uv;
uv.x = v[1].to_float();
uv.y = 1.0 - v[2].to_float();
uvs.push_back(uv);
} else if (l.begins_with("vn ")) {
//normal
Vector<String> v = l.split(" ", false);
ERR_FAIL_COND_V(v.size() < 4, ERR_FILE_CORRUPT);
Vector3 nrm;
nrm.x = v[1].to_float();
nrm.y = v[2].to_float();
nrm.z = v[3].to_float();
normals.push_back(nrm);
} else if (l.begins_with("f ")) {
//vertex
Vector<String> v = l.split(" ", false);
ERR_FAIL_COND_V(v.size() < 4, ERR_FILE_CORRUPT);
//not very fast, could be sped up
Vector<String> face[3];
face[0] = v[1].split("/");
face[1] = v[2].split("/");
ERR_FAIL_COND_V(face[0].size() == 0, ERR_FILE_CORRUPT);
ERR_FAIL_COND_V(face[0].size() != face[1].size(), ERR_FILE_CORRUPT);
for (int i = 2; i < v.size() - 1; i++) {
face[2] = v[i + 1].split("/");
ERR_FAIL_COND_V(face[0].size() != face[2].size(), ERR_FILE_CORRUPT);
for (int j = 0; j < 3; j++) {
int idx = j;
if (!flip_faces && idx < 2) {
idx = 1 ^ idx;
}
if (face[idx].size() == 3) {
int norm = face[idx][2].to_int() - 1;
if (norm < 0)
norm += normals.size() + 1;
ERR_FAIL_INDEX_V(norm, normals.size(), ERR_FILE_CORRUPT);
surf_tool->add_normal(normals[norm]);
}
if (face[idx].size() >= 2 && face[idx][1] != String()) {
int uv = face[idx][1].to_int() - 1;
if (uv < 0)
uv += uvs.size() + 1;
ERR_FAIL_INDEX_V(uv, uvs.size(), ERR_FILE_CORRUPT);
//.........这里部分代码省略.........
示例2: switch
void AnimatedSprite::_notification(int p_what) {
switch(p_what) {
case NOTIFICATION_PROCESS: {
if (frames.is_null())
return;
if (!frames->has_animation(animation))
return;
if (frame<0)
return;
float speed = frames->get_animation_speed(animation);
if (speed==0)
return; //do nothing
float remaining = get_process_delta_time();
while(remaining) {
if (timeout<=0) {
timeout=1.0/speed;
int fc = frames->get_frame_count(animation);
if (frame>=fc-1) {
if (frames->get_animation_loop(animation)) {
frame=0;
} else {
frame=fc-1;
}
} else {
frame++;
}
update();
_change_notify("frame");
}
float to_process = MIN(timeout,remaining);
remaining-=to_process;
timeout-=to_process;
}
} break;
case NOTIFICATION_DRAW: {
if (frames.is_null()) {
print_line("no draw no faemos");
return;
}
if (frame<0) {
print_line("no draw frame <0");
return;
}
if (!frames->has_animation(animation)) {
print_line("no draw no anim: "+String(animation));
return;
}
Ref<Texture> texture = frames->get_frame(animation,frame);
if (texture.is_null()) {
print_line("no draw texture is null");
return;
}
//print_line("DECIDED TO DRAW");
RID ci = get_canvas_item();
/*
texture->draw(ci,Point2());
break;
*/
Size2i s;
s = texture->get_size();
Point2 ofs=offset;
if (centered)
ofs-=s/2;
if (OS::get_singleton()->get_use_pixel_snap()) {
ofs=ofs.floor();
}
Rect2 dst_rect(ofs,s);
if (hflip)
dst_rect.size.x=-dst_rect.size.x;
if (vflip)
dst_rect.size.y=-dst_rect.size.y;
//texture->draw_rect(ci,dst_rect,false,modulate);
texture->draw_rect_region(ci,dst_rect,Rect2(Vector2(),texture->get_size()),modulate);
// VisualServer::get_singleton()->canvas_item_add_texture_rect_region(ci,dst_rect,texture->get_rid(),src_rect,modulate);
} break;
//.........这里部分代码省略.........
示例3: getSeconds
void OpenGLRenderer::renderFrame(const Ref<Camera>& camera, const Ref<BackendScene>& scene, Ref<Film>& film)
{
/*! render frame */
double t = getSeconds();
this->camera = camera;
this->scene = scene;
this->film = film;
/*! precompute some values */
if (!OpenGLRenderer::is_initialized){
OpenGLRenderer::initGL(scene);
}
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, OpenGLRenderer::fbo_render);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
GL_TEXTURE_2D,OpenGLRenderer::img_render, 0);
glEnable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
glEnable(GL_CULL_FACE);
glClearColor(0.0,0.0,0.0,0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (linedrawing) glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
else glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glViewport(0,0,fb_size_w,fb_size_h);
PinholeCamera* cam = dynamic_cast<PinholeCamera*>(camera.ptr);
if (!cam) {
std::cerr<<"OpenGL Renderer use only pinehole camera ! "<<std::endl;
exit(1);
}
AffineSpace worldToCam = rcp(cam->localToWorld);
float mat[16];
worldToCam.to4x4ArrayMatrix(mat);
glMatrixMode( GL_PROJECTION );
glPushMatrix();
glLoadIdentity();
//std::cerr<<"Far plane ..."<<std::endl;
gluPerspective(cam->angle,cam->aspectRatio,cam->focalDistance,1000.0*cam->focalDistance);
glMatrixMode( GL_MODELVIEW );
glPushMatrix();
glLoadMatrixf(mat);
//glMultMatrixf(mat);
//! Handle lights
if (scene->allLights.size()>0) {
glEnable(GL_LIGHTING);
uint ind_lght = 0;
std::vector< Ref< Light > > lights = scene->allLights;
for(std::vector< Ref< Light > >::iterator it = lights.begin();it != lights.end();it++) {
handleLight(ind_lght++,*it);
}
}
glColor3f(1.0,0.0,0.0);
std::vector< Ref< Instance > > geom = scene->geometry;
Ref<Shape> one_shape;
uint ind_mesh = 0;
for(std::vector< Ref< Instance > >::iterator it = geom.begin();it != geom.end();it++) {
one_shape = (*it)->shape;
handleMaterial((*it)->material);
if (TriangleMesh* tm = dynamic_cast<TriangleMesh*>(one_shape.ptr)) {
drawTriangleMesh(ind_mesh++,tm);
}
else if (Triangle* tr = dynamic_cast<Triangle*>(one_shape.ptr)) {
drawTriangle(tr);
}
//! Handle here all other cases
else if (TriangleMeshWithNormals* trn = dynamic_cast<TriangleMeshWithNormals*>(one_shape.ptr)) {
drawTriangleMeshNormals(ind_mesh++,trn);
}
else {
//std::cerr<<" Is a "<<typeid(*one_shape).name()<<std::endl;
}
}
glPopMatrix();
glMatrixMode( GL_PROJECTION );
glPopMatrix();
glMatrixMode( GL_MODELVIEW );
glFinish();
//! Copy of the GPU framebuffer to the CPU color buffer...
glReadPixels(0,0,OpenGLRenderer::fb_size_w,OpenGLRenderer::fb_size_h,GL_RGB,
GL_UNSIGNED_BYTE,OpenGLRenderer::color_buffer);
glFinish();
glDisable(GL_DEPTH_TEST);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
glDisable(GL_DEPTH_TEST);
//! Copy of the CPU color buffer to the film...
Col3f colcour;
for(uint i=0;i<fb_size_w;i++) {
for(uint j=0;j<fb_size_h;j++) {
colcour.r = OpenGLRenderer::color_buffer[(fb_size_h-1-j)*3*fb_size_w+3*i]/255.0;
colcour.g = OpenGLRenderer::color_buffer[(fb_size_h-1-j)*3*fb_size_w+3*i+1]/255.0;
//.........这里部分代码省略.........
示例4: generate_preview_texture
void SampleEditor::generate_preview_texture(const Ref<Sample>& p_sample,Ref<ImageTexture> &p_texture) {
DVector<uint8_t> data = p_sample->get_data();
DVector<uint8_t> img;
int w = p_texture->get_width();
int h = p_texture->get_height();
img.resize(w*h*3);
DVector<uint8_t>::Write imgdata = img.write();
uint8_t * imgw = imgdata.ptr();
DVector<uint8_t>::Read sampledata = data.read();
const uint8_t *sdata=sampledata.ptr();
bool stereo = p_sample->is_stereo();
bool _16=p_sample->get_format()==Sample::FORMAT_PCM16;
int len = p_sample->get_length();
if (len<1)
return;
for(int i=0;i<w;i++) {
// i trust gcc will optimize this loop
float max[2]={-1e10,-1e10};
float min[2]={1e10,1e10};
int c=stereo?2:1;
int from = i*len/w;
int to = (i+1)*len/w;
if (to>=len)
to=len-1;
if (_16) {
const int16_t*src =(const int16_t*)sdata;
for(int j=0;j<c;j++) {
for(int k=from;k<=to;k++) {
float v = src[k*c+j]/32768.0;
if (v>max[j])
max[j]=v;
if (v<min[j])
min[j]=v;
}
}
} else {
const int8_t*src =(const int8_t*)sdata;
for(int j=0;j<c;j++) {
for(int k=from;k<=to;k++) {
float v = src[k*c+j]/128.0;
if (v>max[j])
max[j]=v;
if (v<min[j])
min[j]=v;
}
}
}
if (!stereo) {
for(int j=0;j<h;j++) {
float v = (j/(float)h) * 2.0 - 1.0;
uint8_t* imgofs = &imgw[(j*w+i)*3];
if (v>min[0] && v<max[0]) {
imgofs[0]=255;
imgofs[1]=150;
imgofs[2]=80;
} else {
imgofs[0]=0;
imgofs[1]=0;
imgofs[2]=0;
}
}
} else {
for(int j=0;j<h;j++) {
int half,ofs;
float v;
if (j<(h/2)) {
half=0;
ofs=0;
v = (j/(float)(h/2)) * 2.0 - 1.0;
} else {
half=1;
ofs=h/2;
v = ((j-(h/2))/(float)(h/2)) * 2.0 - 1.0;
}
uint8_t* imgofs = &imgw[(j*w+i)*3];
if (v>min[half] && v<max[half]) {
imgofs[0]=255;
imgofs[1]=150;
imgofs[2]=80;
} else {
//.........这里部分代码省略.........
示例5: WKUserContentControllerCopyUserScripts
WKArrayRef WKUserContentControllerCopyUserScripts(WKUserContentControllerRef userContentControllerRef)
{
Ref<API::Array> userScripts = toImpl(userContentControllerRef)->userScripts().copy();
return toAPI(&userScripts.leakRef());
}
示例6: AuthLoop
void AuthLoop(CONNECT_INFO* cfg, Ref< UsersPool > OnlineUsers, Ref< CrossThreadQueue< string > > OutputQueue) {
RakPeerInterface* rakServer = RakNetworkFactory::GetRakPeerInterface();
PacketFileLogger* msgFileHandler = NULL;
if (cfg->logFile) {
msgFileHandler = new PacketFileLogger();
rakServer->AttachPlugin(msgFileHandler);
}
InitSecurity(rakServer, cfg->useEncryption);
SocketDescriptor socketDescriptor(cfg->listenPort, 0);
if (rakServer->Startup(8, 30, &socketDescriptor, 1)) {
stringstream s;
s << "auth started! Listening on: " << cfg->listenPort << "\n";
OutputQueue->Insert(s.str());
} else QuitError("auth server init error!");
rakServer->SetMaximumIncomingConnections(8);
if (msgFileHandler != NULL) msgFileHandler->StartLog(".\\logs\\auth");
Packet* packet;
while (!LUNIterminate) {
RakSleep(30); // This sleep keeps RakNet responsive
packet = rakServer->Receive();
if (packet == NULL) continue;
PrintPacketInfo(packet, msgFileHandler);
switch (packet->data[0]) {
case ID_LEGO_PACKET:
switch (packet->data[1]) {
case LUNI_INITAW:
if (packet->data[3] == 0) { // thats just a formality so far since no other numbers occured for this case
// response: 00, 00
auto v = OpenPacket(".\\auth\\init_aw.bin");
// bytes 8-10 is the game version (same numbers are mentioned in the game log)
// the client expects it to be the same that he sent (otherwise he displays "server is being updated" and disconnects)
ServerSendPacket(rakServer, v, packet->systemAddress);
}
break;
case LUNI_LOGIN: //user logging into server
{
auto usr = HandleUserLogin(rakServer, packet, cfg, OnlineUsers);
if( usr != NULL ) OutputQueue->Insert("\n" + usr->GetUsername() + " Logged-in\n");
#ifdef DEBUG
else OutputQueue->Insert("\n Login failed!\n");
#endif
}
break;
default:
stringstream s;
s << "\nauth received unknow pakcet: " << RawDataToString(packet->data, packet->length) << endl;
OutputQueue->Insert(s.str());
}
break;
case ID_NEW_INCOMING_CONNECTION:
# ifdef DEBUG
OutputQueue->Insert("\n Auth is receiving a new connection...\n");
#endif
break;
case ID_DISCONNECTION_NOTIFICATION: // do nothing
break;
default:
stringstream s;
s << "\nauth received unknow pakcet: " << RawDataToString(packet->data, packet->length) << endl;
OutputQueue->Insert(s.str());
}
rakServer->DeallocatePacket(packet);
}
stringstream s;
s << "Quitting auth\n";
OutputQueue->Insert(s.str());
rakServer->Shutdown(0);
RakNetworkFactory::DestroyRakPeerInterface(rakServer);
}
示例7: _parse_completion_class
//.........这里部分代码省略.........
if (!p_indices) {
if (!in_static_func) {
for(int i=0;i<p_class->variables.size();i++) {
r_options->push_back(p_class->variables[i].identifier);
}
}
for(int i=0;i<p_class->constant_expressions.size();i++) {
r_options->push_back(p_class->constant_expressions[i].identifier);
}
if (!in_static_func) {
for(int i=0;i<p_class->functions.size();i++) {
r_options->push_back(p_class->functions[i]->name);
}
}
for(int i=0;i<p_class->static_functions.size();i++) {
r_options->push_back(p_class->static_functions[i]->name);
}
}
if (p_class->extends_used) {
//do inheritance
String path = p_class->extends_file;
Ref<GDScript> script;
Ref<GDNativeClass> native;
if (path!="") {
//path (and optionally subclasses)
script = ResourceLoader::load(path);
if (script.is_null()) {
return false;
}
if (p_class->extends_class.size()) {
for(int i=0;i<p_class->extends_class.size();i++) {
String sub = p_class->extends_class[i];
if (script->get_subclasses().has(sub)) {
script=script->get_subclasses()[sub];
} else {
return false;
}
}
}
} else {
ERR_FAIL_COND_V(p_class->extends_class.size()==0,false);
//look around for the subclasses
String base=p_class->extends_class[0];
Ref<GDScript> base_class;
示例8: main
int main(int argc, char** argv)
{
if (argc == 2)
return echo(argc, argv);
{
class TestFactory: public ProcessFactory
{
public:
int incarnate() {
print("Good morning %%.\n", User(Process::realUserId()).fullName());
return 7;
}
};
print("(1) Worker clone\n\n");
Ref<ProcessFactory, Owner> factory = new TestFactory;
Ref<Process, Owner> worker = factory->produce();
int ret = worker->wait();
print("ret = %%\n", ret);
print("\n");
}
{
print("(2) I/O Redirection, passing of arguments and environment variables\n\n");
Ref<ProcessFactory, Owner> factory = new ProcessFactory;
factory->setExecPath(argv[0]);
factory->setIoPolicy(Process::ForwardInput | Process::ForwardOutput);
factory->options()->append("--echo 123");
factory->envMap()->define("Hello", "World!");
Ref<Process, Owner> process = factory->produce();
print("Created child process with pid = %%\n", unsigned(process->id()));
const char* message =
"Hello, world!\n"
"exit\n";
process->rawInput()->write(message, str::len(message));
process->rawInput()->close();
const int bufSize = 16;
uint8_t buf[bufSize];
while (true) {
int bufFill = process->rawOutput()->readAvail(buf, bufSize);
if (bufFill == 0) break;
rawOutput()->write(buf, bufFill);
}
print("Waiting for child process to finish...\n");
int ret = process->wait();
print("ret = %%\n", ret);
print("\n");
}
{
print("(3) Current process\n\n");
print("Process::cwd() = %%\n", Process::cwd());
print("Process::execPath() = %%\n", Process::execPath());
print("Process::isSuperUser() = %%\n", Process::isSuperUser());
print("\n");
}
return 0;
}
示例9: builder
Ref<BVH2<Triangle4> > BVH2Builder::build(const BuildTriangle* triangles, size_t numTriangles)
{
Ref<BVH2<Triangle4> > bvh = new BVH2<Triangle4>;
double t0 = getSeconds();
BVH2Builder builder(triangles,numTriangles,bvh);
double t1 = getSeconds();
size_t bytesNodes = bvh->getNumNodes()*sizeof(BVH2<Triangle4>::Node);
size_t bytesTris = bvh->getNumPrimBlocks()*sizeof(BVH2<Triangle4>::Triangle);
std::ostringstream stream;
stream << "triangles = " << numTriangles << std::endl;
stream.setf(std::ios::fixed, std::ios::floatfield);
stream.precision(0);
stream << "build time = " << (t1-t0)*1000.0f << " ms" << std::endl;
stream.setf(std::ios::scientific, std::ios::floatfield);
stream.precision(2);
stream << "sah = " << bvh->getSAH() << std::endl;
stream.setf(std::ios::fixed, std::ios::floatfield);
stream.precision(1);
stream << "size = " << (bytesNodes+bytesTris)/1048576.0f << " MB" << std::endl;
stream << "nodes = " << bvh->getNumNodes() << " "
<< "(" << bytesNodes/1048576.0f << " MB) "
<< "(" << 100.0f*(bvh->getNumNodes()-1+bvh->getNumLeaves())/(2.0*bvh->getNumNodes()) << " %)"
<< std::endl;
stream << "leaves = " << bvh->getNumLeaves() << " "
<< "(" << bytesTris/1048576.0f << " MB) "
<< "(" << 100.0f*bvh->getNumPrims()/(4.0*bvh->getNumPrimBlocks()) << " %)"
<< std::endl;
std::cout << stream.str();
return bvh;
}
示例10: catch
void GenericMultipleBarcodeReader::doDecodeMultiple(Ref<BinaryBitmap> image,
DecodeHints hints, std::vector<Ref<Result> >& results, int xOffset, int yOffset)
{
Ref<Result> result;
try {
result = delegate_.decode(image, hints);
} catch (ReaderException& re) {
return;
}
bool alreadyFound = false;
for (unsigned int i = 0; i < results.size(); i++) {
Ref<Result> existingResult = results[i];
if (existingResult->getText()->getText() == result->getText()->getText()) {
alreadyFound = true;
break;
}
}
if (alreadyFound) {
return;
}
results.push_back(translateResultPoints(result, xOffset, yOffset));
const std::vector<Ref<ResultPoint> > resultPoints = result->getResultPoints();
if (resultPoints.empty()) {
return;
}
int width = image->getWidth();
int height = image->getHeight();
float minX = width;
float minY = height;
float maxX = 0.0f;
float maxY = 0.0f;
for (unsigned int i = 0; i < resultPoints.size(); i++) {
Ref<ResultPoint> point = resultPoints[i];
float x = point->getX();
float y = point->getY();
if (x < minX) {
minX = x;
}
if (y < minY) {
minY = y;
}
if (x > maxX) {
maxX = x;
}
if (y > maxY) {
maxY = y;
}
}
// Decode left of barcode
if (minX > MIN_DIMENSION_TO_RECUR) {
doDecodeMultiple(image->crop(0, 0, (int) minX, height),
hints, results, xOffset, yOffset);
}
// Decode above barcode
if (minY > MIN_DIMENSION_TO_RECUR) {
doDecodeMultiple(image->crop(0, 0, width, (int) minY),
hints, results, xOffset, yOffset);
}
// Decode right of barcode
if (maxX < width - MIN_DIMENSION_TO_RECUR) {
doDecodeMultiple(image->crop((int) maxX, 0, width - (int) maxX, height),
hints, results, xOffset + (int) maxX, yOffset);
}
// Decode below barcode
if (maxY < height - MIN_DIMENSION_TO_RECUR) {
doDecodeMultiple(image->crop(0, (int) maxY, width, height - (int) maxY),
hints, results, xOffset, yOffset + (int) maxY);
}
}
示例11: velocityReference
VectorXd velocityReference(NewQPControllerData *pdata, double t, const Ref<VectorXd> &q, const Ref<VectorXd> &qd, const Ref<VectorXd> &qdd, bool foot_contact[2], VRefIntegratorParams *params, RobotPropertyCache *rpc) {
// Integrate expected accelerations to determine a target feed-forward velocity, which we can pass in to Atlas
int i;
assert(qdd.size() == pdata->r->num_velocities);
double dt = 0;
if (pdata->state.t_prev != 0) {
dt = t - pdata->state.t_prev;
}
VectorXd qdd_limited = qdd;
// Do not wind the vref integrator up against the joint limits for the legs
for (i=0; i < rpc->position_indices.at("r_leg").size(); i++) {
int pos_ind = rpc->position_indices.at("r_leg")(i);
if (q(pos_ind) <= pdata->r->joint_limit_min(pos_ind) + LEG_INTEGRATOR_DEACTIVATION_MARGIN) {
qdd_limited(pos_ind) = std::max(qdd(pos_ind), 0.0);
} else if (q(pos_ind) >= pdata->r->joint_limit_max(pos_ind) - LEG_INTEGRATOR_DEACTIVATION_MARGIN) {
qdd_limited(pos_ind) = std::min(qdd(pos_ind), 0.0);
}
}
for (i=0; i < rpc->position_indices.at("l_leg").size(); i++) {
int pos_ind = rpc->position_indices.at("l_leg")(i);
if (q(pos_ind) <= pdata->r->joint_limit_min(pos_ind) + LEG_INTEGRATOR_DEACTIVATION_MARGIN) {
qdd_limited(pos_ind) = std::max(qdd(pos_ind), 0.0);
} else if (q(pos_ind) >= pdata->r->joint_limit_max(pos_ind) - LEG_INTEGRATOR_DEACTIVATION_MARGIN) {
qdd_limited(pos_ind) = std::min(qdd(pos_ind), 0.0);
}
}
pdata->state.vref_integrator_state = (1-params->eta)*pdata->state.vref_integrator_state + params->eta*qd + qdd_limited*dt;
if (params->zero_ankles_on_contact && foot_contact[0] == 1) {
for (i=0; i < rpc->position_indices.at("l_leg_ak").size(); i++) {
pdata->state.vref_integrator_state(rpc->position_indices.at("l_leg_ak")(i)) = 0;
}
}
if (params->zero_ankles_on_contact && foot_contact[1] == 1) {
for (i=0; i < rpc->position_indices.at("r_leg_ak").size(); i++) {
pdata->state.vref_integrator_state(rpc->position_indices.at("r_leg_ak")(i)) = 0;
}
}
if (pdata->state.foot_contact_prev[0] != foot_contact[0]) {
// contact state changed, reset integrated velocities
for (i=0; i < rpc->position_indices.at("l_leg").size(); i++) {
pdata->state.vref_integrator_state(rpc->position_indices.at("l_leg")(i)) = qd(rpc->position_indices.at("l_leg")(i));
}
}
if (pdata->state.foot_contact_prev[1] != foot_contact[1]) {
// contact state changed, reset integrated velocities
for (i=0; i < rpc->position_indices.at("r_leg").size(); i++) {
pdata->state.vref_integrator_state(rpc->position_indices.at("r_leg")(i)) = qd(rpc->position_indices.at("r_leg")(i));
}
}
pdata->state.foot_contact_prev[0] = foot_contact[0];
pdata->state.foot_contact_prev[1] = foot_contact[1];
VectorXd qd_err = pdata->state.vref_integrator_state - qd;
// do not velocity control ankles when in contact
if (params->zero_ankles_on_contact && foot_contact[0] == 1) {
for (i=0; i < rpc->position_indices.at("l_leg_ak").size(); i++) {
qd_err(rpc->position_indices.at("l_leg_ak")(i)) = 0;
}
}
if (params->zero_ankles_on_contact && foot_contact[1] == 1) {
for (i=0; i < rpc->position_indices.at("r_leg_ak").size(); i++) {
qd_err(rpc->position_indices.at("r_leg_ak")(i)) = 0;
}
}
VectorXd qd_ref = qd_err.array().max(-params->delta_max);
qd_ref = qd_ref.array().min(params->delta_max);
return qd_ref;
}
示例12: ASSERT_NOT_REACHED
void ConsoleMessage::addToFrontend(ConsoleFrontendDispatcher* consoleFrontendDispatcher, InjectedScriptManager* injectedScriptManager, bool generatePreview)
{
Ref<Inspector::Protocol::Console::ConsoleMessage> jsonObj = Inspector::Protocol::Console::ConsoleMessage::create()
.setSource(messageSourceValue(m_source))
.setLevel(messageLevelValue(m_level))
.setText(m_message)
.release();
// FIXME: only send out type for ConsoleAPI source messages.
jsonObj->setType(messageTypeValue(m_type));
jsonObj->setLine(static_cast<int>(m_line));
jsonObj->setColumn(static_cast<int>(m_column));
jsonObj->setUrl(m_url);
jsonObj->setRepeatCount(static_cast<int>(m_repeatCount));
if (m_source == MessageSource::Network && !m_requestId.isEmpty())
jsonObj->setNetworkRequestId(m_requestId);
if (m_arguments && m_arguments->argumentCount()) {
InjectedScript injectedScript = injectedScriptManager->injectedScriptFor(m_arguments->globalState());
if (!injectedScript.hasNoValue()) {
Ref<Inspector::Protocol::Array<Inspector::Protocol::Runtime::RemoteObject>> jsonArgs = Inspector::Protocol::Array<Inspector::Protocol::Runtime::RemoteObject>::create();
if (m_type == MessageType::Table && generatePreview && m_arguments->argumentCount()) {
Deprecated::ScriptValue table = m_arguments->argumentAt(0);
Deprecated::ScriptValue columns = m_arguments->argumentCount() > 1 ? m_arguments->argumentAt(1) : Deprecated::ScriptValue();
RefPtr<Inspector::Protocol::Runtime::RemoteObject> inspectorValue = injectedScript.wrapTable(table, columns);
if (!inspectorValue) {
ASSERT_NOT_REACHED();
return;
}
jsonArgs->addItem(inspectorValue.copyRef());
if (m_arguments->argumentCount() > 1)
jsonArgs->addItem(injectedScript.wrapObject(columns, ASCIILiteral("console"), true));
} else {
for (unsigned i = 0; i < m_arguments->argumentCount(); ++i) {
RefPtr<Inspector::Protocol::Runtime::RemoteObject> inspectorValue = injectedScript.wrapObject(m_arguments->argumentAt(i), ASCIILiteral("console"), generatePreview);
if (!inspectorValue) {
ASSERT_NOT_REACHED();
return;
}
jsonArgs->addItem(inspectorValue.copyRef());
}
}
jsonObj->setParameters(WTF::move(jsonArgs));
}
}
if (m_callStack)
jsonObj->setStackTrace(m_callStack->buildInspectorArray());
consoleFrontendDispatcher->messageAdded(WTF::move(jsonObj));
}
示例13: _parse_material_library
static Error _parse_material_library(const String &p_path, Map<String, Ref<SpatialMaterial> > &material_map, List<String> *r_missing_deps) {
FileAccessRef f = FileAccess::open(p_path, FileAccess::READ);
ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
Ref<SpatialMaterial> current;
String current_name;
String base_path = p_path.get_base_dir();
while (true) {
String l = f->get_line().strip_edges();
if (l.begins_with("newmtl ")) {
//vertex
current_name = l.replace("newmtl", "").strip_edges();
current.instance();
current->set_name(current_name);
material_map[current_name] = current;
} else if (l.begins_with("Ka ")) {
//uv
print_line("Warning: Ambient light for material '" + current_name + "' is ignored in PBR");
} else if (l.begins_with("Kd ")) {
//normal
ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
Vector<String> v = l.split(" ", false);
ERR_FAIL_COND_V(v.size() < 4, ERR_INVALID_DATA);
Color c = current->get_albedo();
c.r = v[1].to_float();
c.g = v[2].to_float();
c.b = v[3].to_float();
current->set_albedo(c);
} else if (l.begins_with("Ks ")) {
//normal
ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
Vector<String> v = l.split(" ", false);
ERR_FAIL_COND_V(v.size() < 4, ERR_INVALID_DATA);
float r = v[1].to_float();
float g = v[2].to_float();
float b = v[3].to_float();
float metalness = MAX(r, MAX(g, b));
current->set_metallic(metalness);
} else if (l.begins_with("Ns ")) {
//normal
ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
Vector<String> v = l.split(" ", false);
ERR_FAIL_COND_V(v.size() != 2, ERR_INVALID_DATA);
float s = v[1].to_float();
current->set_metallic((1000.0 - s) / 1000.0);
} else if (l.begins_with("d ")) {
//normal
ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
Vector<String> v = l.split(" ", false);
ERR_FAIL_COND_V(v.size() != 2, ERR_INVALID_DATA);
float d = v[1].to_float();
Color c = current->get_albedo();
c.a = d;
current->set_albedo(c);
if (c.a < 0.99) {
current->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
}
} else if (l.begins_with("Tr ")) {
//normal
ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
Vector<String> v = l.split(" ", false);
ERR_FAIL_COND_V(v.size() != 2, ERR_INVALID_DATA);
float d = v[1].to_float();
Color c = current->get_albedo();
c.a = 1.0 - d;
current->set_albedo(c);
if (c.a < 0.99) {
current->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
}
} else if (l.begins_with("map_Ka ")) {
//uv
print_line("Warning: Ambient light texture for material '" + current_name + "' is ignored in PBR");
} else if (l.begins_with("map_Kd ")) {
//normal
ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
String p = l.replace("map_Kd", "").replace("\\", "/").strip_edges();
String path = base_path.plus_file(p);
Ref<Texture> texture = ResourceLoader::load(path);
if (texture.is_valid()) {
current->set_texture(SpatialMaterial::TEXTURE_ALBEDO, texture);
} else if (r_missing_deps) {
r_missing_deps->push_back(path);
}
} else if (l.begins_with("map_Ks ")) {
//normal
ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
String p = l.replace("map_Ks", "").replace("\\", "/").strip_edges();
String path = base_path.plus_file(p);
//.........这里部分代码省略.........
示例14: row
Ref<Result> OneDReader::doDecode(Ref<BinaryBitmap> image, DecodeHints hints) {
int width = image->getWidth();
int height = image->getHeight();
Ref<BitArray> row(new BitArray(width));
int middle = height >> 1;
bool tryHarder = hints.getTryHarder();
int rowStep = std::max(1, height >> (tryHarder ? 8 : 5));
using namespace std;
// cerr << "rS " << rowStep << " " << height << " " << tryHarder << endl;
int maxLines;
if (tryHarder) {
maxLines = height; // Look at the whole image, not just the center
} else {
maxLines = 15; // 15 rows spaced 1/32 apart is roughly the middle half of the image
}
for (int x = 0; x < maxLines; x++) {
// Scanning from the middle out. Determine which row we're looking at next:
int rowStepsAboveOrBelow = (x + 1) >> 1;
bool isAbove = (x & 0x01) == 0; // i.e. is x even?
int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow);
if (false) {
std::cerr << "rN "
<< rowNumber << " "
<< height << " "
<< middle << " "
<< rowStep << " "
<< isAbove << " "
<< rowStepsAboveOrBelow
<< std::endl;
}
if (rowNumber < 0 || rowNumber >= height) {
// Oops, if we run off the top or bottom, stop
break;
}
// Estimate black point for this row and load it:
try {
row = image->getBlackRow(rowNumber, row);
} catch (NotFoundException const& ignored) {
(void)ignored;
continue;
}
// While we have the image data in a BitArray, it's fairly cheap to reverse it in place to
// handle decoding upside down barcodes.
for (int attempt = 0; attempt < 2; attempt++) {
if (attempt == 1) {
row->reverse(); // reverse the row and continue
}
// Java hints stuff missing
try {
// Look for a barcode
// std::cerr << "rn " << rowNumber << " " << typeid(*this).name() << std::endl;
Ref<Result> result = decodeRow(rowNumber, row);
// We found our barcode
if (attempt == 1) {
// But it was upside down, so note that
// result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(180));
// And remember to flip the result points horizontally.
ArrayRef< Ref<ResultPoint> > points(result->getResultPoints());
if (points) {
points[0] = Ref<ResultPoint>(new OneDResultPoint(width - points[0]->getX() - 1,
points[0]->getY()));
points[1] = Ref<ResultPoint>(new OneDResultPoint(width - points[1]->getX() - 1,
points[1]->getY()));
}
}
return result;
} catch (ReaderException const& re) {
(void)re;
continue;
}
}
}
throw NotFoundException();
}
示例15: switch
bool Path2DEditor::forward_input_event(const InputEvent& p_event) {
if (!node)
return false;
if (!node->is_visible())
return false;
if (!node->get_curve().is_valid())
return false;
switch(p_event.type) {
case InputEvent::MOUSE_BUTTON: {
const InputEventMouseButton &mb=p_event.mouse_button;
Matrix32 xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
Vector2 gpoint = Point2(mb.x,mb.y);
Vector2 cpoint = !mb.mod.alt? snap_point(xform.affine_inverse().xform(gpoint))
: node->get_global_transform().affine_inverse().xform( snap_point(canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint)) );
//first check if a point is to be added (segment split)
real_t grab_treshold=EDITOR_DEF("poly_editor/point_grab_radius",8);
// Test move point!!
if ( mb.pressed && mb.button_index==BUTTON_LEFT ) {
Ref<Curve2D> curve = node->get_curve();
for(int i=0;i<curve->get_point_count();i++) {
bool pointunder=false;
{
Point2 p = xform.xform( curve->get_point_pos(i) );
if (gpoint.distance_to(p) < grab_treshold ) {
if (!mb.mod.shift) {
action=ACTION_MOVING_POINT;
action_point=i;
moving_from=curve->get_point_pos(i);
moving_screen_from=gpoint;
return true;
} else
pointunder=true;
}
}
if (i<(curve->get_point_count()-1)) {
Point2 p = xform.xform( curve->get_point_pos(i)+curve->get_point_out(i) );
if (gpoint.distance_to(p) < grab_treshold ) {
action=ACTION_MOVING_OUT;
action_point=i;
moving_from=curve->get_point_out(i);
moving_screen_from=gpoint;
return true;
}
}
if (i>0) {
Point2 p = xform.xform( curve->get_point_pos(i)+curve->get_point_in(i) );
if (gpoint.distance_to(p) < grab_treshold ) {
action=ACTION_MOVING_IN;
action_point=i;
moving_from=curve->get_point_in(i);
moving_screen_from=gpoint;
return true;
}
}
if (pointunder)
return true;
}
}
// Test add point in empty space!
if ( mb.pressed && mb.mod.control && mb.button_index==BUTTON_LEFT ) {
Ref<Curve2D> curve = node->get_curve();
undo_redo->create_action("Add Point to Curve");
undo_redo->add_do_method(curve.ptr(),"add_point",cpoint);
undo_redo->add_undo_method(curve.ptr(),"remove_point",curve->get_point_count());
undo_redo->add_do_method(canvas_item_editor,"update");
undo_redo->add_undo_method(canvas_item_editor,"update");
undo_redo->commit_action();
action=ACTION_MOVING_POINT;
action_point=curve->get_point_count()-1;
//.........这里部分代码省略.........