void MyGLWidget::createBuffers () { // Carreguem el model de l'OBJ - Atenció! Abans de crear els buffers! caps.load("./models/cow.obj"); // Calculem la capsa contenidora del model calculaCapsaModel (); // Creació del Vertex Array Object del Patricio glGenVertexArrays(1, &VAO_Caps); glBindVertexArray(VAO_Caps); // Creació dels buffers del model patr // Buffer de posicions glGenBuffers(1, &VBO_CapsPos); glBindBuffer(GL_ARRAY_BUFFER, VBO_CapsPos); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*caps.faces().size()*3*3, caps.VBO_vertices(), GL_STATIC_DRAW); // Activem l'atribut vertexLoc glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(vertexLoc); // Buffer de normals glGenBuffers(1, &VBO_CapsNorm); glBindBuffer(GL_ARRAY_BUFFER, VBO_CapsNorm); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*caps.faces().size()*3*3, caps.VBO_normals(), GL_STATIC_DRAW); glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(normalLoc); // En lloc del color, ara passem tots els paràmetres dels materials // Buffer de component ambient glGenBuffers(1, &VBO_CapsMatamb); glBindBuffer(GL_ARRAY_BUFFER, VBO_CapsMatamb); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*caps.faces().size()*3*3, caps.VBO_matamb(), GL_STATIC_DRAW); glVertexAttribPointer(matambLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matambLoc); // Buffer de component difusa glGenBuffers(1, &VBO_CapsMatdiff); glBindBuffer(GL_ARRAY_BUFFER, VBO_CapsMatdiff); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*caps.faces().size()*3*3, caps.VBO_matdiff(), GL_STATIC_DRAW); glVertexAttribPointer(matdiffLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matdiffLoc); // Buffer de component especular glGenBuffers(1, &VBO_CapsMatspec); glBindBuffer(GL_ARRAY_BUFFER, VBO_CapsMatspec); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*caps.faces().size()*3*3, caps.VBO_matspec(), GL_STATIC_DRAW); glVertexAttribPointer(matspecLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matspecLoc); // Buffer de component shininness glGenBuffers(1, &VBO_CapsMatshin); glBindBuffer(GL_ARRAY_BUFFER, VBO_CapsMatshin); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*caps.faces().size()*3, caps.VBO_matshin(), GL_STATIC_DRAW); glVertexAttribPointer(matshinLoc, 1, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matshinLoc); // Carreguem el model de l'OBJ - Atenció! Abans de crear els buffers! caps2.load("./models/Patricio.obj"); // Calculem la capsa contenidora del model calculaCapsaModel2 (); // Creació del Vertex Array Object del Patricio glGenVertexArrays(1, &VAO_Caps2); glBindVertexArray(VAO_Caps2); // Creació dels buffers del model patr // Buffer de posicions glGenBuffers(1, &VBO_Caps2Pos); glBindBuffer(GL_ARRAY_BUFFER, VBO_Caps2Pos); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*caps2.faces().size()*3*3, caps2.VBO_vertices(), GL_STATIC_DRAW); // Activem l'atribut vertexLoc glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(vertexLoc); // Buffer de normals glGenBuffers(1, &VBO_Caps2Norm); glBindBuffer(GL_ARRAY_BUFFER, VBO_Caps2Norm); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*caps2.faces().size()*3*3, caps2.VBO_normals(), GL_STATIC_DRAW); glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(normalLoc); // En lloc del color, ara passem tots els paràmetres dels materials // Buffer de component ambient glGenBuffers(1, &VBO_Caps2Matamb); glBindBuffer(GL_ARRAY_BUFFER, VBO_Caps2Matamb); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*caps2.faces().size()*3*3, caps2.VBO_matamb(), GL_STATIC_DRAW); glVertexAttribPointer(matambLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matambLoc); // Buffer de component difusa glGenBuffers(1, &VBO_Caps2Matdiff); glBindBuffer(GL_ARRAY_BUFFER, VBO_Caps2Matdiff); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*caps2.faces().size()*3*3, caps2.VBO_matdiff(), GL_STATIC_DRAW); glVertexAttribPointer(matdiffLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matdiffLoc); // Buffer de component especular glGenBuffers(1, &VBO_Caps2Matspec); glBindBuffer(GL_ARRAY_BUFFER, VBO_Caps2Matspec); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*caps2.faces().size()*3*3, caps2.VBO_matspec(), GL_STATIC_DRAW); glVertexAttribPointer(matspecLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matspecLoc); // Buffer de component shininness glGenBuffers(1, &VBO_Caps2Matshin); glBindBuffer(GL_ARRAY_BUFFER, VBO_Caps2Matshin); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*caps2.faces().size()*3, caps2.VBO_matshin(), GL_STATIC_DRAW); glVertexAttribPointer(matshinLoc, 1, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matshinLoc); // Dades del terra // VBO amb la posició dels vèrtexs glm::vec3 posterra[12] = { glm::vec3(-2.0, -1.0, 2.0), glm::vec3(2.0, -1.0, 2.0), glm::vec3(-2.0, -1.0, -2.0), glm::vec3(-2.0, -1.0, -2.0), glm::vec3(2.0, -1.0, 2.0), glm::vec3(2.0, -1.0, -2.0), glm::vec3(-2.0, -1.0, -2.0), glm::vec3(2.0, -1.0, -2.0), glm::vec3(-2.0, 1.0, -2.0), glm::vec3(-2.0, 1.0, -2.0), glm::vec3(2.0, -1.0, -2.0), glm::vec3(2.0, 1.0, -2.0) }; //________________________________________________________________ //___________________CALCUL MAX I MIN TERRA_______________________ maxTerra.x = minTerra.x = posterra[0].x; maxTerra.y = minTerra.y = posterra[0].y; maxTerra.z = minTerra.z = posterra[0].z; for (unsigned int i = 0; i < 12; i+=1) { if (posterra[i].x < minTerra.x) minTerra.x = posterra[i].x; if (posterra[i].x > maxTerra.x) maxTerra.x = posterra[i].x; if (posterra[i].y < minTerra.y) minTerra.y = posterra[i].y; if (posterra[i].y > maxTerra.y) maxTerra.y = posterra[i].y; if (posterra[i].z < minTerra.z) minTerra.z = posterra[i].z; if (posterra[i].z > maxTerra.z) maxTerra.z = posterra[i].z; } centreTerra.x = (minTerra.x+maxTerra.x)/2.0; centreTerra.y = (minTerra.y+maxTerra.y)/2.0; centreTerra.z = (minTerra.z+maxTerra.z)/2.0; //________________________________________________________ //_______________FI CALCUL________________________________ // VBO amb la normal de cada vèrtex glm::vec3 norm1 (0,1,0); glm::vec3 norm2 (0,0,1); glm::vec3 normterra[12] = { norm1, norm1, norm1, norm1, norm1, norm1, // la normal (0,1,0) per als primers dos triangles norm2, norm2, norm2, norm2, norm2, norm2 // la normal (0,0,1) per als dos últims triangles }; // Definim el material del terra glm::vec3 amb(0.2,0,0.2); glm::vec3 diff(0.8,0,0.8); glm::vec3 spec(0,0,0); float shin = 100; // Fem que aquest material afecti a tots els vèrtexs per igual glm::vec3 matambterra[12] = { amb, amb, amb, amb, amb, amb, amb, amb, amb, amb, amb, amb }; glm::vec3 matdiffterra[12] = { diff, diff, diff, diff, diff, diff, diff, diff, diff, diff, diff, diff }; glm::vec3 matspecterra[12] = { spec, spec, spec, spec, spec, spec, spec, spec, spec, spec, spec, spec }; float matshinterra[12] = { shin, shin, shin, shin, shin, shin, shin, shin, shin, shin, shin, shin }; // Creació del Vertex Array Object del terra glGenVertexArrays(1, &VAO_Terra); glBindVertexArray(VAO_Terra); glGenBuffers(1, &VBO_TerraPos); glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraPos); glBufferData(GL_ARRAY_BUFFER, sizeof(posterra), posterra, GL_STATIC_DRAW); // Activem l'atribut vertexLoc glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(vertexLoc); glGenBuffers(1, &VBO_TerraNorm); glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraNorm); glBufferData(GL_ARRAY_BUFFER, sizeof(normterra), normterra, GL_STATIC_DRAW); // Activem l'atribut normalLoc glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(normalLoc); // En lloc del color, ara passem tots els paràmetres dels materials // Buffer de component ambient glGenBuffers(1, &VBO_TerraMatamb); glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraMatamb); glBufferData(GL_ARRAY_BUFFER, sizeof(matambterra), matambterra, GL_STATIC_DRAW); glVertexAttribPointer(matambLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matambLoc); // Buffer de component difusa glGenBuffers(1, &VBO_TerraMatdiff); glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraMatdiff); glBufferData(GL_ARRAY_BUFFER, sizeof(matdiffterra), matdiffterra, GL_STATIC_DRAW); glVertexAttribPointer(matdiffLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matdiffLoc); // Buffer de component especular glGenBuffers(1, &VBO_TerraMatspec); glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraMatspec); glBufferData(GL_ARRAY_BUFFER, sizeof(matspecterra), matspecterra, GL_STATIC_DRAW); glVertexAttribPointer(matspecLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matspecLoc); // Buffer de component shininness glGenBuffers(1, &VBO_TerraMatshin); glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraMatshin); glBufferData(GL_ARRAY_BUFFER, sizeof(matshinterra), matshinterra, GL_STATIC_DRAW); glVertexAttribPointer(matshinLoc, 1, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matshinLoc); glBindVertexArray(0); }
void create() { Client::Context c(_cappedNs); string err; ASSERT(userCreateNS( _cappedNs.c_str(), fromjson( spec() ), err, false )); }
void rpc_request_task::enqueue(service_node* node) { spec().on_rpc_request_enqueue.execute(this); task::enqueue(node->computation()->get_pool(spec().pool_code)); }
void UmlClass::generate_decl(QTextStream & f_h, WrapperStr indent) { context.append(this); bool removed = FALSE; QVector<UmlItem*> ch = children(); const unsigned sup = ch.size(); QLOG_INFO() << "children.size() is: " << sup; const WrapperStr & stereotype = cpp_stereotype(); bool a_typedef = (stereotype == "typedef"); bool an_enum = (stereotype == "enum"); QLOG_INFO() << "the class is an enum: " << an_enum; const QList<UmlFormalParameter> formals = this->formals(); const QList<UmlActualParameter> actuals = this->actuals(); unsigned index; const char * p = cppDecl(); const char * pp = 0; const char * sep; bool nestedp = parent()->kind() == aClass; if (nestedp) indent += " "; while ((*p == ' ') || (*p == '\t')) indent += toLocale(p); if (*p != '#') f_h << indent; for (;;) { if (*p == 0) { if (pp == 0) break; // comment management done p = pp; pp = 0; if (*p == 0) break; if (*p != '#') f_h << indent; } if (*p == '\n') { f_h << toLocale(p); bool isNotNull = *p; bool isNotGrid = *p != '#'; bool isMembers = strncmp(p, "${members}", 10); bool isItems = strncmp(p, "${items}", 8); if (isNotNull && isNotGrid && (isMembers || isItems)) f_h << indent; } else if (*p == '@') manage_alias(p, f_h); else if (*p != '$') f_h << toLocale(p); else if (!strncmp(p, "${comment}", 10)) manage_comment(p, pp, CppSettings::isGenerateJavadocStyleComment()); else if (!strncmp(p, "${description}", 14)) manage_description(p, pp); else if (! strncmp(p, "${name}", 7)) { p += 7; f_h << name(); } else if (a_typedef) { if (!strncmp(p, "${type}", 7)) { p += 7; UmlClass::write(f_h, baseType(), FALSE); UmlClass * cl = baseType().type; if ((cl != 0) && !actuals.isEmpty()) { QList<UmlActualParameter>::ConstIterator ita; BooL need_space = FALSE; for (ita = actuals.begin(); ita != actuals.end(); ++ita) if ((*ita).superClass() == cl) if (!(*ita).generate(f_h, need_space)) // no specified value break; if (need_space) f_h << " >"; else f_h << '>'; } } else // strange f_h << toLocale(p); } else if (an_enum) { if (!strncmp(p, "${items}", 8)) { p += 8; // items declaration aVisibility current_visibility = DefaultVisibility; unsigned max = sup - 1; BooL first = TRUE; QLOG_INFO() << "Found enum"; for (index = 0; index < sup; index += 1) { UmlItem * it = ch[index]; QLOG_INFO() << "The item is of kind: " << it->kind(); switch (it->kind()) { case aClass: case aNcRelation: break; default: if (!((UmlClassItem *) it)->cppDecl().isEmpty()) { ((UmlClassItem *) it)->generate_decl(current_visibility, f_h, stereotype, indent, first, index == max); } } } if (*p == '}') f_h << indent; } else // strange f_h << toLocale(p); } else if (! strncmp(p, "${template}", 11)) { p += 11; // template if (!formals.isEmpty()) { sep = "template<"; const char * sep2 = "<"; BooL need_space = FALSE; QList<UmlFormalParameter>::ConstIterator itf; for (itf = formals.begin(); itf != formals.end(); ++itf) (*itf).generate(f_h, sep, sep2, need_space); f_h << ((need_space) ? " >\n" : ">\n"); if (nestedp) f_h << indent; } else if (name().find('<') != -1) { f_h << "template<>\n"; if (nestedp) f_h << indent; } } else if (! strncmp(p, "${inherit}", 10)) { p += 10; // inherit sep = " : "; for (index = 0; index != sup; index += 1) { UmlItem * x = ch[index]; if ((x->kind() == aRelation) && !((UmlRelation *) ch[index])->cppDecl().isEmpty()) ((UmlRelation *) x)->generate_inherit(sep, f_h, actuals, stereotype); } } else if (! strncmp(p, "${members}", 10)) { p += 10; // members declaration aVisibility current_visibility; current_visibility = ((stereotype == "struct") || (stereotype == "union")) ? PublicVisibility : DefaultVisibility; unsigned last = sup - 1; BooL first = TRUE; for (index = 0; index != sup; index += 1) { UmlItem * it = ch[index]; if ((it->kind() != aNcRelation) && !((UmlClassItem *) it)->cppDecl().isEmpty()) { QLOG_INFO() << "generating member declarations"; ((UmlClassItem *) it)->generate_decl(current_visibility, f_h, stereotype, indent, first, index == last); } } if (*p == '}') f_h << indent; } else if (!strncmp(p, "${inlines}", 10)) { p += 10; context.removeLast(); removed = TRUE; if (! nestedp) { // inline operations definition // template class members WrapperStr templates; WrapperStr cl_names; WrapperStr templates_tmplop; WrapperStr cl_names_tmplop; spec(templates, cl_names, templates_tmplop, cl_names_tmplop); for (index = 0; index != sup; index += 1) if (ch[index]->kind() != aNcRelation) ((UmlClassItem *) ch[index]) ->generate_def(f_h, indent, TRUE, templates, cl_names, templates_tmplop, cl_names_tmplop); } if (*p == '\n') p += 1; } else // strange f_h << toLocale(p); } if (! removed) context.removeLast(); }
void MyGLWidget::createBuffers () { // Carreguem el model de l'OBJ - Atenció! Abans de crear els buffers! //patr.load("/assig/idi/models/Patricio.obj"); patr.load("./models/cow.obj"); patr2.load("./models/Patricio.obj"); // Calculem la capsa contenidora del model calculaCapsaModel (); calculaCapsaModelCow (); // Creació del Vertex Array Object del Patricio glGenVertexArrays(1, &VAO_Patr); glBindVertexArray(VAO_Patr); // Creació dels buffers del model patr // Buffer de posicions glGenBuffers(1, &VBO_PatrPos); glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrPos); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3*3, patr.VBO_vertices(), GL_STATIC_DRAW); // Activem l'atribut vertexLoc glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(vertexLoc); // Buffer de normals glGenBuffers(1, &VBO_PatrNorm); glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrNorm); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3*3, patr.VBO_normals(), GL_STATIC_DRAW); glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(normalLoc); // En lloc del color, ara passem tots els paràmetres dels materials // Buffer de component ambient glGenBuffers(1, &VBO_PatrMatamb); glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrMatamb); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3*3, patr.VBO_matamb(), GL_STATIC_DRAW); glVertexAttribPointer(matambLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matambLoc); // Buffer de component difusa glGenBuffers(1, &VBO_PatrMatdiff); glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrMatdiff); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3*3, patr.VBO_matdiff(), GL_STATIC_DRAW); glVertexAttribPointer(matdiffLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matdiffLoc); // Buffer de component especular glGenBuffers(1, &VBO_PatrMatspec); glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrMatspec); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3*3, patr.VBO_matspec(), GL_STATIC_DRAW); glVertexAttribPointer(matspecLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matspecLoc); // Buffer de component shininness glGenBuffers(1, &VBO_PatrMatshin); glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrMatshin); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3, patr.VBO_matshin(), GL_STATIC_DRAW); glVertexAttribPointer(matshinLoc, 1, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matshinLoc); ////Segundo Patricio // Creació del Vertex Array Object del Patricio glGenVertexArrays(1, &VAO_Patr2); glBindVertexArray(VAO_Patr2); // Creació dels buffers del model patr // Buffer de posicions glGenBuffers(1, &VBO_PatrPos2); glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrPos2); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr2.faces().size()*3*3, patr2.VBO_vertices(), GL_STATIC_DRAW); // Activem l'atribut vertexLoc glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(vertexLoc); // Buffer de normals glGenBuffers(1, &VBO_PatrNorm2); glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrNorm2); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr2.faces().size()*3*3, patr2.VBO_normals(), GL_STATIC_DRAW); glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(normalLoc); // En lloc del color, ara passem tots els paràmetres dels materials // Buffer de component ambient glGenBuffers(1, &VBO_PatrMatamb2); glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrMatamb2); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr2.faces().size()*3*3, patr2.VBO_matamb(), GL_STATIC_DRAW); glVertexAttribPointer(matambLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matambLoc); // Buffer de component difusa glGenBuffers(1, &VBO_PatrMatdiff2); glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrMatdiff2); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr2.faces().size()*3*3, patr2.VBO_matdiff(), GL_STATIC_DRAW); glVertexAttribPointer(matdiffLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matdiffLoc); // Buffer de component especular glGenBuffers(1, &VBO_PatrMatspec2); glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrMatspec2); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr2.faces().size()*3*3, patr2.VBO_matspec(), GL_STATIC_DRAW); glVertexAttribPointer(matspecLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matspecLoc); // Buffer de component shininness glGenBuffers(1, &VBO_PatrMatshin2); glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrMatshin2); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr2.faces().size()*3, patr2.VBO_matshin(), GL_STATIC_DRAW); glVertexAttribPointer(matshinLoc, 1, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matshinLoc); // Dades del terra // VBO amb la posició dels vèrtexs glm::vec3 posterra[12] = { glm::vec3(-1.0, -1.0, 1.0), glm::vec3(1.0, -1.0, 1.0), glm::vec3(-1.0, -1.0, -1.0), glm::vec3(-1.0, -1.0, -1.0), glm::vec3(1.0, -1.0, 1.0), glm::vec3(1.0, -1.0, -1.0), glm::vec3(-1.0, -1.0, -1.0), glm::vec3(1.0, -1.0, -1.0), glm::vec3(-1.0, 1.0, -1.0), glm::vec3(-1.0, 1.0, -1.0), glm::vec3(1.0, -1.0, -1.0), glm::vec3(1.0, 1.0, -1.0) }; // VBO amb la normal de cada vèrtex glm::vec3 norm1 (0,1,0); glm::vec3 norm2 (0,0,1); glm::vec3 normterra[12] = { norm1, norm1, norm1, norm1, norm1, norm1, // la normal (0,1,0) per als primers dos triangles norm2, norm2, norm2, norm2, norm2, norm2 // la normal (0,0,1) per als dos últims triangles }; // Definim el material del terra glm::vec3 amb(0.2,0,0.2); glm::vec3 diff(0.8,0,0.8); glm::vec3 spec(0,0,0); float shin = 100; // Fem que aquest material afecti a tots els vèrtexs per igual glm::vec3 matambterra[12] = { amb, amb, amb, amb, amb, amb, amb, amb, amb, amb, amb, amb }; glm::vec3 matdiffterra[12] = { diff, diff, diff, diff, diff, diff, diff, diff, diff, diff, diff, diff }; glm::vec3 matspecterra[12] = { spec, spec, spec, spec, spec, spec, spec, spec, spec, spec, spec, spec }; float matshinterra[12] = { shin, shin, shin, shin, shin, shin, shin, shin, shin, shin, shin, shin }; // Creació del Vertex Array Object del terra glGenVertexArrays(1, &VAO_Terra); glBindVertexArray(VAO_Terra); glGenBuffers(1, &VBO_TerraPos); glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraPos); glBufferData(GL_ARRAY_BUFFER, sizeof(posterra), posterra, GL_STATIC_DRAW); // Activem l'atribut vertexLoc glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(vertexLoc); glGenBuffers(1, &VBO_TerraNorm); glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraNorm); glBufferData(GL_ARRAY_BUFFER, sizeof(normterra), normterra, GL_STATIC_DRAW); // Activem l'atribut normalLoc glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(normalLoc); // En lloc del color, ara passem tots els paràmetres dels materials // Buffer de component ambient glGenBuffers(1, &VBO_TerraMatamb); glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraMatamb); glBufferData(GL_ARRAY_BUFFER, sizeof(matambterra), matambterra, GL_STATIC_DRAW); glVertexAttribPointer(matambLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matambLoc); // Buffer de component difusa glGenBuffers(1, &VBO_TerraMatdiff); glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraMatdiff); glBufferData(GL_ARRAY_BUFFER, sizeof(matdiffterra), matdiffterra, GL_STATIC_DRAW); glVertexAttribPointer(matdiffLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matdiffLoc); // Buffer de component especular glGenBuffers(1, &VBO_TerraMatspec); glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraMatspec); glBufferData(GL_ARRAY_BUFFER, sizeof(matspecterra), matspecterra, GL_STATIC_DRAW); glVertexAttribPointer(matspecLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matspecLoc); // Buffer de component shininness glGenBuffers(1, &VBO_TerraMatshin); glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraMatshin); glBufferData(GL_ARRAY_BUFFER, sizeof(matshinterra), matshinterra, GL_STATIC_DRAW); glVertexAttribPointer(matshinLoc, 1, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matshinLoc); glBindVertexArray(0); }
// // * - type ... calgray, calrgb, cielab, icc, [palette] // * - white = x, z // * - black = x, y, z // * - range = amin, amax, bmin, bmax (cielab) // * - gamma = val [,val, val] (calgray [,calrgb]) // * - matrix = 9 vals (calrgb) // * - profile = file-path (icc based) // * - name = sRGB .. some predefined name IColorSpaceMan::cs_handle_pair_t ColorSpaceManImpl::color_space_load(Char const* spec_str) { ParseArgs pargs(&g_cs_kwds, &g_cs_names); ParsedResult pres(parse_options(spec_str, pargs)); unsigned name = pres.explicit_value(); if (name == ParsedResult::NO_EXPL_VALUE) throw exception_invalid_value(msg_invalid_cs_spec()) << JAGLOC; cs_str_spec_t spec(name, pres); cs_handle_pair_t result; switch (name) { case CSN_SRGB: result.first = register_icc_from_memory(binres::icc_srgb, binres::icc_srgb_size, 3); break; case CSN_ADOBE_RGB: result.first = register_icc_from_memory(binres::icc_adobe_rgb, binres::icc_adobe_rgb_size, 3); break; case CSN_BYID: if (!spec.id) throw exception_invalid_value(msg_invalid_cs_spec()) << JAGLOC; result.first = ColorSpaceHandle( handle_from_id<RESOURCE_COLOR_SPACE>(spec.id)); break; case CSN_DEVICE_RGB: result.first = ColorSpaceHandle(CS_DEVICE_RGB); break; case CSN_DEVICE_GRAY: result.first = ColorSpaceHandle(CS_DEVICE_GRAY); break; case CSN_DEVICE_CMYK: result.first = ColorSpaceHandle(CS_DEVICE_CMYK); break; case CSN_CALGRAY: { intrusive_ptr<ICIECalGray> gray(define_calgray()); set_cie_base(spec, *gray); if (!spec.gamma.empty()) gray->gamma(spec.gamma[0]); result.first = color_space_load(gray); break; } case CSN_CALRGB: { intrusive_ptr<ICIECalRGB> rgb(define_calrgb()); set_cie_base(spec, *rgb); if (!spec.gamma.empty()) { JAG_ASSERT(spec.gamma.size()==3); rgb->gamma(spec.gamma[0], spec.gamma[1], spec.gamma[2]); } if (!spec.matrix.empty()) { JAG_ASSERT(spec.matrix.size()==9); rgb->matrix(spec.matrix[0], spec.matrix[1], spec.matrix[2], spec.matrix[3], spec.matrix[4], spec.matrix[5], spec.matrix[6], spec.matrix[7], spec.matrix[8]); } result.first = color_space_load(rgb); break; } case CSN_CIELAB: { intrusive_ptr<ICIELab> lab(define_cielab()); set_cie_base(spec, *lab); if (!spec.range.empty()) { JAG_ASSERT(4 == spec.range.size()); lab->range(spec.range[0], spec.range[1], spec.range[2], spec.range[3]); } result.first = color_space_load(lab); break; } case CSN_ICC: { if (-1==spec.components || spec.icc_profile.empty()) throw exception_invalid_value(msg_invalid_cs_spec()) << JAGLOC; intrusive_ptr<IICCBased> icc(define_iccbased()); icc->num_components(spec.components); icc->icc_profile(spec.icc_profile.c_str()); result.first = color_space_load(icc); break; } default: ; } // switch JAG_ASSERT(is_valid(result.first)); // is it palette? if (!spec.palette.empty()) { intrusive_ptr<IPalette> indexed(define_indexed()); indexed->set( id_from_handle<ColorSpace>(result.first), &spec.palette[0], static_cast<UInt>(spec.palette.size())); result.second = result.first; result.first = color_space_load(indexed); } return result; }
void TenuredGeneration::compute_new_size() { assert(_shrink_factor <= 100, "invalid shrink factor"); size_t current_shrink_factor = _shrink_factor; _shrink_factor = 0; // We don't have floating point command-line arguments // Note: argument processing ensures that MinHeapFreeRatio < 100. const double minimum_free_percentage = MinHeapFreeRatio / 100.0; const double maximum_used_percentage = 1.0 - minimum_free_percentage; // Compute some numbers about the state of the heap. const size_t used_after_gc = used(); const size_t capacity_after_gc = capacity(); const double min_tmp = used_after_gc / maximum_used_percentage; size_t minimum_desired_capacity = (size_t)MIN2(min_tmp, double(max_uintx)); // Don't shrink less than the initial generation size minimum_desired_capacity = MAX2(minimum_desired_capacity, spec()->init_size()); assert(used_after_gc <= minimum_desired_capacity, "sanity check"); if (PrintGC && Verbose) { const size_t free_after_gc = free(); const double free_percentage = ((double)free_after_gc) / capacity_after_gc; gclog_or_tty->print_cr("TenuredGeneration::compute_new_size: "); gclog_or_tty->print_cr(" " " minimum_free_percentage: %6.2f" " maximum_used_percentage: %6.2f", minimum_free_percentage, maximum_used_percentage); gclog_or_tty->print_cr(" " " free_after_gc : %6.1fK" " used_after_gc : %6.1fK" " capacity_after_gc : %6.1fK", free_after_gc / (double) K, used_after_gc / (double) K, capacity_after_gc / (double) K); gclog_or_tty->print_cr(" " " free_percentage: %6.2f", free_percentage); } if (capacity_after_gc < minimum_desired_capacity) { // If we have less free space than we want then expand size_t expand_bytes = minimum_desired_capacity - capacity_after_gc; // Don't expand unless it's significant if (expand_bytes >= _min_heap_delta_bytes) { expand(expand_bytes, 0); // safe if expansion fails } if (PrintGC && Verbose) { gclog_or_tty->print_cr(" expanding:" " minimum_desired_capacity: %6.1fK" " expand_bytes: %6.1fK" " _min_heap_delta_bytes: %6.1fK", minimum_desired_capacity / (double) K, expand_bytes / (double) K, _min_heap_delta_bytes / (double) K); } return; } // No expansion, now see if we want to shrink size_t shrink_bytes = 0; // We would never want to shrink more than this size_t max_shrink_bytes = capacity_after_gc - minimum_desired_capacity; if (MaxHeapFreeRatio < 100) { const double maximum_free_percentage = MaxHeapFreeRatio / 100.0; const double minimum_used_percentage = 1.0 - maximum_free_percentage; const double max_tmp = used_after_gc / minimum_used_percentage; size_t maximum_desired_capacity = (size_t)MIN2(max_tmp, double(max_uintx)); maximum_desired_capacity = MAX2(maximum_desired_capacity, spec()->init_size()); if (PrintGC && Verbose) { gclog_or_tty->print_cr(" " " maximum_free_percentage: %6.2f" " minimum_used_percentage: %6.2f", maximum_free_percentage, minimum_used_percentage); gclog_or_tty->print_cr(" " " _capacity_at_prologue: %6.1fK" " minimum_desired_capacity: %6.1fK" " maximum_desired_capacity: %6.1fK", _capacity_at_prologue / (double) K, minimum_desired_capacity / (double) K, maximum_desired_capacity / (double) K); } assert(minimum_desired_capacity <= maximum_desired_capacity, "sanity check"); if (capacity_after_gc > maximum_desired_capacity) { // Capacity too large, compute shrinking size shrink_bytes = capacity_after_gc - maximum_desired_capacity; // We don't want shrink all the way back to initSize if people call // System.gc(), because some programs do that between "phases" and then // we'd just have to grow the heap up again for the next phase. So we // damp the shrinking: 0% on the first call, 10% on the second call, 40% // on the third call, and 100% by the fourth call. But if we recompute // size without shrinking, it goes back to 0%. shrink_bytes = shrink_bytes / 100 * current_shrink_factor; assert(shrink_bytes <= max_shrink_bytes, "invalid shrink size"); if (current_shrink_factor == 0) { _shrink_factor = 10; } else { _shrink_factor = MIN2(current_shrink_factor * 4, (size_t) 100); } if (PrintGC && Verbose) { gclog_or_tty->print_cr(" " " shrinking:" " initSize: %.1fK" " maximum_desired_capacity: %.1fK", spec()->init_size() / (double) K, maximum_desired_capacity / (double) K); gclog_or_tty->print_cr(" " " shrink_bytes: %.1fK" " current_shrink_factor: %d" " new shrink factor: %d" " _min_heap_delta_bytes: %.1fK", shrink_bytes / (double) K, current_shrink_factor, _shrink_factor, _min_heap_delta_bytes / (double) K); } } } if (capacity_after_gc > _capacity_at_prologue) { // We might have expanded for promotions, in which case we might want to // take back that expansion if there's room after GC. That keeps us from // stretching the heap with promotions when there's plenty of room. size_t expansion_for_promotion = capacity_after_gc - _capacity_at_prologue; expansion_for_promotion = MIN2(expansion_for_promotion, max_shrink_bytes); // We have two shrinking computations, take the largest shrink_bytes = MAX2(shrink_bytes, expansion_for_promotion); assert(shrink_bytes <= max_shrink_bytes, "invalid shrink size"); if (PrintGC && Verbose) { gclog_or_tty->print_cr(" " " aggressive shrinking:" " _capacity_at_prologue: %.1fK" " capacity_after_gc: %.1fK" " expansion_for_promotion: %.1fK" " shrink_bytes: %.1fK", capacity_after_gc / (double) K, _capacity_at_prologue / (double) K, expansion_for_promotion / (double) K, shrink_bytes / (double) K); } } // Don't shrink unless it's significant if (shrink_bytes >= _min_heap_delta_bytes) { shrink(shrink_bytes); } assert(used() == used_after_gc && used_after_gc <= capacity(), "sanity check"); }
bool OpenEXRInput::read_native_deep_tiles (int xbegin, int xend, int ybegin, int yend, int zbegin, int zend, int chbegin, int chend, DeepData &deepdata) { if (m_deep_tiled_input_part == NULL) { error ("called OpenEXRInput::read_native_deep_tiles without an open file"); return false; } #ifdef USE_OPENEXR_VERSION2 try { const PartInfo &part (m_parts[m_subimage]); size_t width = (xend - xbegin); size_t npixels = width * (yend - ybegin) * (zend - zbegin); chend = clamp (chend, chbegin+1, m_spec.nchannels); int nchans = chend - chbegin; // Set up the count and pointers arrays and the Imf framebuffer std::vector<TypeDesc> channeltypes; m_spec.get_channelformats (channeltypes); deepdata.init (npixels, nchans, array_view<const TypeDesc>(&channeltypes[chbegin], chend-chbegin), spec().channelnames); std::vector<unsigned int> all_samples (npixels); std::vector<void*> pointerbuf (npixels * nchans); Imf::DeepFrameBuffer frameBuffer; Imf::Slice countslice (Imf::UINT, (char *)(&all_samples[0] - xbegin - ybegin*width), sizeof(unsigned int), sizeof(unsigned int) * width); frameBuffer.insertSampleCountSlice (countslice); for (int c = chbegin; c < chend; ++c) { Imf::DeepSlice slice (part.pixeltype[c], (char *)(&pointerbuf[0]+(c-chbegin) - xbegin*nchans - ybegin*width*nchans), sizeof(void*) * nchans, // xstride of pointer array sizeof(void*) * nchans*width, // ystride of pointer array deepdata.samplesize()); // stride of data sample frameBuffer.insert (m_spec.channelnames[c].c_str(), slice); } m_deep_tiled_input_part->setFrameBuffer (frameBuffer); int xtiles = round_to_multiple (xend-xbegin, m_spec.tile_width) / m_spec.tile_width; int ytiles = round_to_multiple (yend-ybegin, m_spec.tile_height) / m_spec.tile_height; int firstxtile = (xbegin - m_spec.x) / m_spec.tile_width; int firstytile = (ybegin - m_spec.y) / m_spec.tile_height; // Get the sample counts for each pixel and compute the total // number of samples and resize the data area appropriately. m_deep_tiled_input_part->readPixelSampleCounts ( firstxtile, firstxtile+xtiles-1, firstytile, firstytile+ytiles-1); deepdata.set_all_samples (all_samples); deepdata.get_pointers (pointerbuf); // Read the pixels m_deep_tiled_input_part->readTiles ( firstxtile, firstxtile+xtiles-1, firstytile, firstytile+ytiles-1, m_miplevel, m_miplevel); } catch (const std::exception &e) { error ("Failed OpenEXR read: %s", e.what()); return false; } catch (...) { // catch-all for edge cases or compiler bugs error ("Failed OpenEXR read: unknown exception"); return false; } return true; #else return false; #endif }
bool ImageInput::read_scanlines (int ybegin, int yend, int z, int chbegin, int chend, TypeDesc format, void *data, stride_t xstride, stride_t ystride) { chend = clamp (chend, chbegin+1, m_spec.nchannels); int nchans = chend - chbegin; yend = std::min (yend, spec().y+spec().height); size_t native_pixel_bytes = m_spec.pixel_bytes (chbegin, chend, true); imagesize_t native_scanline_bytes = clamped_mult64 ((imagesize_t)m_spec.width, (imagesize_t)native_pixel_bytes); bool native = (format == TypeDesc::UNKNOWN); size_t pixel_bytes = native ? native_pixel_bytes : format.size()*nchans; if (native && xstride == AutoStride) xstride = pixel_bytes; stride_t zstride = AutoStride; m_spec.auto_stride (xstride, ystride, zstride, format, nchans, m_spec.width, m_spec.height); bool contiguous = (xstride == (stride_t) native_pixel_bytes && ystride == (stride_t) native_scanline_bytes); // If user's format and strides are set up to accept the native data // layout, read the scanlines directly into the user's buffer. bool rightformat = (format == TypeDesc::UNKNOWN) || (format == m_spec.format && m_spec.channelformats.empty()); if (rightformat && contiguous) { if (chbegin == 0 && chend == m_spec.nchannels) return read_native_scanlines (ybegin, yend, z, data); else return read_native_scanlines (ybegin, yend, z, chbegin, chend, data); } // No such luck. Read scanlines in chunks. const imagesize_t limit = 16*1024*1024; // Allocate 16 MB, or 1 scanline int chunk = std::max (1, int(limit / native_scanline_bytes)); boost::scoped_array<char> buf (new char [chunk * native_scanline_bytes]); bool ok = true; int scanline_values = m_spec.width * nchans; for (; ok && ybegin < yend; ybegin += chunk) { int y1 = std::min (ybegin+chunk, yend); ok &= read_native_scanlines (ybegin, y1, z, chbegin, chend, &buf[0]); if (! ok) break; int nscanlines = y1 - ybegin; int chunkvalues = scanline_values * nscanlines; if (m_spec.channelformats.empty()) { // No per-channel formats -- do the conversion in one shot if (contiguous) { ok = convert_types (m_spec.format, &buf[0], format, data, chunkvalues); } else { ok = parallel_convert_image (nchans, m_spec.width, nscanlines, 1, &buf[0], m_spec.format, AutoStride, AutoStride, AutoStride, data, format, xstride, ystride, zstride); } } else { // Per-channel formats -- have to convert/copy channels individually size_t offset = 0; for (int c = 0; ok && c < nchans; ++c) { TypeDesc chanformat = m_spec.channelformats[c+chbegin]; ok = convert_image (1 /* channels */, m_spec.width, nscanlines, 1, &buf[offset], chanformat, native_pixel_bytes, AutoStride, AutoStride, (char *)data + c*format.size(), format, xstride, ystride, zstride); offset += chanformat.size (); } } if (! ok) error ("ImageInput::read_scanlines : no support for format %s", m_spec.format.c_str()); data = (char *)data + ystride*nscanlines; } return ok; }
void ImageBuf::setpixel (int i, const float *pixel, int maxchannels) { setpixel (spec().x + (i % spec().width), spec().y + (i / spec().width), pixel, maxchannels); }
void MyGLWidget::createBuffers () { // Carreguem el model de l'OBJ - Atenció! Abans de crear els buffers! patr.load("./models/Patricio.obj"); // Calculem la capsa contenidora del model calculaCapsaModel (); // Creació del Vertex Array Object del Patricio glGenVertexArrays(1, &VAO_Patr); glBindVertexArray(VAO_Patr); // Creació dels buffers del model patr // Buffer de posicions glGenBuffers(1, &VBO_PatrPos); glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrPos); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3*3, patr.VBO_vertices(), GL_STATIC_DRAW); // Activem l'atribut vertexLoc glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(vertexLoc); // Buffer de normals glGenBuffers(1, &VBO_PatrNorm); glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrNorm); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3*3, patr.VBO_normals(), GL_STATIC_DRAW); glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(normalLoc); // En lloc del color, ara passem tots els paràmetres dels materials // Buffer de component ambient glGenBuffers(1, &VBO_PatrMatamb); glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrMatamb); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3*3, patr.VBO_matamb(), GL_STATIC_DRAW); glVertexAttribPointer(matambLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matambLoc); // Buffer de component difusa glGenBuffers(1, &VBO_PatrMatdiff); glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrMatdiff); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3*3, patr.VBO_matdiff(), GL_STATIC_DRAW); glVertexAttribPointer(matdiffLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matdiffLoc); // Buffer de component especular glGenBuffers(1, &VBO_PatrMatspec); glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrMatspec); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3*3, patr.VBO_matspec(), GL_STATIC_DRAW); glVertexAttribPointer(matspecLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matspecLoc); // Buffer de component shininness glGenBuffers(1, &VBO_PatrMatshin); glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrMatshin); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3, patr.VBO_matshin(), GL_STATIC_DRAW); glVertexAttribPointer(matshinLoc, 1, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matshinLoc); //LEGOMAN // Carreguem el model de l'OBJ - Atenció! Abans de crear els buffers! lego.load("./models/legoman.obj"); // Calculem la capsa contenidora del model calculaCapsaCirc (); // Creació del Vertex Array Object del Legoman glGenVertexArrays(1, &VAO_lego); glBindVertexArray(VAO_lego); // Creació dels buffers del model lego // Buffer de posicions glGenBuffers(1, &VBO_legoPos); glBindBuffer(GL_ARRAY_BUFFER, VBO_legoPos); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*lego.faces().size()*3*3, lego.VBO_vertices(), GL_STATIC_DRAW); // Activem l'atribut vertexLoc glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(vertexLoc); // Buffer de normals glGenBuffers(1, &VBO_legoNorm); glBindBuffer(GL_ARRAY_BUFFER, VBO_legoNorm); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*lego.faces().size()*3*3, lego.VBO_normals(), GL_STATIC_DRAW); glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(normalLoc); // En lloc del color, ara passem tots els paràmetres dels materials // Buffer de component ambient glGenBuffers(1, &VBO_legoMatamb); glBindBuffer(GL_ARRAY_BUFFER, VBO_legoMatamb); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*lego.faces().size()*3*3, lego.VBO_matamb(), GL_STATIC_DRAW); glVertexAttribPointer(matambLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matambLoc); // Buffer de component difusa glGenBuffers(1, &VBO_legoMatdiff); glBindBuffer(GL_ARRAY_BUFFER, VBO_legoMatdiff); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*lego.faces().size()*3*3, lego.VBO_matdiff(), GL_STATIC_DRAW); glVertexAttribPointer(matdiffLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matdiffLoc); // Buffer de component especular glGenBuffers(1, &VBO_legoMatspec); glBindBuffer(GL_ARRAY_BUFFER, VBO_legoMatspec); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*lego.faces().size()*3*3, lego.VBO_matspec(), GL_STATIC_DRAW); glVertexAttribPointer(matspecLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matspecLoc); // Buffer de component shininness glGenBuffers(1, &VBO_legoMatshin); glBindBuffer(GL_ARRAY_BUFFER, VBO_legoMatshin); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*lego.faces().size()*3, lego.VBO_matshin(), GL_STATIC_DRAW); glVertexAttribPointer(matshinLoc, 1, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matshinLoc); // Dades del terra // VBO amb la posició dels vèrtexs glm::vec3 posterra[4] = { glm::vec3( 10.0, 0.0, -10.0), glm::vec3( 10.0, 0.0, 10.0), glm::vec3(-10.0, 0.0, -10.0), glm::vec3(-10.0, 0.0, 10.0) }; // VBO amb la normal de cada vèrtex glm::vec3 norm (0,1,0); glm::vec3 normterra[4] = { norm, norm, norm, norm }; // Definim el material del terra glm::vec3 amb(0.1,0.09,0.); glm::vec3 diff(0.,0.8,0.); glm::vec3 spec(1.,1.,1.); float shin = 100; // Fem que aquest material afecti a tots els vèrtexs per igual glm::vec3 matambterra[4] = { amb, amb, amb, amb }; glm::vec3 matdiffterra[4] = { diff, diff, diff, diff }; glm::vec3 matspecterra[4] = { spec, spec, spec, spec }; float matshinterra[4] = { shin, shin, shin, shin }; // Creació del Vertex Array Object del terra glGenVertexArrays(1, &VAO_Terra); glBindVertexArray(VAO_Terra); glGenBuffers(1, &VBO_TerraPos); glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraPos); glBufferData(GL_ARRAY_BUFFER, sizeof(posterra), posterra, GL_STATIC_DRAW); // Activem l'atribut vertexLoc glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(vertexLoc); glGenBuffers(1, &VBO_TerraNorm); glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraNorm); glBufferData(GL_ARRAY_BUFFER, sizeof(normterra), normterra, GL_STATIC_DRAW); // Activem l'atribut normalLoc glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(normalLoc); // En lloc del color, ara passem tots els paràmetres dels materials // Buffer de component ambient glGenBuffers(1, &VBO_TerraMatamb); glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraMatamb); glBufferData(GL_ARRAY_BUFFER, sizeof(matambterra), matambterra, GL_STATIC_DRAW); glVertexAttribPointer(matambLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matambLoc); // Buffer de component difusa glGenBuffers(1, &VBO_TerraMatdiff); glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraMatdiff); glBufferData(GL_ARRAY_BUFFER, sizeof(matdiffterra), matdiffterra, GL_STATIC_DRAW); glVertexAttribPointer(matdiffLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matdiffLoc); // Buffer de component especular glGenBuffers(1, &VBO_TerraMatspec); glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraMatspec); glBufferData(GL_ARRAY_BUFFER, sizeof(matspecterra), matspecterra, GL_STATIC_DRAW); glVertexAttribPointer(matspecLoc, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matspecLoc); // Buffer de component shininness glGenBuffers(1, &VBO_TerraMatshin); glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraMatshin); glBufferData(GL_ARRAY_BUFFER, sizeof(matshinterra), matshinterra, GL_STATIC_DRAW); glVertexAttribPointer(matshinLoc, 1, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(matshinLoc); glBindVertexArray(0); }
void fill_poisson_mixture_approximation_table_1( NormalMixtureApproximationTable *table) { //---------------------------------------------------------------------- // nu = 1 kl = 1.55587e-05 { NormalMixtureApproximation spec( BOOM::Vector("-1.10017 4.63951 3.13821 2.10282 0.885889 0.174309 -0.465988 0.228799 0.671705 2.71379"), BOOM::Vector("0.383782 2.17443 1.42327 0.586083 0.719241 0.508172 0.464148 0.446046 0.628454 0.814524"), BOOM::Vector("0.051647 0.00554244 0.0441814 0.0478747 0.356135 0.0856119 0.256498 0.0887642 0.0172381 0.0465076")); table->add(1, spec); } //---------------------------------------------------------------------- // nu = 2 kl = 8.45545e-05 { NormalMixtureApproximation spec( BOOM::Vector("-1.3477 0.858862 -0.928641 -0.780994 0.33308 -0.00631014 -0.812043 -0.413538 -0.236343 -0.267196"), BOOM::Vector("0.353737 1.09171 0.422356 0.445879 0.718825 0.622078 0.423838 0.529212 0.476274 0.516796"), BOOM::Vector("0.107311 0.0467586 0.0830307 0.108579 0.149063 0.0845241 0.153324 0.078107 0.0596707 0.129633")); table->add(2, spec); } //---------------------------------------------------------------------- // nu = 3 kl = -9.23107e-06 { NormalMixtureApproximation spec( BOOM::Vector("-0.22326 -0.10081 -1.11593 -0.743897 -1.47646 -1.23108 -0.669934 -1.01269 0.400115 -1.82461"), BOOM::Vector("0.40346 0.628081 0.294969 0.404837 0.293553 0.367995 0.343763 0.393868 0.881989 0.277423"), BOOM::Vector("0.0793824 0.0953603 0.109487 0.217827 0.172565 0.0638406 0.0379442 0.164582 0.00983275 0.0491789")); table->add(3, spec); } //---------------------------------------------------------------------- // nu = 4 kl = 8.98929e-05 { NormalMixtureApproximation spec( BOOM::Vector("-1.10537 -1.05435 -1.583 -1.9239 -0.963913 -1.06215 -1.42551 -0.684022 -1.23966 -1.5737"), BOOM::Vector("0.44342 0.438956 0.295335 0.264879 0.448243 0.43186 0.345451 0.636252 0.309343 0.276064"), BOOM::Vector("0.0935312 0.103366 0.113602 0.0930069 0.0926803 0.0884835 0.0626031 0.111189 0.131113 0.110425")); table->add(4, spec); } //---------------------------------------------------------------------- // nu = 5 kl = 1.47037e-05 { NormalMixtureApproximation spec( BOOM::Vector("-1.5118 -1.22628 -1.63669 -1.33663 -0.906453 -1.80417 -1.25535 -2.04477 -1.50231 -1.14495"), BOOM::Vector("0.313541 0.414644 0.276942 0.344436 0.576564 0.22352 0.409026 0.256978 0.300562 0.427996"), BOOM::Vector("0.112605 0.0887378 0.139101 0.0850069 0.0536112 0.0878054 0.070821 0.153145 0.104148 0.105019")); table->add(5, spec); } //---------------------------------------------------------------------- // nu = 6 kl = 3.89138e-06 { NormalMixtureApproximation spec( BOOM::Vector("-1.17601 -1.63461 -1.83448 -2.28023 -1.47591 -1.67298 -1.46829 -1.18444 -2.03269 -1.51588"), BOOM::Vector("0.523049 0.291187 0.198541 0.225656 0.280095 0.211637 0.332143 0.344228 0.217072 0.301913"), BOOM::Vector("0.0467676 0.152629 0.0971597 0.0851477 0.120512 0.0994461 0.0481825 0.0946917 0.222209 0.0332553")); table->add(6, spec); } //---------------------------------------------------------------------- // nu = 7 kl = 4.38059e-07 { NormalMixtureApproximation spec( BOOM::Vector("-1.95409 -1.5987 -2.38938 -1.88714 -1.67858 -1.26291 -2.22767 -1.36283 -2.03974 -1.79702"), BOOM::Vector("0.24874 0.31425 0.217831 0.268854 0.307241 0.497019 0.196812 0.367221 0.214022 0.24747"), BOOM::Vector("0.0979245 0.111223 0.089909 0.093848 0.15818 0.0138501 0.0928954 0.0722608 0.157491 0.112417")); table->add(7, spec); } //---------------------------------------------------------------------- // nu = 8 kl = 1.29294e-06 { NormalMixtureApproximation spec( BOOM::Vector("-2.30217 -2.15613 -1.91148 -1.54833 -1.85478 -2.47531 -2.04351 -1.65014 -2.10472 -1.76658"), BOOM::Vector("0.194811 0.223825 0.274489 0.443433 0.258878 0.211065 0.251567 0.332834 0.221687 0.322762"), BOOM::Vector("0.0993276 0.0975451 0.134871 0.0321373 0.103546 0.103078 0.124797 0.0994464 0.118788 0.0864636")); table->add(8, spec); } //---------------------------------------------------------------------- // nu = 9 kl = 4.53982e-06 { NormalMixtureApproximation spec( BOOM::Vector("-2.5401 -2.29312 -2.08495 -2.15647 -2.30637 -1.91603 -2.03128 -1.85113 -1.77696 -2.29659"), BOOM::Vector("0.209626 0.231174 0.274278 0.258245 0.231812 0.301126 0.233743 0.294184 0.400296 0.222109"), BOOM::Vector("0.102804 0.0822189 0.0894677 0.112456 0.0944807 0.113298 0.112262 0.0896138 0.0656408 0.137758")); table->add(9, spec); } //---------------------------------------------------------------------- // nu = 10 kl = 3.83057e-07 { NormalMixtureApproximation spec( BOOM::Vector("-2.16845 -2.25588 -2.19865 -1.90242 -2.06094 -2.11239 -1.84307 -2.51369 -2.36089 -2.65598"), BOOM::Vector("0.248697 0.202707 0.25112 0.293086 0.250231 0.243349 0.391287 0.175322 0.176943 0.194795"), BOOM::Vector("0.0923346 0.171586 0.0723437 0.110928 0.095274 0.0821783 0.0265003 0.131075 0.109546 0.108234")); table->add(10, spec); } //---------------------------------------------------------------------- // nu = 11 kl = 8.47546e-07 { NormalMixtureApproximation spec( BOOM::Vector("-2.22232 -2.29665 -2.16183 -2.39302 -2.57522 -2.25139 -1.98906 -2.00743 -2.74873 -2.39589"), BOOM::Vector("0.260293 0.238146 0.215392 0.1938 0.182653 0.234875 0.258872 0.362308 0.186749 0.209153"), BOOM::Vector("0.0927876 0.100831 0.0752709 0.124486 0.174055 0.0721123 0.0836925 0.0444238 0.0863255 0.146014")); table->add(11, spec); } //---------------------------------------------------------------------- // nu = 12 kl = 4.29371e-06 { NormalMixtureApproximation spec( BOOM::Vector("-2.19049 -2.3886 -2.27972 -2.53907 -2.32686 -2.64601 -2.48734 -2.80491 -2.27897 -2.46083"), BOOM::Vector("0.335353 0.245024 0.254954 0.208269 0.251906 0.166496 0.199451 0.180348 0.257982 0.199256"), BOOM::Vector("0.104595 0.0904034 0.0878298 0.082432 0.102242 0.103936 0.101115 0.103654 0.0978934 0.1259")); table->add(12, spec); } //---------------------------------------------------------------------- // nu = 13 kl = 3.09935e-07 { NormalMixtureApproximation spec( BOOM::Vector("-2.50814 -2.87985 -2.5114 -2.56513 -2.25455 -2.21383 -2.45251 -2.72674 -2.49844 -2.39733"), BOOM::Vector("0.219854 0.176586 0.220641 0.165629 0.250955 0.330506 0.218216 0.167059 0.219848 0.224279"), BOOM::Vector("0.0971237 0.094922 0.0993836 0.102112 0.132761 0.0389869 0.0846605 0.16732 0.0984257 0.0843056")); table->add(13, spec); } //---------------------------------------------------------------------- // nu = 14 kl = 1.53499e-06 { NormalMixtureApproximation spec( BOOM::Vector("-2.71819 -2.39403 -2.91088 -2.58549 -2.34768 -2.46503 -2.61749 -2.47247 -2.60676 -2.75375"), BOOM::Vector("0.188596 0.238503 0.177131 0.202064 0.309244 0.239031 0.209365 0.241211 0.210188 0.169953"), BOOM::Vector("0.0887803 0.0968716 0.119126 0.118051 0.0737052 0.0877944 0.0936813 0.0792559 0.145228 0.0975057")); table->add(14, spec); } //---------------------------------------------------------------------- // nu = 15 kl = 1.33612e-06 { NormalMixtureApproximation spec( BOOM::Vector("-2.83187 -2.97929 -2.5351 -2.693 -2.72854 -2.63332 -2.62734 -2.71848 -2.43859 -2.47099"), BOOM::Vector("0.161589 0.170474 0.233919 0.200019 0.193735 0.220349 0.210566 0.196697 0.298003 0.230645"), BOOM::Vector("0.0999033 0.109203 0.11753 0.104285 0.112205 0.0805466 0.0967948 0.107108 0.0773693 0.0950548")); table->add(15, spec); } //---------------------------------------------------------------------- // nu = 16 kl = 4.40761e-07 { NormalMixtureApproximation spec( BOOM::Vector("-2.78261 -2.49315 -2.69906 -3.03961 -2.49316 -2.79538 -2.63364 -2.72594 -2.92355 -2.7082"), BOOM::Vector("0.187353 0.217334 0.200883 0.16552 0.290165 0.155372 0.199695 0.201618 0.150474 0.195079"), BOOM::Vector("0.0955543 0.119762 0.0962062 0.115448 0.0557457 0.0966131 0.101652 0.0996282 0.108908 0.110482")); table->add(16, spec); } //---------------------------------------------------------------------- // nu = 17 kl = 2.85303e-07 { NormalMixtureApproximation spec( BOOM::Vector("-2.86147 -2.54106 -2.98934 -2.56169 -2.69321 -2.86739 -2.77851 -2.76546 -2.74476 -3.10841"), BOOM::Vector("0.157162 0.209479 0.149403 0.281295 0.193017 0.175629 0.192595 0.200924 0.197301 0.159568"), BOOM::Vector("0.0977126 0.0974159 0.111694 0.0511133 0.0967194 0.117931 0.113648 0.105572 0.115429 0.0927649")); table->add(17, spec); } //---------------------------------------------------------------------- // nu = 18 kl = 2.88659e-07 { NormalMixtureApproximation spec( BOOM::Vector("-2.70424 -2.67037 -2.83261 -2.89881 -3.14233 -2.80686 -2.81421 -2.92335 -2.63058 -3.02756"), BOOM::Vector("0.215005 0.215035 0.189501 0.176083 0.158559 0.183899 0.190533 0.157471 0.272262 0.148654"), BOOM::Vector("0.0918774 0.105924 0.0945922 0.1111 0.111545 0.11282 0.0979044 0.111961 0.0510972 0.111179")); table->add(18, spec); } //---------------------------------------------------------------------- // nu = 19 kl = 1.04033e-06 { NormalMixtureApproximation spec( BOOM::Vector("-3.04786 -2.79218 -2.95496 -2.72309 -2.94398 -2.83479 -3.18163 -2.81501 -2.89527 -2.95439"), BOOM::Vector("0.150927 0.209676 0.179842 0.259399 0.177905 0.211588 0.156208 0.21029 0.194266 0.179479"), BOOM::Vector("0.101883 0.127502 0.0992203 0.087471 0.0921502 0.0918428 0.105798 0.0906732 0.0782149 0.125244")); table->add(19, spec); } //---------------------------------------------------------------------- // nu = 20 kl = 1.95135e-05 { NormalMixtureApproximation spec( BOOM::Vector("-2.96542 -2.94527 -2.8337 -3.13593"), BOOM::Vector("0.196234 0.187911 0.240907 0.168479"), BOOM::Vector("0.264079 0.251065 0.23993 0.244925")); table->add(20, spec); } //---------------------------------------------------------------------- // nu = 21 kl = 1.25501e-06 { NormalMixtureApproximation spec( BOOM::Vector("-3.21395 -2.9257 -2.79684 -3.05254"), BOOM::Vector("0.160645 0.199949 0.239806 0.166301"), BOOM::Vector("0.208282 0.390199 0.0631345 0.338385")); table->add(21, spec); } //---------------------------------------------------------------------- // nu = 22 kl = 9.95333e-07 { NormalMixtureApproximation spec( BOOM::Vector("-2.86939 -3.12875 -2.97884 -3.28986"), BOOM::Vector("0.23555 0.171039 0.195224 0.152216"), BOOM::Vector("0.0750799 0.444956 0.380877 0.0990878")); table->add(22, spec); } //---------------------------------------------------------------------- // nu = 23 kl = 1.07408e-06 { NormalMixtureApproximation spec( BOOM::Vector("-3.14447 -3.03371 -3.29641 -2.90364"), BOOM::Vector("0.157386 0.192051 0.154507 0.227346"), BOOM::Vector("0.297551 0.42609 0.211001 0.0653575")); table->add(23, spec); } //---------------------------------------------------------------------- // nu = 24 kl = 7.97378e-07 { NormalMixtureApproximation spec( BOOM::Vector("-3.3425 -3.19125 -2.93168 -3.05843"), BOOM::Vector("0.151682 0.162609 0.221468 0.188103"), BOOM::Vector("0.172572 0.420153 0.0487638 0.358511")); table->add(24, spec); } //---------------------------------------------------------------------- // nu = 25 kl = 7.77405e-07 { NormalMixtureApproximation spec( BOOM::Vector("-3.01992 -3.39868 -3.24511 -3.08839"), BOOM::Vector("0.219514 0.145746 0.163358 0.17772"), BOOM::Vector("0.0799961 0.109955 0.521404 0.288645")); table->add(25, spec); } //---------------------------------------------------------------------- // nu = 26 kl = 7.05901e-07 { NormalMixtureApproximation spec( BOOM::Vector("-3.06494 -3.13075 -3.2832 -3.43299"), BOOM::Vector("0.214884 0.174372 0.160391 0.143716"), BOOM::Vector("0.0802951 0.28768 0.519044 0.11298")); table->add(26, spec); } //---------------------------------------------------------------------- // nu = 27 kl = 6.71093e-07 { NormalMixtureApproximation spec( BOOM::Vector("-3.11417 -3.325 -3.19994 -3.46592"), BOOM::Vector("0.210819 0.15283 0.175212 0.141729"), BOOM::Vector("0.0870154 0.399954 0.382538 0.130493")); table->add(27, spec); } //---------------------------------------------------------------------- // nu = 28 kl = 5.55738e-07 { NormalMixtureApproximation spec( BOOM::Vector("-3.48618 -3.3487 -3.23148 -3.12311"), BOOM::Vector("0.141835 0.150604 0.174175 0.204322"), BOOM::Vector("0.167048 0.396213 0.379249 0.0574893")); table->add(28, spec); } //---------------------------------------------------------------------- // nu = 29 kl = 6.26874e-07 { NormalMixtureApproximation spec( BOOM::Vector("-3.22416 -3.17597 -3.5103 -3.36949"), BOOM::Vector("0.161478 0.201 0.141115 0.150377"), BOOM::Vector("0.228483 0.0707529 0.194295 0.506469")); table->add(29, spec); } //---------------------------------------------------------------------- // nu = 30 kl = 9.31351e-07 { NormalMixtureApproximation spec( BOOM::Vector("-3.53716 -3.296 -3.40811 -3.25089"), BOOM::Vector("0.138433 0.157926 0.137968 0.198364"), BOOM::Vector("0.239853 0.311762 0.323243 0.125142")); table->add(30, spec); } //---------------------------------------------------------------------- // nu = 31 kl = 5.40522e-07 { NormalMixtureApproximation spec( BOOM::Vector("-3.30406 -3.43753 -3.57137 -3.25426"), BOOM::Vector("0.157096 0.14466 0.137224 0.193906"), BOOM::Vector("0.247653 0.477233 0.200927 0.074188")); table->add(31, spec); } //---------------------------------------------------------------------- // nu = 32 kl = 1.83494e-06 { NormalMixtureApproximation spec( BOOM::Vector("-3.47206 -3.59097 -3.3608 -3.34302"), BOOM::Vector("0.127225 0.134355 0.143781 0.190057"), BOOM::Vector("0.262988 0.275631 0.266175 0.195207")); table->add(32, spec); } //---------------------------------------------------------------------- // nu = 33 kl = 1.74988e-06 { NormalMixtureApproximation spec( BOOM::Vector("-3.63039 -3.39652 -3.51067 -3.37979"), BOOM::Vector("0.130819 0.142221 0.126932 0.187349"), BOOM::Vector("0.233177 0.269683 0.294478 0.202661")); table->add(33, spec); } //---------------------------------------------------------------------- // nu = 34 kl = 1.91619e-06 { NormalMixtureApproximation spec( BOOM::Vector("-3.66024 -3.54621 -3.44422 -3.41632"), BOOM::Vector("0.128445 0.122684 0.142192 0.184388"), BOOM::Vector("0.227178 0.238719 0.316899 0.217204")); table->add(34, spec); } //---------------------------------------------------------------------- // nu = 35 kl = 2.4272e-06 { NormalMixtureApproximation spec( BOOM::Vector("-3.45333 -3.47375 -3.57858 -3.69033"), BOOM::Vector("0.181102 0.137254 0.119576 0.125799"), BOOM::Vector("0.246407 0.296997 0.238148 0.218447")); table->add(35, spec); } //---------------------------------------------------------------------- // nu = 36 kl = 9.03495e-07 { NormalMixtureApproximation spec( BOOM::Vector("-3.46691 -3.72351 -3.6068 -3.49929"), BOOM::Vector("0.1796 0.125171 0.126406 0.142434"), BOOM::Vector("0.17033 0.179811 0.329946 0.319914")); table->add(36, spec); } //---------------------------------------------------------------------- // nu = 37 kl = 1.00391e-06 { NormalMixtureApproximation spec( BOOM::Vector("-3.61444 -3.51887 -3.49594 -3.7235"), BOOM::Vector("0.120991 0.137913 0.176566 0.127275"), BOOM::Vector("0.252224 0.289143 0.173494 0.285139")); table->add(37, spec); } //---------------------------------------------------------------------- // nu = 38 kl = 6.04446e-07 { NormalMixtureApproximation spec( BOOM::Vector("-3.51812 -3.5603 -3.65507 -3.76597"), BOOM::Vector("0.174583 0.14181 0.123721 0.123863"), BOOM::Vector("0.146419 0.350147 0.300214 0.203221")); table->add(38, spec); } //---------------------------------------------------------------------- // nu = 39 kl = 4.68814e-07 { NormalMixtureApproximation spec( BOOM::Vector("-3.54317 -3.58864 -3.68474 -3.79577"), BOOM::Vector("0.172549 0.141695 0.124397 0.122032"), BOOM::Vector("0.134179 0.360045 0.329741 0.176035")); table->add(39, spec); } //---------------------------------------------------------------------- // nu = 40 kl = 1.98959e-06 { NormalMixtureApproximation spec( BOOM::Vector("-3.68816 -3.79375 -3.60942 -3.58782"), BOOM::Vector("0.121886 0.124039 0.135526 0.168426"), BOOM::Vector("0.257529 0.277002 0.260389 0.20508")); table->add(40, spec); } //---------------------------------------------------------------------- // nu = 41 kl = 3.80594e-07 { NormalMixtureApproximation spec( BOOM::Vector("-3.59369 -3.62076 -3.72969 -3.84174"), BOOM::Vector("0.167718 0.135457 0.1248 0.119954"), BOOM::Vector("0.127238 0.276005 0.427154 0.169603")); table->add(41, spec); } //---------------------------------------------------------------------- // nu = 42 kl = 3.82951e-07 { NormalMixtureApproximation spec( BOOM::Vector("-3.62167 -3.75431 -3.65586 -3.86188"), BOOM::Vector("0.165586 0.121414 0.135013 0.11882"), BOOM::Vector("0.132126 0.368265 0.314571 0.185038")); table->add(42, spec); } //---------------------------------------------------------------------- // nu = 43 kl = 3.97626e-07 { NormalMixtureApproximation spec( BOOM::Vector("-3.65898 -3.86544 -3.75917 -3.64107"), BOOM::Vector("0.129864 0.120191 0.11909 0.162826"), BOOM::Vector("0.240719 0.272621 0.363895 0.122765")); table->add(43, spec); } //---------------------------------------------------------------------- // nu = 44 kl = 2.80783e-07 { NormalMixtureApproximation spec( BOOM::Vector("-3.78941 -3.89013 -3.72035 -3.65658"), BOOM::Vector("0.11587 0.118651 0.137201 0.160976"), BOOM::Vector("0.238061 0.248387 0.416636 0.0969155")); table->add(44, spec); } //---------------------------------------------------------------------- // nu = 45 kl = 2.55462e-07 { NormalMixtureApproximation spec( BOOM::Vector("-3.81316 -3.74376 -3.68008 -3.91278"), BOOM::Vector("0.115294 0.135939 0.159032 0.117355"), BOOM::Vector("0.24792 0.417027 0.0949106 0.240143")); table->add(45, spec); } //---------------------------------------------------------------------- // nu = 46 kl = 2.66128e-07 { NormalMixtureApproximation spec( BOOM::Vector("-3.73393 -3.93083 -3.7034 -3.82829"), BOOM::Vector("0.128576 0.116838 0.156829 0.117263"), BOOM::Vector("0.26287 0.257823 0.0976207 0.381685")); table->add(46, spec); } //---------------------------------------------------------------------- // nu = 47 kl = 1.47922e-06 { NormalMixtureApproximation spec( BOOM::Vector("-3.84796 -3.94334 -3.77286 -3.76275"), BOOM::Vector("0.113791 0.116108 0.124328 0.155116"), BOOM::Vector("0.261941 0.288034 0.236086 0.213939")); table->add(47, spec); } //---------------------------------------------------------------------- // nu = 48 kl = 3.12752e-07 { NormalMixtureApproximation spec( BOOM::Vector("-3.76952 -3.98498 -3.88842 -3.80743"), BOOM::Vector("0.154289 0.112206 0.112186 0.127838"), BOOM::Vector("0.143959 0.195912 0.296249 0.363879")); table->add(48, spec); } //---------------------------------------------------------------------- // nu = 49 kl = 1.59178e-06 { NormalMixtureApproximation spec( BOOM::Vector("-3.80908 -3.81053 -3.98866 -3.89524"), BOOM::Vector("0.150898 0.118717 0.11317 0.1122"), BOOM::Vector("0.238816 0.199434 0.254894 0.306856")); table->add(49, spec); } }
void user_settings_io::import_settings(const std::string& file_path) { YAML::Node node; try { node = YAML::LoadFile(file_path); settings_file_name_ = file_path; } catch(YAML::Exception& e) { const std::string& error = "Failed to load user settings file from \"" + file_path + "\".\n\tError: " + e.what(); LOG(logger::critical, error); throw std::runtime_error(error); } /// Check input file structure validity check_input_validity(node); settings_.set_fs(node[usc::fs].as<double>()); settings_.set_excitation_time(node[usc::excitation_time].as<std::size_t>()); settings_.set_excitation_time_step(node[usc::excitation_time_step].as<double>()); YAML::Node spec_node = node[usc::rtss::self]; relaxation_time_step_spec spec(spec_node[usc::rtss::initial_step].as<double>(), spec_node[usc::rtss::time_delta].as<std::size_t>(), spec_node[usc::rtss::coefficient].as<double>()); settings_.set_relaxation_time_step_spec(spec); settings_.set_simulations_count(node[usc::simulations_count].as<std::size_t>()); if(node[usc::force_application_nodes]) { const YAML::Node& force_node = node[usc::force_application_nodes]; std::vector<std::size_t> nodes; for(std::size_t i = 0; i < force_node.size(); ++i) { std::size_t node = force_node[i].as<std::size_t>(); nodes.push_back(node); } settings_.set_force_application_nodes(nodes); } settings_.set_forces_dynamic(node[usc::forces_dynamic].as<bool>()); if(node[usc::visualization_nodes]) { const YAML::Node& visualization_node = node[usc::visualization_nodes]; std::vector<std::size_t> nodes; for(std::size_t i = 0; i < visualization_node.size(); ++i) { std::size_t node = visualization_node[i].as<std::size_t>(); nodes.push_back(node); } settings_.set_visualization_nodes(nodes); } if(node[usc::nodes]) { settings_.set_network(read_network_from_yaml(node)); } else { std::string absolute_path = node[usc::network_file_path].as<std::string>(); if(!absolute_path.empty()) { if(absolute_path[0] != '/') { //This is relative path, need to attach current YAML file's directory to path absolute_path.insert(0, file_path.substr(0, file_path.find_last_of("/") + 1)); } network_file_name_ = absolute_path; import_network_from_external_file(absolute_path); } } if(node[usc::l0]) { double cutoff = node[usc::l0].as<double>(); settings_.set_cutoff_distance(cutoff); network net = settings_.get_network(); net.set_cutoff_distance(cutoff); settings_.set_network(net); } std::cout << settings_ << std::endl; }
MSSpectrum<FeatureFinderAlgorithmIsotopeWavelet::PeakType>* FeatureFinderAlgorithmIsotopeWavelet::createHRData(const UInt i) { MSSpectrum<PeakType> spec((*this->map_)[i]); const MSSpectrum<PeakType>& specr((*this->map_)[i]); for (UInt j = 0; j < spec.size() - 1; ++j) { spec[j].setMZ(-1 * (specr[j + 1].getMZ() - specr[j].getMZ())); spec[j].setIntensity((specr[j].getIntensity() + specr[j + 1].getIntensity())); } spec[spec.size() - 1].setMZ(-1); spec[spec.size() - 1].setIntensity(-1); ConstRefVector<MSSpectrum<PeakType> > c_sorted_spec(spec.begin(), spec.end()); //Sort in ascending order according to the intensities present in the transform c_sorted_spec.sortByPosition(); #ifdef OPENMS_DEBUG_ISOTOPE_WAVELET std::ofstream ofilex("spacings.trans"); for (UInt j = 0; j < spec.size() - 1; ++j) { ofilex << ::std::setprecision(12) << std::fixed << spec[j].getMZ() << "\t" << spec[j].getIntensity() << std::endl; } ofilex.close(); #endif UInt pos = 0; while (c_sorted_spec[pos].getIntensity() <= 0) { if (++pos >= c_sorted_spec.size()) { std::cout << "Detected empty scan or a scan that cannot be interpolated with zeros in HR mode. " << std::endl; std::cout << "Please check scan # " << i << " of your data set." << std::endl; exit(-1); } } double bound = -1 * c_sorted_spec[pos].getMZ(); if (bound > (1. / max_charge_) / 2.) { //that might be case for simulated spectra, //which might show a very artificial spacing bound = (1. / max_charge_) / 2. / 4.; } MSSpectrum<PeakType>* new_spec = new MSSpectrum<PeakType>; new_spec->reserve(200000); new_spec->setRT(((*this->map_)[i]).getRT()); PeakType p; p.setMZ(specr[0].getMZ()); p.setIntensity(specr[0].getIntensity()); new_spec->push_back(p); UInt count; for (UInt j = 0; j < spec.size() - 1; ++j) { count = 0; while (-spec[j].getMZ() - count * bound > bound) { ++count; p.setMZ(specr[j].getMZ() + count * bound); p.setIntensity(0); new_spec->push_back(p); } p.setMZ(specr[j + 1].getMZ()); p.setIntensity(specr[j + 1].getIntensity()); new_spec->push_back(p); } #ifdef OPENMS_DEBUG_ISOTOPE_WAVELET std::ofstream ofiley("new_spec.trans"); for (UInt j = 0; j < new_spec->size(); ++j) { ofiley << ::std::setprecision(12) << std::fixed << (*new_spec)[j].getMZ() << "\t" << (*new_spec)[j].getIntensity() << std::endl; } ofiley.close(); #endif return new_spec; }
// static nsresult nsChannelClassifier::SetBlockedTrackingContent(nsIChannel *channel) { // Can be called in EITHER the parent or child process. nsCOMPtr<nsIParentChannel> parentChannel; NS_QueryNotificationCallbacks(channel, parentChannel); if (parentChannel) { // This channel is a parent-process proxy for a child process request. The // actual channel will be notified via the status passed to // nsIRequest::Cancel and do this for us. return NS_OK; } nsresult rv; nsCOMPtr<mozIDOMWindowProxy> win; nsCOMPtr<mozIThirdPartyUtil> thirdPartyUtil = do_GetService(THIRDPARTYUTIL_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, NS_OK); rv = thirdPartyUtil->GetTopWindowForChannel(channel, getter_AddRefs(win)); NS_ENSURE_SUCCESS(rv, NS_OK); auto* pwin = nsPIDOMWindowOuter::From(win); nsCOMPtr<nsIDocShell> docShell = pwin->GetDocShell(); if (!docShell) { return NS_OK; } nsCOMPtr<nsIDocument> doc = docShell->GetDocument(); NS_ENSURE_TRUE(doc, NS_OK); // This event might come after the user has navigated to another page. // To prevent showing the TrackingProtection UI on the wrong page, we need to // check that the loading URI for the channel is the same as the URI currently // loaded in the document. if (!SameLoadingURI(doc, channel)) { return NS_OK; } // Notify nsIWebProgressListeners of this security event. // Can be used to change the UI state. nsCOMPtr<nsISecurityEventSink> eventSink = do_QueryInterface(docShell, &rv); NS_ENSURE_SUCCESS(rv, NS_OK); uint32_t state = 0; nsCOMPtr<nsISecureBrowserUI> securityUI; docShell->GetSecurityUI(getter_AddRefs(securityUI)); if (!securityUI) { return NS_OK; } doc->SetHasTrackingContentBlocked(true); securityUI->GetState(&state); state |= nsIWebProgressListener::STATE_BLOCKED_TRACKING_CONTENT; eventSink->OnSecurityChange(nullptr, state); // Log a warning to the web console. nsCOMPtr<nsIURI> uri; channel->GetURI(getter_AddRefs(uri)); NS_ConvertUTF8toUTF16 spec(uri->GetSpecOrDefault()); const char16_t* params[] = { spec.get() }; nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Tracking Protection"), doc, nsContentUtils::eNECKO_PROPERTIES, "TrackingUriBlocked", params, ArrayLength(params)); return NS_OK; }
TEST( FTSSpec, Extra1 ) { BSONObj user = BSON( "key" << BSON( "data" << "text" ) ); FTSSpec spec( FTSSpec::fixSpec( user ) ); ASSERT_EQUALS( 0U, spec.numExtraBefore() ); ASSERT_EQUALS( 0U, spec.numExtraAfter() ); }
LEVEL_RESULT playsingle_controller::play_scenario(const config& level) { LOG_NG << "in playsingle_controller::play_scenario()...\n"; // Start music. for(const config &m : level.child_range("music")) { sound::play_music_config(m); } sound::commit_music_changes(); if(!this->is_skipping_replay()) { show_story(gui_->video(), get_scenario_name(), level.child_range("story")); } gui_->labels().read(level); // Read sound sources assert(soundsources_manager_ != nullptr); for (const config &s : level.child_range("sound_source")) { try { soundsource::sourcespec spec(s); soundsources_manager_->add(spec); } catch (bad_lexical_cast &) { ERR_NG << "Error when parsing sound_source config: bad lexical cast." << std::endl; ERR_NG << "sound_source config was: " << s.debug() << std::endl; ERR_NG << "Skipping this sound source..." << std::endl; } } LOG_NG << "entering try... " << (SDL_GetTicks() - ticks()) << "\n"; try { play_scenario_init(); // clears level config; this->saved_game_.remove_snapshot(); if (!is_regular_game_end() && !linger_) { play_scenario_main_loop(); } if (game_config::exit_at_end) { exit(0); } const bool is_victory = get_end_level_data_const().is_victory; if(gamestate().gamedata_.phase() <= game_data::PRESTART) { sdl::draw_solid_tinted_rectangle( 0, 0, gui_->video().getx(), gui_->video().gety(), 0, 0, 0, 1.0, gui_->video().getSurface() ); update_rect(0, 0, gui_->video().getx(), gui_->video().gety()); } ai_testing::log_game_end(); const end_level_data& end_level = get_end_level_data_const(); if (!end_level.transient.custom_endlevel_music.empty()) { if (!is_victory) { set_defeat_music_list(end_level.transient.custom_endlevel_music); } else { set_victory_music_list(end_level.transient.custom_endlevel_music); } } if (gamestate().board_.teams().empty()) { //store persistent teams saved_game_.set_snapshot(config()); return LEVEL_RESULT::VICTORY; // this is probably only a story scenario, i.e. has its endlevel in the prestart event } if(linger_) { LOG_NG << "resuming from loaded linger state...\n"; //as carryover information is stored in the snapshot, we have to re-store it after loading a linger state saved_game_.set_snapshot(config()); if(!is_observer()) { persist_.end_transaction(); } return LEVEL_RESULT::VICTORY; } pump().fire(is_victory ? "local_victory" : "local_defeat"); { // Block for set_scontext_synced_base set_scontext_synced_base sync; pump().fire(end_level.proceed_to_next_level ? "victory" : "defeat"); pump().fire("scenario end"); } if(end_level.proceed_to_next_level) { gamestate().board_.heal_all_survivors(); } if(is_observer()) { gui2::show_transient_message(gui_->video(), _("Game Over"), _("The game is over.")); return LEVEL_RESULT::OBSERVER_END; } // If we're a player, and the result is victory/defeat, then send // a message to notify the server of the reason for the game ending. send_to_wesnothd(config_of ("info", config_of ("type", "termination") ("condition", "game over") ("result", is_victory ? "victory" : "defeat") )); // Play victory music once all victory events // are finished, if we aren't observers. // // Some scenario authors may use 'continue' // result for something that is not story-wise // a victory, so let them use [music] tags // instead should they want special music. const std::string& end_music = is_victory ? select_victory_music() : select_defeat_music(); if(end_music.empty() != true) { sound::play_music_once(end_music); } persist_.end_transaction(); return is_victory ? LEVEL_RESULT::VICTORY : LEVEL_RESULT::DEFEAT; } catch(const game::load_game_exception &) { // Loading a new game is effectively a quit. // if ( game::load_game_exception::game != "" ) { saved_game_ = saved_game(); } throw; } catch(wesnothd_error& e) { scoped_savegame_snapshot snapshot(*this); savegame::ingame_savegame save(saved_game_, *gui_, preferences::save_compression_format()); save.save_game_interactive(gui_->video(), _("A network disconnection has occurred, and the game cannot continue. Do you want to save the game?"), gui::YES_NO); if(dynamic_cast<ingame_wesnothd_error*>(&e)) { return LEVEL_RESULT::QUIT; } else { throw; } } return LEVEL_RESULT::QUIT; }
int main(int argc, char *argv[]) { int retval = 0; /* Initialization */ log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION); log_add_output_all_levs(&main_dstream_no_stderr_log_out); log_register_thread("main"); // This enables internatonal characters input if( setlocale(LC_ALL, "") == NULL ) { fprintf( stderr, "%s: warning: could not set default locale\n", argv[0] ); } // Set locale. This is for forcing '.' as the decimal point. try { std::locale::global(std::locale(std::locale(""), "C", std::locale::numeric)); setlocale(LC_NUMERIC, "C"); } catch (const std::exception& ex) { errorstream<<"Could not set numeric locale to C"<<std::endl; } /* Parse command line */ // List all allowed options core::map<std::string, ValueSpec> allowed_options; allowed_options.insert("help", ValueSpec(VALUETYPE_FLAG, _("Show allowed options"))); allowed_options.insert("config", ValueSpec(VALUETYPE_STRING, _("Load configuration from specified file"))); allowed_options.insert("port", ValueSpec(VALUETYPE_STRING, _("Set network port (UDP)"))); allowed_options.insert("disable-unittests", ValueSpec(VALUETYPE_FLAG, _("Disable unit tests"))); allowed_options.insert("enable-unittests", ValueSpec(VALUETYPE_FLAG, _("Enable unit tests"))); allowed_options.insert("map-dir", ValueSpec(VALUETYPE_STRING, _("Same as --world (deprecated)"))); allowed_options.insert("world", ValueSpec(VALUETYPE_STRING, _("Set world path (implies local game) ('list' lists all)"))); allowed_options.insert("worldname", ValueSpec(VALUETYPE_STRING, _("Set world by name (implies local game)"))); allowed_options.insert("info", ValueSpec(VALUETYPE_FLAG, _("Print more information to console"))); allowed_options.insert("verbose", ValueSpec(VALUETYPE_FLAG, _("Print even more information to console"))); allowed_options.insert("trace", ValueSpec(VALUETYPE_FLAG, _("Print enormous amounts of information to log and console"))); allowed_options.insert("logfile", ValueSpec(VALUETYPE_STRING, _("Set logfile path ('' = no logging)"))); allowed_options.insert("gameid", ValueSpec(VALUETYPE_STRING, _("Set gameid (\"--gameid list\" prints available ones)"))); #ifndef SERVER allowed_options.insert("speedtests", ValueSpec(VALUETYPE_FLAG, _("Run speed tests"))); allowed_options.insert("address", ValueSpec(VALUETYPE_STRING, _("Address to connect to. ('' = local game)"))); allowed_options.insert("random-input", ValueSpec(VALUETYPE_FLAG, _("Enable random user input, for testing"))); allowed_options.insert("server", ValueSpec(VALUETYPE_FLAG, _("Run dedicated server"))); allowed_options.insert("name", ValueSpec(VALUETYPE_STRING, _("Set player name"))); allowed_options.insert("password", ValueSpec(VALUETYPE_STRING, _("Set password"))); allowed_options.insert("go", ValueSpec(VALUETYPE_FLAG, _("Disable main menu"))); #endif Settings cmd_args; bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options); if(ret == false || cmd_args.getFlag("help") || cmd_args.exists("nonopt1")) { dstream<<_("Allowed options:")<<std::endl; for(core::map<std::string, ValueSpec>::Iterator i = allowed_options.getIterator(); i.atEnd() == false; i++) { std::ostringstream os1(std::ios::binary); os1<<" --"<<i.getNode()->getKey(); if(i.getNode()->getValue().type == VALUETYPE_FLAG) {} else os1<<_(" <value>"); dstream<<padStringRight(os1.str(), 24); if(i.getNode()->getValue().help != NULL) dstream<<i.getNode()->getValue().help; dstream<<std::endl; } return cmd_args.getFlag("help") ? 0 : 1; } /* Low-level initialization */ // If trace is enabled, enable logging of certain things if(cmd_args.getFlag("trace")){ dstream<<_("Enabling trace level debug output")<<std::endl; log_trace_level_enabled = true; dout_con_ptr = &verbosestream; // this is somewhat old crap socket_enable_debug_output = true; // socket doesn't use log.h } // In certain cases, output info level on stderr if(cmd_args.getFlag("info") || cmd_args.getFlag("verbose") || cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests")) log_add_output(&main_stderr_log_out, LMT_INFO); // In certain cases, output verbose level on stderr if(cmd_args.getFlag("verbose") || cmd_args.getFlag("trace")) log_add_output(&main_stderr_log_out, LMT_VERBOSE); porting::signal_handler_init(); bool &kill = *porting::signal_handler_killstatus(); porting::initializePaths(); // Create user data directory fs::CreateDir(porting::path_user); init_gettext((porting::path_share + DIR_DELIM + "locale").c_str()); infostream<<"path_share = "<<porting::path_share<<std::endl; infostream<<"path_user = "******"gameid") && cmd_args.get("gameid") == "list") { std::set<std::string> gameids = getAvailableGameIds(); for(std::set<std::string>::const_iterator i = gameids.begin(); i != gameids.end(); i++) dstream<<(*i)<<std::endl; return 0; } // List worlds if requested if(cmd_args.exists("world") && cmd_args.get("world") == "list"){ dstream<<_("Available worlds:")<<std::endl; std::vector<WorldSpec> worldspecs = getAvailableWorlds(); print_worldspecs(worldspecs, dstream); return 0; } // Print startup message infostream<<PROJECT_NAME<< " "<<_("with")<<" SER_FMT_VER_HIGHEST="<<(int)SER_FMT_VER_HIGHEST <<", "<<BUILD_INFO <<std::endl; /* Basic initialization */ // Initialize default settings set_default_settings(g_settings); // Initialize sockets sockets_init(); atexit(sockets_cleanup); /* Read config file */ // Path of configuration file in use std::string configpath = ""; if(cmd_args.exists("config")) { bool r = g_settings->readConfigFile(cmd_args.get("config").c_str()); if(r == false) { errorstream<<"Could not read configuration from \"" <<cmd_args.get("config")<<"\""<<std::endl; return 1; } configpath = cmd_args.get("config"); } else { core::array<std::string> filenames; filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf"); // Legacy configuration file location filenames.push_back(porting::path_user + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf"); #if RUN_IN_PLACE // Try also from a lower level (to aid having the same configuration // for many RUN_IN_PLACE installs) filenames.push_back(porting::path_user + DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf"); #endif for(u32 i=0; i<filenames.size(); i++) { bool r = g_settings->readConfigFile(filenames[i].c_str()); if(r) { configpath = filenames[i]; break; } } // If no path found, use the first one (menu creates the file) if(configpath == "") configpath = filenames[0]; } // Initialize debug streams #define DEBUGFILE "debug.txt" #if RUN_IN_PLACE std::string logfile = DEBUGFILE; #else std::string logfile = porting::path_user+DIR_DELIM+DEBUGFILE; #endif if(cmd_args.exists("logfile")) logfile = cmd_args.get("logfile"); log_remove_output(&main_dstream_no_stderr_log_out); int loglevel = g_settings->getS32("debug_log_level"); if (loglevel == 0) //no logging logfile = ""; else if (loglevel > 0 && loglevel <= LMT_NUM_VALUES) log_add_output_maxlev(&main_dstream_no_stderr_log_out, (LogMessageLevel)(loglevel - 1)); if(logfile != "") debugstreams_init(false, logfile.c_str()); else debugstreams_init(false, NULL); infostream<<"logfile = "<<logfile<<std::endl; // Initialize random seed srand(time(0)); mysrand(time(0)); /* Run unit tests */ if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false) || cmd_args.getFlag("enable-unittests") == true) { run_tests(); } /* Game parameters */ // Port u16 port = 30000; if(cmd_args.exists("port")) port = cmd_args.getU16("port"); else if(g_settings->exists("port")) port = g_settings->getU16("port"); if(port == 0) port = 30000; // World directory std::string commanded_world = ""; if(cmd_args.exists("world")) commanded_world = cmd_args.get("world"); else if(cmd_args.exists("map-dir")) commanded_world = cmd_args.get("map-dir"); else if(cmd_args.exists("nonopt0")) // First nameless argument commanded_world = cmd_args.get("nonopt0"); else if(g_settings->exists("map-dir")) commanded_world = g_settings->get("map-dir"); // World name std::string commanded_worldname = ""; if(cmd_args.exists("worldname")) commanded_worldname = cmd_args.get("worldname"); // Strip world.mt from commanded_world { std::string worldmt = "world.mt"; if(commanded_world.size() > worldmt.size() && commanded_world.substr(commanded_world.size()-worldmt.size()) == worldmt){ dstream<<_("Supplied world.mt file - stripping it off.")<<std::endl; commanded_world = commanded_world.substr( 0, commanded_world.size()-worldmt.size()); } } // If a world name was specified, convert it to a path if(commanded_worldname != ""){ // Get information about available worlds std::vector<WorldSpec> worldspecs = getAvailableWorlds(); bool found = false; for(u32 i=0; i<worldspecs.size(); i++){ std::string name = worldspecs[i].name; if(name == commanded_worldname){ if(commanded_world != ""){ dstream<<_("--worldname takes precedence over previously " "selected world.")<<std::endl; } commanded_world = worldspecs[i].path; found = true; break; } } if(!found){ dstream<<_("World")<<" '"<<commanded_worldname<<_("' not " "available. Available worlds:")<<std::endl; print_worldspecs(worldspecs, dstream); return 1; } } // Gamespec SubgameSpec commanded_gamespec; if(cmd_args.exists("gameid")){ std::string gameid = cmd_args.get("gameid"); commanded_gamespec = findSubgame(gameid); if(!commanded_gamespec.isValid()){ errorstream<<"Game \""<<gameid<<"\" not found"<<std::endl; return 1; } } /* Run dedicated server if asked to or no other option */ #ifdef SERVER bool run_dedicated_server = true; #else bool run_dedicated_server = cmd_args.getFlag("server"); #endif g_settings->set("server_dedicated", run_dedicated_server ? "true" : "false"); if(run_dedicated_server) { DSTACK("Dedicated server branch"); // Create time getter if built with Irrlicht #ifndef SERVER g_timegetter = new SimpleTimeGetter(); #endif // World directory std::string world_path; verbosestream<<_("Determining world path")<<std::endl; bool is_legacy_world = false; // If a world was commanded, use it if(commanded_world != ""){ world_path = commanded_world; infostream<<"Using commanded world path ["<<world_path<<"]" <<std::endl; } // No world was specified; try to select it automatically else { // Get information about available worlds std::vector<WorldSpec> worldspecs = getAvailableWorlds(); // If a world name was specified, select it if(commanded_worldname != ""){ world_path = ""; for(u32 i=0; i<worldspecs.size(); i++){ std::string name = worldspecs[i].name; if(name == commanded_worldname){ world_path = worldspecs[i].path; break; } } if(world_path == ""){ dstream<<_("World")<<" '"<<commanded_worldname<<"' "<<_("not " "available. Available worlds:")<<std::endl; print_worldspecs(worldspecs, dstream); return 1; } } // If there is only a single world, use it if(worldspecs.size() == 1){ world_path = worldspecs[0].path; dstream<<_("Automatically selecting world at")<<" [" <<world_path<<"]"<<std::endl; // If there are multiple worlds, list them } else if(worldspecs.size() > 1){ dstream<<_("Multiple worlds are available.")<<std::endl; dstream<<_("Please select one using --worldname <name>" " or --world <path>")<<std::endl; print_worldspecs(worldspecs, dstream); return 1; // If there are no worlds, automatically create a new one } else { // This is the ultimate default world path world_path = porting::path_user + DIR_DELIM + "worlds" + DIR_DELIM + "world"; infostream<<"Creating default world at [" <<world_path<<"]"<<std::endl; } } if(world_path == ""){ errorstream<<"No world path specified or found."<<std::endl; return 1; } verbosestream<<_("Using world path")<<" ["<<world_path<<"]"<<std::endl; // We need a gamespec. SubgameSpec gamespec; verbosestream<<_("Determining gameid/gamespec")<<std::endl; // If world doesn't exist if(!getWorldExists(world_path)) { // Try to take gamespec from command line if(commanded_gamespec.isValid()){ gamespec = commanded_gamespec; infostream<<"Using commanded gameid ["<<gamespec.id<<"]"<<std::endl; } // Otherwise we will be using "minetest" else{ gamespec = findSubgame(g_settings->get("default_game")); infostream<<"Using default gameid ["<<gamespec.id<<"]"<<std::endl; } } // World exists else { std::string world_gameid = getWorldGameId(world_path, is_legacy_world); // If commanded to use a gameid, do so if(commanded_gamespec.isValid()){ gamespec = commanded_gamespec; if(commanded_gamespec.id != world_gameid){ errorstream<<"WARNING: Using commanded gameid [" <<gamespec.id<<"]"<<" instead of world gameid [" <<world_gameid<<"]"<<std::endl; } } else{ // If world contains an embedded game, use it; // Otherwise find world from local system. gamespec = findWorldSubgame(world_path); infostream<<"Using world gameid ["<<gamespec.id<<"]"<<std::endl; } } if(!gamespec.isValid()){ errorstream<<"Subgame ["<<gamespec.id<<"] could not be found." <<std::endl; return 1; } verbosestream<<_("Using gameid")<<" ["<<gamespec.id<<"]"<<std::endl; // Create server Server server(world_path, configpath, gamespec, false); server.start(port); // Run server dedicated_server_loop(server, kill); return 0; } #ifndef SERVER // Exclude from dedicated server build /* More parameters */ std::string address = g_settings->get("address"); if(commanded_world != "") address = ""; else if(cmd_args.exists("address")) address = cmd_args.get("address"); std::string playername = g_settings->get("name"); if(cmd_args.exists("name")) playername = cmd_args.get("name"); bool skip_main_menu = cmd_args.getFlag("go"); /* Device initialization */ // Resolution selection bool fullscreen = g_settings->getBool("fullscreen"); u16 screenW = g_settings->getU16("screenW"); u16 screenH = g_settings->getU16("screenH"); // bpp, fsaa, vsync bool vsync = g_settings->getBool("vsync"); u16 bits = g_settings->getU16("fullscreen_bpp"); u16 fsaa = g_settings->getU16("fsaa"); // Determine driver video::E_DRIVER_TYPE driverType; std::string driverstring = g_settings->get("video_driver"); if(driverstring == "null") driverType = video::EDT_NULL; else if(driverstring == "software") driverType = video::EDT_SOFTWARE; else if(driverstring == "burningsvideo") driverType = video::EDT_BURNINGSVIDEO; else if(driverstring == "direct3d8") driverType = video::EDT_DIRECT3D8; else if(driverstring == "direct3d9") driverType = video::EDT_DIRECT3D9; else if(driverstring == "opengl") driverType = video::EDT_OPENGL; else { errorstream<<"WARNING: Invalid video_driver specified; defaulting " "to opengl"<<std::endl; driverType = video::EDT_OPENGL; } /* Create device and exit if creation failed */ MyEventReceiver receiver; IrrlichtDevice *device; SIrrlichtCreationParameters params = SIrrlichtCreationParameters(); params.DriverType = driverType; params.WindowSize = core::dimension2d<u32>(screenW, screenH); params.Bits = bits; params.AntiAlias = fsaa; params.Fullscreen = fullscreen; params.Stencilbuffer = false; params.Vsync = vsync; params.EventReceiver = &receiver; device = createDeviceEx(params); if (device == 0) return 1; // could not create selected driver. /* Continue initialization */ video::IVideoDriver* driver = device->getVideoDriver(); /* This changes the minimum allowed number of vertices in a VBO. Default is 500. */ //driver->setMinHardwareBufferVertexCount(50); // Create time getter g_timegetter = new IrrlichtTimeGetter(device); // Create game callback for menus g_gamecallback = new MainGameCallback(device); /* Speed tests (done after irrlicht is loaded to get timer) */ if(cmd_args.getFlag("speedtests")) { dstream<<"Running speed tests"<<std::endl; SpeedTests(); return 0; } device->setResizable(true); bool random_input = g_settings->getBool("random_input") || cmd_args.getFlag("random-input"); InputHandler *input = NULL; if(random_input) input = new RandomInputHandler(); else input = new RealInputHandler(device, &receiver); scene::ISceneManager* smgr = device->getSceneManager(); guienv = device->getGUIEnvironment(); gui::IGUISkin* skin = guienv->getSkin(); #if USE_FREETYPE std::string font_path = g_settings->get("font_path"); u16 font_size = g_settings->getU16("font_size"); gui::IGUIFont *font = gui::CGUITTFont::createTTFont(guienv, font_path.c_str(), font_size); #else gui::IGUIFont* font = guienv->getFont(getTexturePath("fontlucida.png").c_str()); #endif if(font) skin->setFont(font); else errorstream<<"WARNING: Font file was not found." " Using default font."<<std::endl; // If font was not found, this will get us one font = skin->getFont(); assert(font); u32 text_height = font->getDimension(L"Hello, world!").Height; infostream<<"text_height="<<text_height<<std::endl; //skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0)); skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255)); //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0)); //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0)); skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0)); skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0)); skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255,70,100,50)); skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255,255,255,255)); #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2 // Irrlicht 1.8 input colours skin->setColor(gui::EGDC_EDITABLE, video::SColor(255,128,128,128)); skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255,96,134,49)); #endif /* GUI stuff */ ChatBackend chat_backend; /* If an error occurs, this is set to something and the menu-game loop is restarted. It is then displayed before the menu. */ std::wstring error_message = L""; // The password entered during the menu screen, std::string password; bool first_loop = true; /* Menu-game loop */ while(device->run() && kill == false) { // Set the window caption device->setWindowCaption((std::wstring(L"Minetest [")+wgettext("Main Menu")+L"]").c_str()); // This is used for catching disconnects try { /* Clear everything from the GUIEnvironment */ guienv->clear(); /* We need some kind of a root node to be able to add custom gui elements directly on the screen. Otherwise they won't be automatically drawn. */ guiroot = guienv->addStaticText(L"", core::rect<s32>(0, 0, 10000, 10000)); SubgameSpec gamespec; WorldSpec worldspec; bool simple_singleplayer_mode = false; // These are set up based on the menu and other things std::string current_playername = "inv£lid"; std::string current_password = ""; std::string current_address = "does-not-exist"; int current_port = 0; /* Out-of-game menu loop. Loop quits when menu returns proper parameters. */ while(kill == false) { // If skip_main_menu, only go through here once if(skip_main_menu && !first_loop){ kill = true; break; } first_loop = false; // Cursor can be non-visible when coming from the game device->getCursorControl()->setVisible(true); // Some stuff are left to scene manager when coming from the game // (map at least?) smgr->clear(); // Initialize menu data MainMenuData menudata; if(g_settings->exists("selected_mainmenu_tab")) menudata.selected_tab = g_settings->getS32("selected_mainmenu_tab"); menudata.address = narrow_to_wide(address); menudata.name = narrow_to_wide(playername); menudata.port = narrow_to_wide(itos(port)); if(cmd_args.exists("password")) menudata.password = narrow_to_wide(cmd_args.get("password")); menudata.fancy_trees = g_settings->getBool("new_style_leaves"); menudata.smooth_lighting = g_settings->getBool("smooth_lighting"); menudata.clouds_3d = g_settings->getBool("enable_3d_clouds"); menudata.opaque_water = g_settings->getBool("opaque_water"); menudata.mip_map = g_settings->getBool("mip_map"); menudata.anisotropic_filter = g_settings->getBool("anisotropic_filter"); menudata.bilinear_filter = g_settings->getBool("bilinear_filter"); menudata.trilinear_filter = g_settings->getBool("trilinear_filter"); menudata.enable_shaders = g_settings->getS32("enable_shaders"); menudata.preload_item_visuals = g_settings->getBool("preload_item_visuals"); menudata.enable_particles = g_settings->getBool("enable_particles"); driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, menudata.mip_map); menudata.creative_mode = g_settings->getBool("creative_mode"); menudata.enable_damage = g_settings->getBool("enable_damage"); menudata.enable_public = g_settings->getBool("server_announce"); // Default to selecting nothing menudata.selected_world = -1; // Get world listing for the menu std::vector<WorldSpec> worldspecs = getAvailableWorlds(); // If there is only one world, select it if(worldspecs.size() == 1){ menudata.selected_world = 0; } // Otherwise try to select according to selected_world_path else if(g_settings->exists("selected_world_path")){ std::string trypath = g_settings->get("selected_world_path"); for(u32 i=0; i<worldspecs.size(); i++){ if(worldspecs[i].path == trypath){ menudata.selected_world = i; break; } } } // If a world was commanded, append and select it if(commanded_world != ""){ std::string gameid = getWorldGameId(commanded_world, true); std::string name = _("[--world parameter]"); if(gameid == ""){ gameid = g_settings->get("default_game"); name += " [new]"; } WorldSpec spec(commanded_world, name, gameid); worldspecs.push_back(spec); menudata.selected_world = worldspecs.size()-1; } // Copy worldspecs to menu menudata.worlds = worldspecs; if(skip_main_menu == false) { video::IVideoDriver* driver = device->getVideoDriver(); infostream<<"Waiting for other menus"<<std::endl; while(device->run() && kill == false) { if(noMenuActive()) break; driver->beginScene(true, true, video::SColor(255,128,128,128)); drawMenuBackground(driver); guienv->drawAll(); driver->endScene(); // On some computers framerate doesn't seem to be // automatically limited sleep_ms(25); } infostream<<"Waited for other menus"<<std::endl; GUIMainMenu *menu = new GUIMainMenu(guienv, guiroot, -1, &g_menumgr, &menudata, g_gamecallback); menu->allowFocusRemoval(true); if(error_message != L"") { verbosestream<<"error_message = " <<wide_to_narrow(error_message)<<std::endl; GUIMessageMenu *menu2 = new GUIMessageMenu(guienv, guiroot, -1, &g_menumgr, error_message.c_str()); menu2->drop(); error_message = L""; } infostream<<"Created main menu"<<std::endl; while(device->run() && kill == false) { if(menu->getStatus() == true) break; //driver->beginScene(true, true, video::SColor(255,0,0,0)); driver->beginScene(true, true, video::SColor(255,128,128,128)); drawMenuBackground(driver); guienv->drawAll(); driver->endScene(); // On some computers framerate doesn't seem to be // automatically limited sleep_ms(25); } infostream<<"Dropping main menu"<<std::endl; menu->drop(); } playername = wide_to_narrow(menudata.name); password = translatePassword(playername, menudata.password); //infostream<<"Main: password hash: '"<<password<<"'"<<std::endl; address = wide_to_narrow(menudata.address); int newport = stoi(wide_to_narrow(menudata.port)); if(newport != 0) port = newport; simple_singleplayer_mode = menudata.simple_singleplayer_mode; // Save settings g_settings->setS32("selected_mainmenu_tab", menudata.selected_tab); g_settings->set("new_style_leaves", itos(menudata.fancy_trees)); g_settings->set("smooth_lighting", itos(menudata.smooth_lighting)); g_settings->set("enable_3d_clouds", itos(menudata.clouds_3d)); g_settings->set("opaque_water", itos(menudata.opaque_water)); g_settings->set("mip_map", itos(menudata.mip_map)); g_settings->set("anisotropic_filter", itos(menudata.anisotropic_filter)); g_settings->set("bilinear_filter", itos(menudata.bilinear_filter)); g_settings->set("trilinear_filter", itos(menudata.trilinear_filter)); g_settings->setS32("enable_shaders", menudata.enable_shaders); g_settings->set("preload_item_visuals", itos(menudata.preload_item_visuals)); g_settings->set("enable_particles", itos(menudata.enable_particles)); g_settings->set("creative_mode", itos(menudata.creative_mode)); g_settings->set("enable_damage", itos(menudata.enable_damage)); g_settings->set("server_announce", itos(menudata.enable_public)); g_settings->set("name", playername); g_settings->set("address", address); g_settings->set("port", itos(port)); if(menudata.selected_world != -1) g_settings->set("selected_world_path", worldspecs[menudata.selected_world].path); // Break out of menu-game loop to shut down cleanly if(device->run() == false || kill == true) break; current_playername = playername; current_password = password; current_address = address; current_port = port; // If using simple singleplayer mode, override if(simple_singleplayer_mode){ current_playername = "singleplayer"; current_password = ""; current_address = ""; current_port = 30011; } else if (address != "") { ServerListSpec server; server["name"] = menudata.servername; server["address"] = wide_to_narrow(menudata.address); server["port"] = wide_to_narrow(menudata.port); server["description"] = menudata.serverdescription; ServerList::insert(server); } // Set world path to selected one if(menudata.selected_world != -1){ worldspec = worldspecs[menudata.selected_world]; infostream<<"Selected world: "<<worldspec.name <<" ["<<worldspec.path<<"]"<<std::endl; } // Only refresh if so requested if(menudata.only_refresh){ infostream<<"Refreshing menu"<<std::endl; continue; } // Create new world if requested if(menudata.create_world_name != L"") { std::string path = porting::path_user + DIR_DELIM "worlds" + DIR_DELIM + wide_to_narrow(menudata.create_world_name); // Create world if it doesn't exist if(!initializeWorld(path, menudata.create_world_gameid)){ error_message = wgettext("Failed to initialize world"); errorstream<<wide_to_narrow(error_message)<<std::endl; continue; } g_settings->set("selected_world_path", path); continue; } // If local game if(current_address == "") { if(menudata.selected_world == -1){ error_message = wgettext("No world selected and no address " "provided. Nothing to do."); errorstream<<wide_to_narrow(error_message)<<std::endl; continue; } // Load gamespec for required game gamespec = findWorldSubgame(worldspec.path); if(!gamespec.isValid() && !commanded_gamespec.isValid()){ error_message = wgettext("Could not find or load game \"") + narrow_to_wide(worldspec.gameid) + L"\""; errorstream<<wide_to_narrow(error_message)<<std::endl; continue; } if(commanded_gamespec.isValid() && commanded_gamespec.id != worldspec.gameid){ errorstream<<"WARNING: Overriding gamespec from \"" <<worldspec.gameid<<"\" to \"" <<commanded_gamespec.id<<"\""<<std::endl; gamespec = commanded_gamespec; } if(!gamespec.isValid()){ error_message = wgettext("Invalid gamespec."); error_message += L" (world_gameid=" +narrow_to_wide(worldspec.gameid)+L")"; errorstream<<wide_to_narrow(error_message)<<std::endl; continue; } } // Continue to game break; } // Break out of menu-game loop to shut down cleanly if(device->run() == false || kill == true) break; /* Run game */ the_game( kill, random_input, input, device, font, worldspec.path, current_playername, current_password, current_address, current_port, error_message, configpath, chat_backend, gamespec, simple_singleplayer_mode ); } //try catch(con::PeerNotFoundException &e) { error_message = wgettext("Connection error (timed out?)"); errorstream<<wide_to_narrow(error_message)<<std::endl; } catch(ServerError &e) { error_message = narrow_to_wide(e.what()); errorstream<<wide_to_narrow(error_message)<<std::endl; } catch(ModError &e) { errorstream<<e.what()<<std::endl; error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details."); } #ifdef NDEBUG catch(std::exception &e) { std::string narrow_message = "Some exception: \""; narrow_message += e.what(); narrow_message += "\""; errorstream<<narrow_message<<std::endl; error_message = narrow_to_wide(narrow_message); } #endif // If no main menu, show error and exit if(skip_main_menu) { if(error_message != L""){ verbosestream<<"error_message = " <<wide_to_narrow(error_message)<<std::endl; retval = 1; } break; } } // Menu-game loop delete input; /* In the end, delete the Irrlicht device. */ device->drop(); #endif // !SERVER // Update configuration file if(configpath != "") g_settings->updateConfigFile(configpath.c_str()); // Print modified quicktune values { bool header_printed = false; std::vector<std::string> names = getQuicktuneNames(); for(u32 i=0; i<names.size(); i++){ QuicktuneValue val = getQuicktuneValue(names[i]); if(!val.modified) continue; if(!header_printed){ dstream<<"Modified quicktune values:"<<std::endl; header_printed = true; } dstream<<names[i]<<" = "<<val.getString()<<std::endl; } } END_DEBUG_EXCEPTION_HANDLER(errorstream) debugstreams_deinit(); return retval; }
int main(int argc, char *argv[]) { std::cout << "#####################################" << std::endl; std::cout << "# Welcome to the YARR Scan Console! #" << std::endl; std::cout << "#####################################" << std::endl; std::cout << "-> Parsing command line parameters ..." << std::endl; // Init parameters unsigned specNum = 0; std::string scanType = "digitalscan"; std::string configPath = ""; std::string outputDir = "./"; bool doPlots = false; int c; while ((c = getopt(argc, argv, "hs:n:c:po:")) != -1) { switch (c) { case 'h': printHelp(); return 0; break; case 's': scanType = std::string(optarg); break; case 'n': specNum = atoi(optarg); break; case 'c': configPath = optarg; break; case 'p': doPlots = true; break; case 'o': outputDir = std::string(optarg); if (outputDir.back() != '/') outputDir = outputDir + "/"; break; case '?': if (optopt == 's' || optopt == 'n' || optopt == 'c') { std::cerr << "-> Option " << (char)optopt << " requires a parameter! (Proceeding with default)" << std::endl; } else { std::cerr << "-> Unknown parameter: " << (char)optopt << std::endl; } break; default: std::cerr << "-> Error while parsing command line parameters!" << std::endl; return -1; } } std::cout << " SPEC Nr: " << specNum << std::endl; std::cout << " Scan Type: " << scanType << std::endl; std::cout << " Global configuration: " << configPath << std::endl; std::cout << " Output Plots: " << doPlots << std::endl; std::cout << " Output Directory: " << outputDir << std::endl; std::cout << std::endl; std::cout << "#################" << std::endl; std::cout << "# Init Hardware #" << std::endl; std::cout << "#################" << std::endl; std::cout << "-> Init SPEC " << specNum << " : " << std::endl; SpecController spec(specNum); TxCore tx(&spec); RxCore rx(&spec); Bookkeeper bookie(&tx, &rx); bookie.setTargetThreshold(1500); std::cout << "-> Read global config (" << configPath << "):" << std::endl; std::fstream gConfig(configPath, std::ios::in); if (!gConfig) { std::cerr << "## ERROR ## Could not open file: " << configPath << std::endl; return -1; } while (!gConfig.eof() && gConfig) { unsigned id, tx, rx; std::string name, feCfgPath; char peekaboo = gConfig.peek(); if (peekaboo == '\n') { gConfig.ignore(); peekaboo = gConfig.peek(); } if (peekaboo == '#') { char tmp[1024]; gConfig.getline(tmp, 1024); std::cout << " Skipping: " << tmp << std::endl; } else { gConfig >> name >> id >> tx >> rx >> feCfgPath; if (gConfig.eof()) break; std::cout << "-> Found FE " << name << std::endl; // Add FE to bookkeeper bookie.addFe(id, tx, rx); bookie.getLastFe()->setName(name); // TODO verify cfg typea // Load config bookie.getLastFe()->fromFileBinary(feCfgPath); // Set chipId again after loading in case we got std cfg bookie.getLastFe()->setChipId(id); } } std::cout << std::endl; std::cout << "#################" << std::endl; std::cout << "# Configure FEs #" << std::endl; std::cout << "#################" << std::endl; std::chrono::steady_clock::time_point cfg_start = std::chrono::steady_clock::now(); for (unsigned i=0; i<bookie.feList.size(); i++) { Fei4 *fe = bookie.feList[i]; std::cout << "-> Configuring " << fe->getName() << std::endl; // Select correct channel tx.setCmdEnable(0x1 << fe->getTxChannel()); // Configure fe->configure(); fe->configurePixels(); // TODO should call abstract configure only // Wait for fifo to be empty std::this_thread::sleep_for(std::chrono::microseconds(100)); while(!tx.isCmdEmpty()); } std::chrono::steady_clock::time_point cfg_end = std::chrono::steady_clock::now(); std::cout << "-> All FEs configured in " << std::chrono::duration_cast<std::chrono::milliseconds>(cfg_end-cfg_start).count() << " ms !" << std::endl; // Wait for rx to sync with FE stream // TODO Check RX sync std::this_thread::sleep_for(std::chrono::microseconds(1000)); // Enable all active channels tx.setCmdEnable(bookie.getTxMask()); std::cout << "-> Setting Tx Mask to: 0x" << std::hex << bookie.getTxMask() << std::dec << std::endl; rx.setRxEnable(bookie.getRxMask()); std::cout << "-> Setting Rx Mask to: 0x" << std::hex << bookie.getRxMask() << std::dec << std::endl; std::cout << std::endl; std::cout << "##############" << std::endl; std::cout << "# Setup Scan #" << std::endl; std::cout << "##############" << std::endl; // TODO Make this nice ScanBase *s = NULL; std::cout << "-> Selecting Scan: " << scanType << std::endl; if (scanType == "digitalscan") { std::cout << "-> Found Digital Scan" << std::endl; s = new Fei4DigitalScan(&bookie); } else if (scanType == "analogscan") { std::cout << "-> Found Analog Scan" << std::endl; s = new Fei4AnalogScan(&bookie); } else if (scanType == "thresholdscan") { std::cout << "-> Found Threshold Scan" << std::endl; s = new Fei4ThresholdScan(&bookie); } else if (scanType == "totscan") { std::cout << "-> Found ToT Scan" << std::endl; s = new Fei4TotScan(&bookie); } else if (scanType == "tune_globalthreshold") { std::cout << "-> Found Global Threshold Tuning" << std::endl; s = new Fei4GlobalThresholdTune(&bookie); } else if (scanType == "tune_pixelthreshold") { std::cout << "-> Found Pixel Threshold Tuning" << std::endl; s = new Fei4PixelThresholdTune(&bookie); } else if (scanType == "tune_globalpreamp") { std::cout << "-> Found Global Preamp Tuning" << std::endl; s = new Fei4GlobalPreampTune(&bookie); } else if (scanType == "tune_pixelpreamp") { std::cout << "-> Found Pixel Preamp Tuning" << std::endl; s = new Fei4PixelPreampTune(&bookie); } else if (scanType == "noisescan") { std::cout << "-> Found Noisescan" << std::endl; s = new Fei4NoiseScan(&bookie); } else { std::cout << "-> No matching Scan found, possible:" << std::endl; listScans(); std::cerr << "-> Aborting!" << std::endl; return -1; } // Init histogrammer and analysis for (unsigned i=0; i<bookie.feList.size(); i++) { Fei4 *fe = bookie.feList[i]; if (fe->isActive()) { // Init histogrammer per FE fe->histogrammer = new Fei4Histogrammer(); fe->histogrammer->connect(fe->clipDataFei4, fe->clipHisto); // Add generic histograms fe->histogrammer->addHistogrammer(new OccupancyMap()); fe->histogrammer->addHistogrammer(new TotMap()); fe->histogrammer->addHistogrammer(new Tot2Map()); fe->histogrammer->addHistogrammer(new L1Dist()); fe->histogrammer->addHistogrammer(new HitDist()); // Init analysis per FE and depending on scan type fe->ana = new Fei4Analysis(&bookie, fe->getRxChannel()); fe->ana->connect(s, fe->clipHisto, fe->clipResult); fe->ana->addAlgorithm(new L1Analysis()); if (scanType == "digitalscan") { fe->ana->addAlgorithm(new OccupancyAnalysis()); } else if (scanType == "analogscan") { fe->ana->addAlgorithm(new OccupancyAnalysis()); } else if (scanType == "thresholdscan") { fe->ana->addAlgorithm(new ScurveFitter()); } else if (scanType == "totscan") { fe->ana->addAlgorithm(new TotAnalysis()); } else if (scanType == "tune_globalthreshold") { fe->ana->addAlgorithm(new OccGlobalThresholdTune()); } else if (scanType == "tune_pixelthreshold") { fe->ana->addAlgorithm(new OccPixelThresholdTune()); } else if (scanType == "tune_globalpreamp") { fe->ana->addAlgorithm(new TotAnalysis()); } else if (scanType == "tune_pixelpreamp") { fe->ana->addAlgorithm(new TotAnalysis()); } else if (scanType == "noisescan") { fe->ana->addAlgorithm(new NoiseAnalysis()); } else { std::cout << "-> Analyses not defined for scan type" << std::endl; listScans(); std::cerr << "-> Aborting!" << std::endl; return -1; } } } std::cout << "-> Running pre scan!" << std::endl; s->init(); s->preScan(); unsigned int numThreads = std::thread::hardware_concurrency(); std::cout << "-> Starting " << numThreads << " processor Threads:" << std::endl; std::vector<std::thread> procThreads; for (unsigned i=0; i<numThreads; i++) { procThreads.push_back(std::thread(process, &bookie)); std::cout << " -> Processor thread #" << i << " started!" << std::endl; } std::vector<std::thread> anaThreads; std::cout << "-> Starting histogrammer and analysis threads:" << std::endl; for (unsigned i=0; i<bookie.feList.size(); i++) { Fei4 *fe = bookie.feList[i]; if (fe->isActive()) { anaThreads.push_back(std::thread(analysis, fe->histogrammer, fe->ana)); std::cout << " -> Analysis thread of Fe " << fe->getRxChannel() << std::endl; } } std::cout << std::endl; std::cout << "########" << std::endl; std::cout << "# Scan #" << std::endl; std::cout << "########" << std::endl; std::cout << "-> Starting scan!" << std::endl; std::chrono::steady_clock::time_point scan_start = std::chrono::steady_clock::now(); s->run(); s->postScan(); std::cout << "-> Scan done!" << std::endl; scanDone = true; std::chrono::steady_clock::time_point scan_done = std::chrono::steady_clock::now(); std::cout << "-> Waiting for processors to finish ..." << std::endl; for (unsigned i=0; i<numThreads; i++) { procThreads[i].join(); } std::chrono::steady_clock::time_point processor_done = std::chrono::steady_clock::now(); processorDone = true; std::cout << "-> Processor done, waiting for analysis ..." << std::endl; for (unsigned i=0; i<anaThreads.size(); i++) { anaThreads[i].join(); } std::chrono::steady_clock::time_point all_done = std::chrono::steady_clock::now(); std::cout << "-> All done!" << std::endl; tx.setCmdEnable(0x0); rx.setRxEnable(0x0); std::cout << std::endl; std::cout << "##########" << std::endl; std::cout << "# Timing #" << std::endl; std::cout << "##########" << std::endl; std::cout << "-> Configuration: " << std::chrono::duration_cast<std::chrono::milliseconds>(cfg_end-cfg_start).count() << " ms" << std::endl; std::cout << "-> Scan: " << std::chrono::duration_cast<std::chrono::milliseconds>(scan_done-scan_start).count() << " ms" << std::endl; std::cout << "-> Processing: " << std::chrono::duration_cast<std::chrono::milliseconds>(processor_done-scan_done).count() << " ms" << std::endl; std::cout << "-> Analysis: " << std::chrono::duration_cast<std::chrono::milliseconds>(all_done-processor_done).count() << " ms" << std::endl; std::cout << std::endl; std::cout << "###########" << std::endl; std::cout << "# Cleanup #" << std::endl; std::cout << "###########" << std::endl; // Cleanup delete s; for (unsigned i=0; i<bookie.feList.size(); i++) { Fei4 *fe = bookie.feList[i]; if (fe->isActive()) { // Save config std::cout << "-> Saving config of FE " << fe->getName() << std::endl; fe->toFileBinary(); // Plot if (doPlots) { std::cout << "-> Plotting histograms of FE " << fe->getRxChannel() << std::endl; fe->ana->plot("ch" + std::to_string(fe->getRxChannel()) + "_" + scanType, outputDir); } // Free delete fe->histogrammer; fe->histogrammer = NULL; delete fe->ana; fe->ana = NULL; } } return 0; }
void bv_refinementt::check_SAT(approximationt &a) { // get values get_values(a); // see if the satisfying assignment is spurious in any way const typet &type=ns.follow(a.expr.type()); if(type.id()==ID_floatbv) { // these are all trinary assert(a.expr.operands().size()==3); if(a.over_state==MAX_STATE) return; ieee_float_spect spec(to_floatbv_type(type)); ieee_floatt o0(spec), o1(spec); o0.unpack(a.op0_value); o1.unpack(a.op1_value); ieee_floatt result=o0; o0.rounding_mode=RM; o1.rounding_mode=RM; result.rounding_mode=RM; if(a.expr.id()==ID_floatbv_plus) result+=o1; else if(a.expr.id()==ID_floatbv_minus) result-=o1; else if(a.expr.id()==ID_floatbv_mult) result*=o1; else if(a.expr.id()==ID_floatbv_div) result/=o1; else assert(false); if(result.pack()==a.result_value) // ok return; #ifdef DEBUG ieee_floatt rr(spec); rr.unpack(a.result_value); std::cout << "S1: " << o0 << " " << a.expr.id() << " " << o1 << " != " << rr << std::endl; std::cout << "S2: " << integer2binary(a.op0_value, spec.width()) << " " << a.expr.id() << " " << integer2binary(a.op1_value, spec.width()) << "!=" << integer2binary(a.result_value, spec.width()) << std::endl; std::cout << "S3: " << integer2binary(a.op0_value, spec.width()) << " " << a.expr.id() << " " << integer2binary(a.op1_value, spec.width()) << "==" << integer2binary(result.pack(), spec.width()) << std::endl; #endif //if(a.over_state==1) { std::cout << "DISAGREEMENT!\n"; exit(1); } if(a.over_state<max_node_refinement) { bvt r; float_utilst float_utils(prop); float_utils.spec=spec; float_utils.rounding_mode_bits.set(RM); literalt op0_equal= bv_utils.equal(a.op0_bv, float_utils.build_constant(o0)); literalt op1_equal= bv_utils.equal(a.op1_bv, float_utils.build_constant(o1)); literalt result_equal= bv_utils.equal(a.result_bv, float_utils.build_constant(result)); literalt op0_and_op1_equal= prop.land(op0_equal, op1_equal); prop.l_set_to_true( prop.limplies(op0_and_op1_equal, result_equal)); } else { // give up // remove any previous over-approximation a.over_assumptions.clear(); a.over_state=MAX_STATE; bvt r; float_utilst float_utils(prop); float_utils.spec=spec; float_utils.rounding_mode_bits.set(RM); bvt op0=a.op0_bv, op1=a.op1_bv, res=a.result_bv; if(a.expr.id()==ID_floatbv_plus) r=float_utils.add(op0, op1); else if(a.expr.id()==ID_floatbv_minus) r=float_utils.sub(op0, op1); else if(a.expr.id()==ID_floatbv_mult) r=float_utils.mul(op0, op1); else if(a.expr.id()==ID_floatbv_div) r=float_utils.div(op0, op1); else assert(0); assert(r.size()==res.size()); bv_utils.set_equal(r, res); } } else if(type.id()==ID_signedbv || type.id()==ID_unsignedbv) { // these are all binary assert(a.expr.operands().size()==2); // already full interpretation? if(a.over_state>0) return; bv_spect spec(type); bv_arithmetict o0(spec), o1(spec); o0.unpack(a.op0_value); o1.unpack(a.op1_value); // division by zero is never spurious if((a.expr.id()==ID_div || a.expr.id()==ID_mod) && o1==0) return; if(a.expr.id()==ID_mult) o0*=o1; else if(a.expr.id()==ID_div) o0/=o1; else if(a.expr.id()==ID_mod) o0%=o1; else assert(false); if(o0.pack()==a.result_value) // ok return; if(a.over_state==0) { // we give up right away and add the full interpretation bvt r; if(a.expr.id()==ID_mult) { r=bv_utils.multiplier( a.op0_bv, a.op1_bv, a.expr.type().id()==ID_signedbv?bv_utilst::SIGNED:bv_utilst::UNSIGNED); } else if(a.expr.id()==ID_div) { r=bv_utils.divider( a.op0_bv, a.op1_bv, a.expr.type().id()==ID_signedbv?bv_utilst::SIGNED:bv_utilst::UNSIGNED); } else if(a.expr.id()==ID_mod) { r=bv_utils.remainder( a.op0_bv, a.op1_bv, a.expr.type().id()==ID_signedbv?bv_utilst::SIGNED:bv_utilst::UNSIGNED); } else assert(0); bv_utils.set_equal(r, a.result_bv); } else assert(0); } else assert(0); status() << "Found spurious `" << a.as_string() << "' (state " << a.over_state << ")" << eom; progress=true; if(a.over_state<MAX_STATE) a.over_state++; }
NS_IMETHODIMP nsIOService::GetProtocolHandler(const char* scheme, nsIProtocolHandler* *result) { nsresult rv; NS_ENSURE_ARG_POINTER(scheme); // XXX we may want to speed this up by introducing our own protocol // scheme -> protocol handler mapping, avoiding the string manipulation // and service manager stuff rv = GetCachedProtocolHandler(scheme, result); if (NS_SUCCEEDED(rv)) return rv; bool externalProtocol = false; nsCOMPtr<nsIPrefBranch2> prefBranch; GetPrefBranch(getter_AddRefs(prefBranch)); if (prefBranch) { nsCAutoString externalProtocolPref("network.protocol-handler.external."); externalProtocolPref += scheme; rv = prefBranch->GetBoolPref(externalProtocolPref.get(), &externalProtocol); if (NS_FAILED(rv)) { externalProtocol = false; } } if (!externalProtocol) { nsCAutoString contractID(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX); contractID += scheme; ToLowerCase(contractID); rv = CallGetService(contractID.get(), result); if (NS_SUCCEEDED(rv)) { CacheProtocolHandler(scheme, *result); return rv; } #ifdef MOZ_X11 // check to see whether GVFS can handle this URI scheme. if it can // create a nsIURI for the "scheme:", then we assume it has support for // the requested protocol. otherwise, we failover to using the default // protocol handler. rv = CallGetService(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX"moz-gio", result); if (NS_SUCCEEDED(rv)) { nsCAutoString spec(scheme); spec.Append(':'); nsIURI *uri; rv = (*result)->NewURI(spec, nsnull, nsnull, &uri); if (NS_SUCCEEDED(rv)) { NS_RELEASE(uri); return rv; } NS_RELEASE(*result); } // check to see whether GnomeVFS can handle this URI scheme. if it can // create a nsIURI for the "scheme:", then we assume it has support for // the requested protocol. otherwise, we failover to using the default // protocol handler. // XXX should this be generalized into something that searches a // category? (see bug 234714) rv = CallGetService(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX"moz-gnomevfs", result); if (NS_SUCCEEDED(rv)) { nsCAutoString spec(scheme); spec.Append(':'); nsIURI *uri; rv = (*result)->NewURI(spec, nsnull, nsnull, &uri); if (NS_SUCCEEDED(rv)) { NS_RELEASE(uri); return rv; } NS_RELEASE(*result); } #endif } // Okay we don't have a protocol handler to handle this url type, so use // the default protocol handler. This will cause urls to get dispatched // out to the OS ('cause we can't do anything with them) when we try to // read from a channel created by the default protocol handler. rv = CallGetService(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX"default", result); if (NS_FAILED(rv)) return NS_ERROR_UNKNOWN_PROTOCOL; return rv; }
DiskLoc DataFileMgr::insert(const char* ns, const void* obuf, int32_t len, bool mayInterrupt, bool god, bool mayAddIndex, bool* addedID) { Database* database = cc().database(); bool wouldAddIndex = false; massert( 10093 , "cannot insert into reserved $ collection", god || NamespaceString::normal( ns ) ); uassert( 10094 , str::stream() << "invalid ns: " << ns , isValidNS( ns ) ); { const char *sys = strstr(ns, "system."); if ( sys ) { if ( !insert_checkSys(sys, ns, wouldAddIndex, obuf, god) ) return DiskLoc(); if ( mayAddIndex && wouldAddIndex ) { // TODO: this should be handled above this function BSONObj spec( static_cast<const char*>( obuf ) ); string collectionToIndex = spec.getStringField( "ns" ); uassert(10096, "invalid ns to index", collectionToIndex.find( '.' ) != string::npos); massert(10097, str::stream() << "trying to create index on wrong db " << " db: " << database->name() << " collection: " << collectionToIndex, database->ownsNS( collectionToIndex ) ); Collection* collection = database->getCollection( collectionToIndex ); if ( !collection ) { collection = database->createCollection( collectionToIndex, false, NULL, true ); verify( collection ); if ( !god ) ensureIdIndexForNewNs( collection ); } Status status = collection->getIndexCatalog()->createIndex( spec, mayInterrupt ); if ( status.code() == ErrorCodes::IndexAlreadyExists ) return DiskLoc(); uassertStatusOK( status ); return DiskLoc(); } } } Collection* collection = database->getCollection( ns ); if ( collection == NULL ) { collection = database->createCollection( ns, false, NULL, false ); int ies = Extent::initialSize(len); if( str::contains(ns, '$') && len + Record::HeaderSize >= BtreeData_V1::BucketSize - 256 && len + Record::HeaderSize <= BtreeData_V1::BucketSize + 256 ) { // probably an index. so we pick a value here for the first extent instead of using // initialExtentSize() which is more for user collections. // TODO: we could look at the # of records in the parent collection to be smarter here. ies = (32+4) * 1024; } collection->increaseStorageSize( ies, false); if ( !god ) ensureIdIndexForNewNs( collection ); } NamespaceDetails* d = collection->details(); IDToInsert idToInsert; // only initialized if needed if( !god ) { /* Check if we have an _id field. If we don't, we'll add it. Note that btree buckets which we insert aren't BSONObj's, but in that case god==true. */ BSONObj io((const char *) obuf); BSONElement idField = io.getField( "_id" ); uassert( 10099 , "_id cannot be an array", idField.type() != Array ); // we don't add _id for capped collections in local as they don't have an _id index if( idField.eoo() && !wouldAddIndex && nsToDatabase( ns ) != "local" && d->haveIdIndex() ) { if( addedID ) *addedID = true; idToInsert.init(); len += idToInsert.size(); } BSONElementManipulator::lookForTimestamps( io ); } int lenWHdr = d->getRecordAllocationSize( len + Record::HeaderSize ); fassert( 16440, lenWHdr >= ( len + Record::HeaderSize ) ); // If the collection is capped, check if the new object will violate a unique index // constraint before allocating space. if ( d->isCapped() && !god) { BSONObj temp = BSONObj( reinterpret_cast<const char *>( obuf ) ); Status ret = collection->getIndexCatalog()->checkNoIndexConflicts( temp ); uassert(12582, "duplicate key insert for unique index of capped collection", ret.isOK() ); } DiskLoc loc = allocateSpaceForANewRecord(ns, d, lenWHdr, god); if ( loc.isNull() ) { string errmsg = str::stream() << "insert: couldn't alloc space for object ns:" << ns << " capped:" << d->isCapped(); log() << errmsg; uasserted( 17248, errmsg ); } Record *r = loc.rec(); { verify( r->lengthWithHeaders() >= lenWHdr ); r = (Record*) getDur().writingPtr(r, lenWHdr); if( idToInsert.needed() ) { /* a little effort was made here to avoid a double copy when we add an ID */ int originalSize = *((int*) obuf); ((int&)*r->data()) = originalSize + idToInsert.size(); memcpy(r->data()+4, idToInsert.rawdata(), idToInsert.size()); memcpy(r->data()+4+idToInsert.size(), ((char*)obuf)+4, originalSize-4); } else { if( obuf ) // obuf can be null from internal callers memcpy(r->data(), obuf, len); } } addRecordToRecListInExtent(r, loc); d->incrementStats( r->netLength(), 1 ); // we don't bother resetting query optimizer stats for the god tables - also god is true when adding a btree bucket if ( !god ) collection->infoCache()->notifyOfWriteOp(); /* add this record to our indexes */ if ( d->getTotalIndexCount() > 0 ) { try { BSONObj obj(r->data()); collection->getIndexCatalog()->indexRecord(obj, loc); } catch( AssertionException& e ) { // should be a dup key error on _id index if( d->isCapped() ) { massert( 12583, "unexpected index insertion failure on capped collection", !d->isCapped() ); string s = e.toString(); s += " : on addIndex/capped - collection and its index will not match"; setLastError(0, s.c_str()); error() << s << endl; } else { // normal case -- we can roll back _deleteRecord(d, ns, r, loc); throw; } } } d->paddingFits(); return loc; }
/** * Translate a "rows" or "cols" spec into an array of nsFramesetSpecs */ nsresult nsHTMLFrameSetElement::ParseRowCol(const nsAString & aValue, int32_t& aNumSpecs, nsFramesetSpec** aSpecs) { if (aValue.IsEmpty()) { aNumSpecs = 0; *aSpecs = nullptr; return NS_OK; } static const PRUnichar sAster('*'); static const PRUnichar sPercent('%'); static const PRUnichar sComma(','); nsAutoString spec(aValue); // remove whitespace (Bug 33699) and quotation marks (bug 224598) // also remove leading/trailing commas (bug 31482) spec.StripChars(" \n\r\t\"\'"); spec.Trim(","); // Count the commas. Don't count more than X commas (bug 576447). PR_STATIC_ASSERT(NS_MAX_FRAMESET_SPEC_COUNT * sizeof(nsFramesetSpec) < (1 << 30)); int32_t commaX = spec.FindChar(sComma); int32_t count = 1; while (commaX != kNotFound && count < NS_MAX_FRAMESET_SPEC_COUNT) { count++; commaX = spec.FindChar(sComma, commaX + 1); } nsFramesetSpec* specs = new nsFramesetSpec[count]; if (!specs) { *aSpecs = nullptr; aNumSpecs = 0; return NS_ERROR_OUT_OF_MEMORY; } // Pre-grab the compat mode; we may need it later in the loop. bool isInQuirks = InNavQuirksMode(OwnerDoc()); // Parse each comma separated token int32_t start = 0; int32_t specLen = spec.Length(); for (int32_t i = 0; i < count; i++) { // Find our comma commaX = spec.FindChar(sComma, start); NS_ASSERTION(i == count - 1 || commaX != kNotFound, "Failed to find comma, somehow"); int32_t end = (commaX == kNotFound) ? specLen : commaX; // Note: If end == start then it means that the token has no // data in it other than a terminating comma (or the end of the spec). // So default to a fixed width of 0. specs[i].mUnit = eFramesetUnit_Fixed; specs[i].mValue = 0; if (end > start) { int32_t numberEnd = end; PRUnichar ch = spec.CharAt(numberEnd - 1); if (sAster == ch) { specs[i].mUnit = eFramesetUnit_Relative; numberEnd--; } else if (sPercent == ch) { specs[i].mUnit = eFramesetUnit_Percent; numberEnd--; // check for "*%" if (numberEnd > start) { ch = spec.CharAt(numberEnd - 1); if (sAster == ch) { specs[i].mUnit = eFramesetUnit_Relative; numberEnd--; } } } // Translate value to an integer nsAutoString token; spec.Mid(token, start, numberEnd - start); // Treat * as 1* if ((eFramesetUnit_Relative == specs[i].mUnit) && (0 == token.Length())) { specs[i].mValue = 1; } else { // Otherwise just convert to integer. nsresult err; specs[i].mValue = token.ToInteger(&err); if (err) { specs[i].mValue = 0; } } // Treat 0* as 1* in quirks mode (bug 40383) if (isInQuirks) { if ((eFramesetUnit_Relative == specs[i].mUnit) && (0 == specs[i].mValue)) { specs[i].mValue = 1; } } // Catch zero and negative frame sizes for Nav compatibility // Nav resized absolute and relative frames to "1" and // percent frames to an even percentage of the width // //if (isInQuirks && (specs[i].mValue <= 0)) { // if (eFramesetUnit_Percent == specs[i].mUnit) { // specs[i].mValue = 100 / count; // } else { // specs[i].mValue = 1; // } //} else { // In standards mode, just set negative sizes to zero if (specs[i].mValue < 0) { specs[i].mValue = 0; } start = end + 1; } } aNumSpecs = count; // Transfer ownership to caller here *aSpecs = specs; return NS_OK; }
int ftree_start() { #ifndef SMALL /* * if -M is given, the list of filenames on stdin is actually * an mtree(8) specfile, so parse the specfile into a NODE * * tree at ftnode, for use by next_file() */ if (Mflag) { if (fthead != NULL) { tty_warn(1, "The -M flag is only supported when reading file list from stdin"); return -1; } ftnode = spec(stdin); if (ftnode != NULL && (ftnode->type != F_DIR || strcmp(ftnode->name, ".") != 0)) { tty_warn(1, "First node of specfile is not `.' directory"); return -1; } return 0; } #endif /* SMALL */ /* * set up the operation mode of fts, open the first file arg. We must * use FTS_NOCHDIR, as the user may have to open multiple archives and * if fts did a chdir off into the boondocks, we may create an archive * volume in an place where the user did not expect to. */ ftsopts = FTS_NOCHDIR; /* * optional user flags that effect file traversal * -H command line symlink follow only (half follow) * -L follow sylinks (logical) * -P do not follow sylinks (physical). This is the default. * -X do not cross over mount points * -t preserve access times on files read. * -n select only the first member of a file tree when a match is found * -d do not extract subtrees rooted at a directory arg. */ if (Lflag) ftsopts |= FTS_LOGICAL; else ftsopts |= FTS_PHYSICAL; if (Hflag) #ifdef NET2_FTS tty_warn(0, "The -H flag is not supported on this version"); #else ftsopts |= FTS_COMFOLLOW; #endif if (Xflag) ftsopts |= FTS_XDEV; if ((fthead == NULL) && ((farray[0] = malloc(PAXPATHLEN+2)) == NULL)) { tty_warn(1, "Unable to allocate memory for file name buffer"); return -1; } if (ftree_arg() < 0) return -1; if (tflag && (atdir_start() < 0)) return -1; return 0; }
nsresult nsSMILParserUtils::ParseClockValue(const nsAString& aSpec, nsSMILTimeValue* aResult, PRUint32 aFlags, // = 0 PRBool* aIsMedia) // = nsnull { nsSMILTime offset = 0L; double component = 0.0; PRInt8 sign = 0; PRUint8 colonCount = 0; PRBool started = PR_FALSE; PRBool isValid = PR_TRUE; PRInt32 metricMultiplicand = MSEC_PER_SEC; PRBool numIsReal = PR_FALSE; PRBool prevNumCouldBeMin = PR_FALSE; PRBool numCouldBeMin = PR_FALSE; PRBool numCouldBeSec = PR_FALSE; PRBool isIndefinite = PR_FALSE; if (aIsMedia) { *aIsMedia = PR_FALSE; } NS_ConvertUTF16toUTF8 spec(aSpec); const char* start = spec.BeginReading(); const char* end = spec.EndReading(); while (start != end) { if (IsSpace(*start)) { if (started) { ++start; break; } // else, we haven't started yet, ignore initial whitespace ++start; } else if ((aFlags & kClockValueAllowSign) && (*start == '+' || *start == '-')) { if (sign != 0) { // sign has already been set isValid = PR_FALSE; break; } if (started) { // sign appears in the middle of the string isValid = PR_FALSE; break; } sign = (*start == '+') ? 1 : -1; ++start; // The NS_IS_DIGIT etc. macros are not locale-specific } else if (NS_IS_DIGIT(*start)) { prevNumCouldBeMin = numCouldBeMin; if (!ParseClockComponent(start, end, component, numIsReal, numCouldBeMin, numCouldBeSec)) { isValid = PR_FALSE; break; } started = PR_TRUE; } else if (*start == ':') { ++colonCount; // Neither minutes nor hours can be reals if (numIsReal) { isValid = PR_FALSE; break; } // Clock value can't start with a ':' if (!started) { isValid = PR_FALSE; break; } // Can't have more than two colons if (colonCount > 2) { isValid = PR_FALSE; break; } // Multiply the offset by 60 and add the last accumulated component offset = offset * 60 + PRInt64(component); component = 0.0; ++start; } else if (NS_IS_ALPHA(*start)) { if (colonCount > 0) { isValid = PR_FALSE; break; } if ((aFlags & kClockValueAllowIndefinite) && ConsumeSubstring(start, end, "indefinite")) { // We set a separate flag because we don't know what the state of the // passed in time value is and we shouldn't change it in the case of a // bad input string (so we can't initialise it to 0ms for example). isIndefinite = PR_TRUE; if (aResult) { aResult->SetIndefinite(); } } else if (aIsMedia && ConsumeSubstring(start, end, "media")) { *aIsMedia = PR_TRUE; } else if (!ParseMetricMultiplicand(start, end, metricMultiplicand)) { isValid = PR_FALSE; break; } // Nothing must come after the string except whitespace break; } else { isValid = PR_FALSE; break; } } if (!started) { isValid = PR_FALSE; } // Process remainder of string (if any) to ensure it is only trailing // whitespace (embedded whitespace is not allowed) SkipBeginWsp(start, end); if (start != end) { isValid = PR_FALSE; } // No more processing required if the value was "indefinite" or "media". if (isIndefinite || (aIsMedia && *aIsMedia)) return NS_OK; // If there is more than one colon then the previous component must be a // correctly formatted minute (i.e. two digits between 00 and 59) and the // latest component must be a correctly formatted second (i.e. two digits // before the .) if (colonCount > 0 && (!prevNumCouldBeMin || !numCouldBeSec)) { isValid = PR_FALSE; } if (isValid) { // Tack on the last component if (colonCount > 0) { offset = offset * 60 * 1000; component *= 1000; // rounding component = (component >= 0) ? component + 0.5 : component - 0.5; offset += PRInt64(component); } else { component *= metricMultiplicand; // rounding component = (component >= 0) ? component + 0.5 : component - 0.5; offset = PRInt64(component); } if (aResult) { nsSMILTime millis = offset; if (sign == -1) { millis = -offset; } aResult->SetMillis(millis); } } return (isValid) ? NS_OK : NS_ERROR_FAILURE; }
LEVEL_RESULT playsingle_controller::play_scenario( const config::const_child_itors &story, bool skip_replay) { uint32_t start = SDL_GetTicks(); // level_ // save game: [snapshort] in save file // new game: [scenario] in <scenarios>.cfg // Start music. BOOST_FOREACH (const config &m, level_.child_range("music")) { sound::play_music_config(m); } sound::commit_music_changes(); if(!skip_replay) { // show_story(*gui_, level_["name"], story); // gui2::show_story(*gui_, level_["name"], story); } gui_->labels().read(level_); // Read sound sources assert(soundsources_manager_ != NULL); BOOST_FOREACH (const config &s, level_.child_range("sound_source")) { soundsource::sourcespec spec(s); soundsources_manager_->add(spec); } uint32_t end_sound_sources = SDL_GetTicks(); posix_print("playsingle_controller::play_scenario, sound sources, used time: %u ms\n", end_sound_sources - start); set_victory_when_enemy_no_city(level_["victory_when_enemy_no_city"].to_bool(true)); end_level_data &end_level = get_end_level_data(); end_level.carryover_percentage = level_["carryover_percentage"].to_int(game_config::gold_carryover_percentage); end_level.carryover_add = level_["carryover_add"].to_bool(); try { uint32_t end_entering_try = SDL_GetTicks(); posix_print("playsingle_controller::play_scenario, entering try, used time: %u ms\n", end_entering_try - end_sound_sources); fire_prestart(!loading_game_); uint32_t end_fire_prestart = SDL_GetTicks(); posix_print("playsingle_controller::play_scenario, fire_prestrt, used time: %u ms\n", end_fire_prestart - end_entering_try); init_gui(); fire_start(!loading_game_); gui_->recalculate_minimap(); // replaying_ = (recorder.at_end() == false); // Initialize countdown clock. std::vector<team>::iterator t; for(t = teams_.begin(); t != teams_.end(); ++t) { if (gamestate_.mp_settings().mp_countdown && !loading_game_) { t->set_countdown_time(1000 * gamestate_.mp_settings().mp_countdown_init_time); } } // if we loaded a save file in linger mode, skip to it. if (linger_) { //determine the bonus gold handling for this scenario const config end_cfg = level_.child_or_empty("endlevel"); end_level.carryover_percentage = level_["carryover_percentage"].to_int(game_config::gold_carryover_percentage); end_level.carryover_add = level_["carr`yover_add"].to_bool(); end_level.gold_bonus = end_cfg["bonus"].to_bool(true); end_level.carryover_report = false; throw end_level_exception(SKIP_TO_LINGER); } // Avoid autosaving after loading, but still // allow the first turn to have an autosave. bool save = !loading_game_; for(; ; first_player_ = 1) { play_turn(save); save = true; } //end for loop } catch(game::load_game_exception& lge) { // Loading a new game is effectively a quit. // if (lge.game != "") { gamestate_ = game_state(); } throw lge; } catch (end_level_exception &end_level_exn) { LEVEL_RESULT end_level_result = end_level_exn.result; if (!end_level.custom_endlevel_music.empty()) { if (end_level_result == DEFEAT) { set_defeat_music_list(end_level.custom_endlevel_music); } else { set_victory_music_list(end_level.custom_endlevel_music); } } if (teams_.empty()) { //store persistent teams gamestate_.snapshot = config(); return VICTORY; // this is probably only a story scenario, i.e. has its endlevel in the prestart event } const bool obs = is_observer(); if (end_level_result == DEFEAT || end_level_result == VICTORY) { gamestate_.classification().completion = (end_level_exn.result == VICTORY) ? "victory" : "defeat"; // If we're a player, and the result is victory/defeat, then send // a message to notify the server of the reason for the game ending. if (!obs) { config cfg; config& info = cfg.add_child("info"); info["type"] = "termination"; info["condition"] = "game over"; info["result"] = gamestate_.classification().completion; network::send_data(lobby->transit, cfg); } else { gui2::show_transient_message(gui_->video(),_("Game Over"), _("The game is over.")); return OBSERVER_END; } } if (end_level_result == QUIT) { return QUIT; } else if (end_level_result == DEFEAT) { gamestate_.classification().completion = "defeat"; game_events::fire("defeat"); if (!obs) { const std::string& defeat_music = select_defeat_music(); if(defeat_music.empty() != true) sound::play_music_once(defeat_music); return DEFEAT; } else { return QUIT; } } else if (end_level_result == VICTORY) { gamestate_.classification().completion = !end_level.linger_mode ? "running" : "victory"; game_events::fire("victory"); // // Play victory music once all victory events // are finished, if we aren't observers. // // Some scenario authors may use 'continue' // result for something that is not story-wise // a victory, so let them use [music] tags // instead should they want special music. // if (!obs && end_level.linger_mode) { const std::string& victory_music = select_victory_music(); if(victory_music.empty() != true) sound::play_music_once(victory_music); } // Add all the units that survived the scenario. LOG_NG << "Add units that survived the scenario to the recall list.\n"; //store all units that survived (recall list for the next scenario) in snapshot gamestate_.snapshot = config(); //store gold and report victory store_gold(obs); return VICTORY; } else if (end_level_result == SKIP_TO_LINGER) { LOG_NG << "resuming from loaded linger state...\n"; //as carryover information is stored in the snapshot, we have to re-store it after loading a linger state gamestate_.snapshot = config(); store_gold(); return VICTORY; } } // end catch catch(network::error& e) { bool disconnect = false; if(e.socket) { e.disconnect(); disconnect = true; } config snapshot; to_config(snapshot); savegame::game_savegame save(heros_, heros_start_, gamestate_, *gui_, snapshot); save.save_game_interactive(gui_->video(), _("A network disconnection has occurred, and the game cannot continue. Do you want to save the game?"), false); if(disconnect) { throw network::error(); } else { return QUIT; } } return QUIT; }
LEVEL_RESULT playsingle_controller::play_scenario( const config::const_child_itors &story, bool skip_replay) { LOG_NG << "in playsingle_controller::play_scenario()...\n"; // Start music. BOOST_FOREACH(const config &m, level_.child_range("music")) { sound::play_music_config(m); } sound::commit_music_changes(); if(!skip_replay) { show_story(*gui_, level_["name"], story); } gui_->labels().read(level_); // Read sound sources assert(soundsources_manager_ != NULL); BOOST_FOREACH(const config &s, level_.child_range("sound_source")) { soundsource::sourcespec spec(s); soundsources_manager_->add(spec); } set_victory_when_enemies_defeated(level_["victory_when_enemies_defeated"].to_bool(true)); set_remove_from_carryover_on_leaders_loss(level_["remove_from_carryover_on_leaders_loss"].to_bool(true)); end_level_data &end_level = get_end_level_data(); end_level.carryover_percentage = level_["carryover_percentage"].to_int(game_config::gold_carryover_percentage); end_level.carryover_add = level_["carryover_add"].to_bool(); bool past_prestart = false; LOG_NG << "entering try... " << (SDL_GetTicks() - ticks_) << "\n"; try { // At the beginning of the scenario, save a snapshot as replay_start if(gamestate_.snapshot.child_or_empty("variables")["turn_number"].to_int(-1)<1){ gamestate_.replay_start() = to_config(); gamestate_.write_snapshot(gamestate_.replay_start(), gui_.get()); } fire_preload(); replaying_ = (recorder.at_end() == false); if(!loading_game_ ) { if(replaying_) { //can this codepath be reached ? //note this when we are entering an mp game and see the 'replay' of the game //this path is not reached because we receive the replay later config* pstart = recorder.get_next_action(); assert(pstart->has_child("start")); } else { assert(recorder.empty()); recorder.add_start(); recorder.get_next_action(); } //we can only use a set_scontext_synced with a non empty recorder. set_scontext_synced sync; fire_prestart(true); init_gui(); past_prestart = true; LOG_NG << "first_time..." << (recorder.is_skipping() ? "skipping" : "no skip") << "\n"; events::raise_draw_event(); fire_start(true); gui_->recalculate_minimap(); } else { init_gui(); past_prestart = true; events::raise_draw_event(); fire_start(false); gui_->recalculate_minimap(); } LOG_NG << "starting main loop\n" << (SDL_GetTicks() - ticks_) << "\n"; // Initialize countdown clock. std::vector<team>::iterator t; for(t = teams_.begin(); t != teams_.end(); ++t) { if (gamestate_.mp_settings().mp_countdown && !loading_game_ ){ t->set_countdown_time(1000 * gamestate_.mp_settings().mp_countdown_init_time); } } // if we loaded a save file in linger mode, skip to it. if (linger_) { //determine the bonus gold handling for this scenario end_level.read(level_.child_or_empty("endlevel")); end_level.transient.carryover_report = false; end_level.transient.disabled = true; throw end_level_exception(SKIP_TO_LINGER); } // Avoid autosaving after loading, but still // allow the first turn to have an autosave. bool save = !loading_game_; ai_testing::log_game_start(); for(; ; first_player_ = 1) { play_turn(save); save = true; } //end for loop } catch(const game::load_game_exception &) { // Loading a new game is effectively a quit. // if ( game::load_game_exception::game != "" ) { gamestate_ = game_state(); } throw; } catch (end_level_exception &end_level_exn) { if(!past_prestart) { draw_solid_tinted_rectangle( 0, 0, gui_->video().getx(), gui_->video().gety(), 0, 0, 0, 1.0, gui_->video().getSurface() ); update_rect(0, 0, gui_->video().getx(), gui_->video().gety()); } ai_testing::log_game_end(); LEVEL_RESULT end_level_result = end_level_exn.result; if (!end_level.transient.custom_endlevel_music.empty()) { if (end_level_result == DEFEAT) { set_defeat_music_list(end_level.transient.custom_endlevel_music); } else { set_victory_music_list(end_level.transient.custom_endlevel_music); } } if (teams_.empty()) { //store persistent teams gamestate_.snapshot = config(); return VICTORY; // this is probably only a story scenario, i.e. has its endlevel in the prestart event } const bool obs = is_observer(); if (game_config::exit_at_end) { exit(0); } if (end_level_result == DEFEAT || end_level_result == VICTORY) { gamestate_.classification().completion = (end_level_exn.result == VICTORY) ? "victory" : "defeat"; // If we're a player, and the result is victory/defeat, then send // a message to notify the server of the reason for the game ending. if (!obs) { config cfg; config& info = cfg.add_child("info"); info["type"] = "termination"; info["condition"] = "game over"; info["result"] = gamestate_.classification().completion; network::send_data(cfg, 0); } else { gui2::show_transient_message(gui_->video(),_("Game Over"), _("The game is over.")); return OBSERVER_END; } } if (end_level_result == QUIT) { return QUIT; } else if (end_level_result == DEFEAT) { gamestate_.classification().completion = "defeat"; game_events::fire("defeat"); if (!obs) { const std::string& defeat_music = select_defeat_music(); if(defeat_music.empty() != true) sound::play_music_once(defeat_music); return DEFEAT; } else { return QUIT; } } else if (end_level_result == VICTORY) { gamestate_.classification().completion = !end_level.transient.linger_mode ? "running" : "victory"; game_events::fire("victory"); // // Play victory music once all victory events // are finished, if we aren't observers. // // Some scenario authors may use 'continue' // result for something that is not story-wise // a victory, so let them use [music] tags // instead should they want special music. // if (!obs && end_level.transient.linger_mode) { const std::string& victory_music = select_victory_music(); if(victory_music.empty() != true) sound::play_music_once(victory_music); } // Add all the units that survived the scenario. LOG_NG << "Add units that survived the scenario to the recall list.\n"; for(unit_map::iterator un = units_.begin(); un != units_.end(); ++un) { if (teams_[un->side() - 1].persistent()) { LOG_NG << "Added unit " << un->id() << ", " << un->name() << "\n"; un->new_turn(); un->new_scenario(); teams_[un->side() - 1].recall_list().push_back(*un); } } gamestate_.snapshot = config(); if(!is_observer()) { persist_.end_transaction(); } return VICTORY; } else if (end_level_result == SKIP_TO_LINGER) { LOG_NG << "resuming from loaded linger state...\n"; //as carryover information is stored in the snapshot, we have to re-store it after loading a linger state gamestate_.snapshot = config(); if(!is_observer()) { persist_.end_transaction(); } return VICTORY; } } // end catch catch(network::error& e) { bool disconnect = false; if(e.socket) { e.disconnect(); disconnect = true; } savegame::ingame_savegame save(gamestate_, *gui_, to_config(), preferences::save_compression_format()); save.save_game_interactive(gui_->video(), _("A network disconnection has occurred, and the game cannot continue. Do you want to save the game?"), gui::YES_NO); if(disconnect) { throw network::error(); } else { return QUIT; } } return QUIT; }
void DefNewGeneration::compute_new_size() { // This is called after a gc that includes the following generation // (which is required to exist.) So from-space will normally be empty. // Note that we check both spaces, since if scavenge failed they revert roles. // If not we bail out (otherwise we would have to relocate the objects) if (!from()->is_empty() || !to()->is_empty()) { return; } int next_level = level() + 1; GenCollectedHeap* gch = GenCollectedHeap::heap(); assert(next_level < gch->_n_gens, "DefNewGeneration cannot be an oldest gen"); Generation* next_gen = gch->_gens[next_level]; size_t old_size = next_gen->capacity(); size_t new_size_before = _virtual_space.committed_size(); size_t min_new_size = spec()->init_size(); size_t max_new_size = reserved().byte_size(); assert(min_new_size <= new_size_before && new_size_before <= max_new_size, "just checking"); // All space sizes must be multiples of Generation::GenGrain. size_t alignment = Generation::GenGrain; // Compute desired new generation size based on NewRatio and // NewSizeThreadIncrease size_t desired_new_size = old_size/NewRatio; int threads_count = Threads::number_of_non_daemon_threads(); size_t thread_increase_size = threads_count * NewSizeThreadIncrease; desired_new_size = align_size_up(desired_new_size + thread_increase_size, alignment); // Adjust new generation size desired_new_size = MAX2(MIN2(desired_new_size, max_new_size), min_new_size); assert(desired_new_size <= max_new_size, "just checking"); bool changed = false; if (desired_new_size > new_size_before) { size_t change = desired_new_size - new_size_before; assert(change % alignment == 0, "just checking"); if (expand(change)) { changed = true; } // If the heap failed to expand to the desired size, // "changed" will be false. If the expansion failed // (and at this point it was expected to succeed), // ignore the failure (leaving "changed" as false). } if (desired_new_size < new_size_before && eden()->is_empty()) { // bail out of shrinking if objects in eden size_t change = new_size_before - desired_new_size; assert(change % alignment == 0, "just checking"); _virtual_space.shrink_by(change); changed = true; } if (changed) { // The spaces have already been mangled at this point but // may not have been cleared (set top = bottom) and should be. // Mangling was done when the heap was being expanded. compute_space_boundaries(eden()->used(), SpaceDecorator::Clear, SpaceDecorator::DontMangle); MemRegion cmr((HeapWord*)_virtual_space.low(), (HeapWord*)_virtual_space.high()); Universe::heap()->barrier_set()->resize_covered_region(cmr); if (Verbose && PrintGC) { size_t new_size_after = _virtual_space.committed_size(); size_t eden_size_after = eden()->capacity(); size_t survivor_size_after = from()->capacity(); gclog_or_tty->print("New generation size " SIZE_FORMAT "K->" SIZE_FORMAT "K [eden=" SIZE_FORMAT "K,survivor=" SIZE_FORMAT "K]", new_size_before/K, new_size_after/K, eden_size_after/K, survivor_size_after/K); if (WizardMode) { gclog_or_tty->print("[allowed " SIZE_FORMAT "K extra for %d threads]", thread_increase_size/K, threads_count); } gclog_or_tty->cr(); } } }
void task_worker_pool::enqueue(task* t) { dassert(t->spec().pool_code == spec().pool_code || t->spec().type == TASK_TYPE_RPC_RESPONSE, "Invalid thread pool used"); if (_is_running) { int idx = (_spec.partitioned ? t->hash() % _queues.size() : 0); task_queue* q = _queues[idx]; //dinfo("%s pool::enqueue %s (%016llx)", _node->name(), task->spec().name, task->id()); if (t->delay_milliseconds() == 0) { auto controller = _controllers[idx]; if (controller != nullptr) { while (!controller->is_task_accepted(t)) { // any customized rejection handler? if (t->spec().rejection_handler != nullptr) { t->spec().rejection_handler(t, controller); ddebug("task %s (%016llx) is rejected", t->spec().name, t->id() ); return; } std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } else if (t->spec().type == TASK_TYPE_RPC_REQUEST && _spec.max_input_queue_length != 0xFFFFFFFFUL) { while ((uint32_t)q->count() >= _spec.max_input_queue_length) { // any customized rejection handler? if (t->spec().rejection_handler != nullptr) { t->spec().rejection_handler(t, controller); ddebug("task %s (%016llx) is rejected because the target queue is full", t->spec().name, t->id() ); return; } std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } } // add reference before adding to the queue t->add_ref(); return q->enqueue(t); } else { dassert (false, "worker pool %s must be started before enqueue task %s", spec().name.c_str(), t->spec().name ); } }
bool OpenEXROutput::write_tiles (int xbegin, int xend, int ybegin, int yend, int zbegin, int zend, TypeDesc format, const void *data, stride_t xstride, stride_t ystride, stride_t zstride) { // std::cerr << "exr::write_tiles " << xbegin << ' ' << xend // << ' ' << ybegin << ' ' << yend << "\n"; if (! m_output_tiled || ! m_spec.valid_tile_range (xbegin, xend, ybegin, yend, zbegin, zend)) return false; // Compute where OpenEXR needs to think the full buffers starts. // OpenImageIO requires that 'data' points to where the client wants // to put the pixels being read, but OpenEXR's frameBuffer.insert() // wants where the address of the "virtual framebuffer" for the // whole image. bool native = (format == TypeDesc::UNKNOWN); size_t user_pixelbytes = m_spec.pixel_bytes (native); size_t pixelbytes = m_spec.pixel_bytes (true); if (native && xstride == AutoStride) xstride = (stride_t) user_pixelbytes; m_spec.auto_stride (xstride, ystride, zstride, format, spec().nchannels, (xend-xbegin), (yend-ybegin)); data = to_native_rectangle (xbegin, xend, ybegin, yend, zbegin, zend, format, data, xstride, ystride, zstride, m_scratch); // clamp to the image edge xend = std::min (xend, m_spec.x+m_spec.width); yend = std::min (yend, m_spec.y+m_spec.height); zend = std::min (zend, m_spec.z+m_spec.depth); int firstxtile = (xbegin-m_spec.x) / m_spec.tile_width; int firstytile = (ybegin-m_spec.y) / m_spec.tile_height; int nxtiles = (xend - xbegin + m_spec.tile_width - 1) / m_spec.tile_width; int nytiles = (yend - ybegin + m_spec.tile_height - 1) / m_spec.tile_height; std::vector<char> padded; int width = nxtiles*m_spec.tile_width; int height = nytiles*m_spec.tile_height; stride_t widthbytes = width * pixelbytes; if (width != (xend-xbegin) || height != (yend-ybegin)) { // If the image region is not an even multiple of the tile size, // we need to copy and add padding. padded.resize (pixelbytes * width * height, 0); OIIO::copy_image (m_spec.nchannels, xend-xbegin, yend-ybegin, 1, data, pixelbytes, pixelbytes, (xend-xbegin)*pixelbytes, (xend-xbegin)*(yend-ybegin)*pixelbytes, &padded[0], pixelbytes, widthbytes, height*widthbytes); data = &padded[0]; } char *buf = (char *)data - xbegin * pixelbytes - ybegin * widthbytes; try { Imf::FrameBuffer frameBuffer; size_t chanoffset = 0; for (int c = 0; c < m_spec.nchannels; ++c) { size_t chanbytes = m_spec.channelformats.size() ? m_spec.channelformats[c].size() : m_spec.format.size(); frameBuffer.insert (m_spec.channelnames[c].c_str(), Imf::Slice (m_pixeltype[c], buf + chanoffset, pixelbytes, widthbytes)); chanoffset += chanbytes; } m_output_tiled->setFrameBuffer (frameBuffer); m_output_tiled->writeTiles (firstxtile, firstxtile+nxtiles-1, firstytile, firstytile+nytiles-1, m_miplevel, m_miplevel); } catch (const std::exception &e) { error ("Failed OpenEXR write: %s", e.what()); return false; } return true; }