void PolarRing::create(const RLLMesh &mesh, bool hasHalfLevel) { this->mesh = &mesh; vr.set_size(mesh.getNumGrid(0, GridType::FULL, true), mesh.getNumGrid(2, GridType::FULL)); divr.set_size(mesh.getNumGrid(0, GridType::FULL, true), mesh.getNumGrid(2, GridType::FULL)); for (int k = 0; k < vr.n_cols; ++k) { for (int i = 0; i < vr.n_rows; ++i) { vr(i, k) = new TimeLevels<SphereVelocity, 2>(hasHalfLevel); for (int l = 0; l < vr(i, k)->getNumLevel(INCLUDE_HALF_LEVEL); ++l) { vr(i, k)->getLevel(l).setNumDim(mesh.getDomain().getNumDim()); } divr(i, k) = new TimeLevels<double, 2>(hasHalfLevel); } } }
vector<uint8_t> ModCom::comunicate(vector<uint8_t> buffer, bool readdata, int sizeread) { uint8_t *buffer_out = &(buffer[0]); uint8_t buffer_in[255]; serialport_flush(fd); serialport_write(fd, (char*)buffer_out); if (!readdata) { vector<uint8_t> toreturn; return toreturn; } // if only send //serial_read(fd, buffer_in, 1, DEF_TIMEOUT); serialport_read(fd, buffer_in, sizeread, DEF_TIMEOUT); if (buffer_in[0] != 0xFF) { vector<uint8_t> toreturn; return toreturn; } vector<uint8_t> vr(buffer_in, buffer_in + sizeread); return vr; }
void CPlayerToolBar::ArrangeControls() { if (!::IsWindow(m_volctrl.m_hWnd)) { return; } CRect r; GetClientRect(&r); CRect br = GetBorders(); CRect r10; GetItemRect(10, &r10); CRect vr(r.right + br.right - 60, r.top - 2, r.right + br.right + 6, r.bottom); m_volctrl.MoveWindow(vr); CRect thumbRect; m_volctrl.GetThumbRect(thumbRect); m_volctrl.MapWindowPoints(this, thumbRect); vr.top += std::max((r.bottom - thumbRect.bottom - 4) / 2, 0l); vr.left -= m_volumeMinSizeInc = MulDiv(thumbRect.Height(), 50, 19) - 50; m_volctrl.MoveWindow(vr); UINT nID; UINT nStyle; int iImage; GetButtonInfo(12, nID, nStyle, iImage); SetButtonInfo(11, GetItemID(11), TBBS_SEPARATOR, vr.left - iImage - r10.right - (r10.bottom - r10.top) + 11); }
int LicensePlate::GetComponent(const Mat& LP, vector<int>& area, vector<Rect>& rect) { int R = LP.rows; int C = LP.cols; memset(mark, -1, R * sizeof(mark[0])); int nComponent = 0; for(int r = 0; r < R; r++) for(int c = 0; c < C; c++) { if(mark[r][c] == -1 && LP.at<uchar>(r, c)) myFloodFill(LP, r, c, nComponent++, R, C); } area.resize(nComponent, 0); rect.resize(nComponent); vector<pair<Point, Point> > vr(nComponent); for(int i = 0; i < nComponent; i++) { vr[i].first.x = 10000; vr[i].first.y = 10000; vr[i].second.x = 0; vr[i].second.y = 0; } for(int r = 0; r < R; r++) for(int c = 0; c < C; c++) { int which = mark[r][c]; if(which != -1) { area[which]++; if(vr[which].first.x > c) vr[which].first.x = c; if(vr[which].first.y > r) vr[which].first.y = r; if(vr[which].second.x < c) vr[which].second.x = c; if(vr[which].second.y < r) vr[which].second.y = r; } } for(int i = 0; i < nComponent; i++) { rect[i] = Rect(vr[i].first, vr[i].second); } return nComponent; }
/* ============================================== main task routine ============================================== */ int main(void) { pool_memadd((uint32_t)pool, sizeof(pool)); #ifdef DEBUG dbg.start(); #endif int val; float degrees; CAdc vr(AD5); // use A5 for VR CServo servo(PWM1); // use PWM1 for Servo Motor vr.begin(); servo.begin(); // Enter an endless loop while(1){ val = vr.read(0.1, 8); degrees = AD2Degrees(val); servo = degrees; #ifdef DEBUG if ( dbg.isDebugMode() ) { dbg.println("ADC=%d, Degrees=%f\n", val, degrees); } #endif sleep(100); } return 0 ; }
void graph3d::grid_draw(void) { mesh_material::set_default(); VECT vn(0.0f,0.0f,-1.0f); VECT vf(0.0f,0.0f, 1.0f); GPIPE *p_gpipe = gpipe_get(); p_gpipe->screen_normal_to_world(&vn); p_gpipe->screen_normal_to_world(&vf); // v1->v2 VECT dir; dir = vf-vn; dir *= 0.5f; vn += dir; vn.y = 0.0f; VECT vl(-1.0f,0.0f,1.0f); VECT vr( 1.0f,0.0f,1.0f); p_gpipe->screen_normal_to_world(&vl); p_gpipe->screen_normal_to_world(&vr); VECT width; width = vr-vl; draw_floor_line(&vn,width.size(),2,40); }
void file_bstore::add_file(const std::string& name) { file_info fi; fi.name = m_dir + "/" + name; file_io* file = new file_io(fi.name); fi.io = file; char prefix; std::vector<char> record; file->seek(0); if (!read_record(file, prefix, record)) throw io_exception("File has no header data"); if (prefix != 'S') throw io_exception("File has incorrect header data"); vector_reader vr(record); off_t start_loc; deserialize(vr, start_loc); m_slabs.insert(std::make_pair(start_loc, fi)); file->seek_end(); off_t file_size = file->get_offset(); if (start_loc + file_size > m_size) { m_cur_slab = file; m_size = start_loc + file_size; } }
int main() { try { std::shared_ptr<gal::verb::VerbosityRegistry> vr( new gal::verb::VerbosityRegistry); vr->reg<gal::mng::managed_process>( "gal managed_process"); vr->reg<gal::mng::managed_object>( "gal managed_object"); vr->reg<gal::registry_base>( "gal registry_base"); vr->reg<gal::mng::registry_process>("gal registry_process"); vr->reg<gal::mng::registry_object>( "gal registry_object"); typedef gal::mng::registry_object R1; typedef std::shared_ptr<R1> S_R1; typedef gal::mng::registry_process R0; typedef std::shared_ptr<R0> S_R0; // process registry S_R0 r0(new R0); r0->VERB::init_verb(vr); r0->init(); // object registry S_R1 r1(new R1); r1->VERB::init_verb(vr); r0->reg(r1); r1->init(); typedef std::shared_ptr<foo> S_F; S_F f0(new foo); S_F f1(new foo); S_F f2(new foo); f0->init_verb(vr); f1->init_verb(vr); f2->init_verb(vr); r1->reg(f0); r1->reg(f1); r1->reg(f2); gal::object_index i0 = f0->get_index(); r1->get(i0); } catch(std::exception & e) { printf("%s\n", e.what()); } }
void VoxelSceneNode::SetValue(irr::core::vector3d<int> Position, float value) { VoxelReference vr(Position); if(chunkMap.find(vr.Chunk) != chunkMap.end()) { chunkMap[vr.Chunk].SetValue(vr.Position, value); } }
PolarRing::~PolarRing() { if (vr.size() > 0) { for (int k = 0; k < vr.n_cols; ++k) { for (int i = 0; i < vr.n_rows; ++i) { delete vr(i, k); delete divr(i, k); } } } }
void fct(const LCC& lcc) { vertex_range vr(vertices(lcc)); std::cout << "new for loop" << std::endl; for(vertex_descriptor vd : vr){ std::cout << vd->point() << std::endl; } std::cout << "boost::tie + std::for_each" << std::endl; vertex_iterator vb, ve; boost::tie(vb,ve) = vertices_range(lcc); std::for_each(vb,ve, Fct()); }
int main(void) { std::size_t i; scitbx::fftpack::complex_to_complex<double> cfft(10); std::vector<std::complex<double> > vc(cfft.n()); for(i=0;i<cfft.n();i++) { vc[i] = std::complex<double>(2.*i, 2.*i+1.); } cfft.forward(vc.begin()); for(i=0;i<cfft.n();i++) { std::cout << vc[i].real() << " " << vc[i].imag() << std::endl; } cfft.backward(vc.begin()); for(i=0;i<cfft.n();i++) { std::cout << vc[i].real() << " " << vc[i].imag() << std::endl; } scitbx::fftpack::real_to_complex<double> rfft(10); std::vector<double> vr(2 * rfft.n_complex()); for(i=0;i<rfft.n_real();i++) { vr[i] = 1.*i; } rfft.forward(vr.begin()); for(i=0;i<2*rfft.n_complex();i++) { std::cout << vr[i] << std::endl; } rfft.backward(vr.begin()); for(i=0;i<rfft.n_real();i++) { std::cout << vr[i] << std::endl; } scitbx::fftpack::complex_to_complex_3d<double> cfft3d(2, 3, 5); scitbx::af::versa<std::complex<double>, scitbx::af::c_grid<3> > c3dmap(scitbx::af::c_grid<3>(cfft3d.n())); cfft3d.forward(c3dmap.ref()); cfft3d.backward(c3dmap.ref()); scitbx::fftpack::real_to_complex_3d<double> rfft3d(3, 4, 5); scitbx::af::versa<double, scitbx::af::c_grid<3> > r3dmap(scitbx::af::c_grid<3>(rfft3d.m_real())); rfft3d.forward(r3dmap.ref()); rfft3d.backward(r3dmap.ref()); #ifdef NEVER_DEFINED #endif return 0; }
PapxFKPage::PapxFKPage(DataReader& dr) { unsigned char pagedata[512]; dr.Read(&pagedata, 512); m_icrun = pagedata[511]; MemoryReader vr(pagedata, m_icrun*17+4); m_BXMap.Read(vr); for (unsigned int i=0; i<m_BXMap.ObjectCount(); i++) { int iOffset = m_BXMap.ObjectAt(i).iWordPos * 2; MemoryReader mr(pagedata + iOffset, 512 - iOffset); m_vecPapxs.push_back(PapX(mr, false)); } }
TreeNode* sortedArrayToBST(std::vector<int>& nums) { // base condition if (nums.size()==0) return NULL; // extract left, right vector const auto mid = nums.begin() + nums.size() / 2; std::vector<int> vl(nums.begin(), mid); std::vector<int> vr(mid+1, nums.end()); // recursion TreeNode* p = new TreeNode(*mid); p->left = sortedArrayToBST(vl); p->right = sortedArrayToBST(vr); return p; }
bool vtkPointSet_to_polygon_mesh(vtkPointSet* poly_data, TM& tmesh) { typedef typename boost::property_map<TM, CGAL::vertex_point_t>::type VPMap; typedef typename boost::property_map_value<TM, CGAL::vertex_point_t>::type Point_3; typedef typename boost::graph_traits<TM>::vertex_descriptor vertex_descriptor; VPMap vpmap = get(CGAL::vertex_point, tmesh); // get nb of points and cells vtkIdType nb_points = poly_data->GetNumberOfPoints(); vtkIdType nb_cells = poly_data->GetNumberOfCells(); //extract points std::vector<vertex_descriptor> vertex_map(nb_points); for (vtkIdType i = 0; i<nb_points; ++i) { double coords[3]; poly_data->GetPoint(i, coords); vertex_descriptor v = add_vertex(tmesh); put(vpmap, v, Point_3(coords[0], coords[1], coords[2])); vertex_map[i]=v; } //extract cells for (vtkIdType i = 0; i<nb_cells; ++i) { if(poly_data->GetCellType(i) != 5 && poly_data->GetCellType(i) != 7 && poly_data->GetCellType(i) != 9) //only supported cells are triangles, quads and polygons continue; vtkCell* cell_ptr = poly_data->GetCell(i); vtkIdType nb_vertices = cell_ptr->GetNumberOfPoints(); if (nb_vertices < 3) return false; std::vector<vertex_descriptor> vr(nb_vertices); for (vtkIdType k=0; k<nb_vertices; ++k) vr[k]=vertex_map[cell_ptr->GetPointId(k)]; CGAL::Euler::add_face(vr, tmesh); } return true; }
virtual V m_bang() { if(!ref.Ok() || !ref.Check()) { /* if(!frms) post("%s - No length defined!",thisName()); else */ { ImmBuf ibuf(frms,zero); Vasp ret(frms,Vasp::Ref(ibuf)); ToOutVasp(0,ret); } } else if(ref.Vectors() > 1) post("%s - More than one vector in vasp!",thisName()); else { VBuffer *buf = ref.Buffer(0); const I len = buf->Length(),chns = buf->Channels(); // size of memory reservation (at least frms samples) const I rlen = frms > len?frms:len; ImmBuf imm(rlen,false); BS *dst = imm.Pointer(); const BS *src = buf->Pointer(); // post("!copy: src: %p,%i,%i -> dst: %p,%i",src,len,chns,dst,rlen); register int i; _DE_LOOP(i,len, ( dst[i] = *src,src += chns ) ) if(zero && rlen > len) ZeroSamples(dst+len,rlen-len); Vasp::Ref vr(imm); // post("!vr: %s,%i",vr.Ok()?vr.Symbol().Name():"***",vr.Offset()); Vasp ret(len,vr); ToOutVasp(0,ret); delete buf; } }
float v4r::Registration::MultiSessionModelling<PointT>::computeFSV (const typename pcl::PointCloud<PointT>::ConstPtr & cloud, pcl::PointCloud<pcl::Normal>::ConstPtr & normals, const std::vector<int> & indices, const Eigen::Matrix4f & pose, const typename pcl::PointCloud<PointT>::ConstPtr & range_image) { v4r::VisibilityReasoning<PointT> vr (525.f, 640, 480); vr.setThresholdTSS (0.01f); typename pcl::PointCloud<PointT>::Ptr model(new pcl::PointCloud<PointT>()); pcl::transformPointCloud(*cloud, indices, *model, pose); pcl::PointCloud<pcl::Normal>::Ptr model_normals (new pcl::PointCloud<pcl::Normal>); v4r::transformNormals(*normals, *model_normals, indices, pose); //Eigen::Matrix4f identity = Eigen::Matrix4f::Identity(); float fsv = vr.computeFSVWithNormals (range_image, model, model_normals); //the more points on the same surface the more reliable this is, so increase fsv if not many points int ss = vr.getFSVUsedPoints(); float ratio = 1.f - ss / static_cast<float>(model->points.size()); //std::cout << model->points.size() << " " << indices.size() << " fsv:" << fsv << std::endl; /*if(fsv > 0.1) {*/ /* ///debug pcl::visualization::PCLVisualizer vis("correspondences"); //int v1,v2; //vis.createViewPort(0,0,0.5,1,v1); //vis.createViewPort(0.5,0,1,1,v2); pcl::visualization::PointCloudColorHandlerCustom<PointT> handler(model, 255, 0, 0); vis.addPointCloud(range_image, "cloud_2"); vis.addPointCloud(model, handler, "cloud_1"); vis.spin(); */ /*}*/ return fsv * ratio; }
void VoxelSceneNode::UpdateVoxel(VoxelData & vd, bool subtract) { VoxelReference vr(vd.Position); chunkMapIterator = chunkMap.find(vr.Chunk); if(chunkMap.find(vr.Chunk) == chunkMap.end()) { //chunkMap[vr.Chunk] = VoxelChunk(); //chunkMap[vr.Chunk].Initialize(dimensions, vr.Chunk); //meshMap[vr.Chunk] = ChunkMesh(); //meshMap[vr.Chunk].Initialize(this, vr.Chunk); } chunkMap[vr.Chunk].UpdateVoxel(vr.Position, vd.Value, vd.Material, subtract); chunkMap[vr.Chunk].status = DIRTY; }
int VoxelSceneNode::GetMaterial(irr::core::vector3d<int> Position) { VoxelReference vr(Position); if(chunkMap.find(vr.Chunk) != chunkMap.end()) { if(chunkMap[vr.Chunk].status != EMPTY && chunkMap[vr.Chunk].status != FILLING) { return chunkMap[vr.Chunk].GetMaterial(vr.Position); } else { return -1; } } else { return -2; } }
/** * Rename virtual methods. */ size_t rename_virtuals(Scope& classes) { // build a ClassScope a RefsMap and a VirtualRenamer ClassScopes class_scopes(classes); scope_info(class_scopes); RefsMap def_refs; collect_refs(classes, def_refs); VirtualRenamer vr(class_scopes, def_refs); // rename virtual only first const auto obj_t = get_object_type(); int seed = 0; size_t renamed = vr.rename_virtual_scopes(obj_t, seed); TRACE(OBFUSCATE, 2, "Virtual renamed: %ld\n", renamed); // rename interfaces std::unordered_set<const VirtualScope*> visited; size_t intf_renamed = vr.rename_interface_scopes(seed); TRACE(OBFUSCATE, 2, "Interface renamed: %ld\n", intf_renamed); TRACE(OBFUSCATE, 2, "MAX seed: %d\n", seed); return renamed + intf_renamed; }
int VoxelSceneNode::GetAltitude(const irr::core::vector3d<int> & Position) { unsigned y; int height; for(y = 0; y < 16; y++) { VoxelReference vr(irr::core::vector3d<int>(Position.X, Position.Y - (y * dimensions.Y), Position.Z)); chunkMapIterator = chunkMap.find(vr.Chunk); if(chunkMapIterator != chunkMap.end()) { height = chunkMapIterator->second.GetHeight(irr::core::vector2d<int>(vr.Position.X, vr.Position.Z)); if(height >= 0) { return (vr.Chunk.Y * dimensions.Y) + height; } } } return -1; }
bool vector_test::run() { bool ok = true; vector< 4, double > v; double data[] = { 1, 2, 3, 4 }; v.iter_set( data, data+4 ); // tests copyFrom1DimCArray function ok = true; { size_t tmp = 1; for( size_t index = 0; ok && index < 4; ++index, ++tmp ) { ok = v.at( index ) == tmp; } tmp = 4; float dataf[] = { 4, 3, 2, 1 }; v.iter_set( dataf, dataf + 4 ); for( size_t index = 0; ok && index < 4; ++index, --tmp ) { ok = v.at( index ) == tmp; } log( "set( input_iterator begin_, input_iterator end_ )", ok ); if ( ! ok ) { std::stringstream error; error << v << std::endl; log_error( error.str() ); } } // tests operator+ function ok = true; { vector< 4, double > v_other; vector< 4, double > v_result; v = data; double datad[] = { 4, 3, 2, 1 }; v_other = datad; v_result = v + v_other; for( size_t index = 0; ok && index < 4; ++index ) { ok = v_result.at( index ) == 5; } v_result = v; v_result += v_other; for( size_t index = 0; ok && index < 4; ++index ) { ok = v_result.at( index ) == 5; } v = data; v_result = v + 2; for( size_t index = 0; ok && index < 4; ++index ) { ok = v_result.at( index ) == index + 3; } v_result = v; v_result += 2; for( size_t index = 0; ok && index < 4; ++index ) { ok = v_result.at( index ) == index + 3; } log( "operator+, operator+=", ok ); if ( ! ok ) { std::stringstream error; error << "\n" << "v " << v << "v_other " << v_other << "v_result " << v_result << std::endl; log_error( error.str() ); } } // tests operator- function ok = true; { vector< 4, double > v_other; vector< 4, double > v_result; v = data; double datad[] = { 1, 2, 3, 4 }; v_other = datad; v_result = v - v_other; for( size_t index = 0; ok && index < 4; ++index ) { ok = v_result.at( index ) == 0; } v_result = v; v_result -= v_other; for( size_t index = 0; ok && index < 4; ++index ) { ok = v_result.at( index ) == 0; } v_result = v - 1.0; for( size_t index = 0; ok && index < 4; ++index ) { ok = v_result.at( index ) == index; } v_result = v; v_result -= 1.0; for( size_t index = 0; ok && index < 4; ++index ) { ok = v_result.at( index ) == index; } log( "operator-, operator-=", ok ); if ( ! ok ) { std::stringstream error; error << "\n" << "v " << v << "v_other " << v_other << "v_result " << v_result << std::endl; log_error( error.str() ); } } // tests operator* function ok = true; { vector< 4, double > v_other; vector< 4, double > v_result; v = data; double datad[] = { 24, 12, 8, 6 }; v_other = datad; v_result = v * v_other; for( size_t index = 0; ok && index < 4; ++index ) { ok = v_result.at( index ) == 24; } v_result = v; v_result *= v_other; for( size_t index = 0; ok && index < 4; ++index ) { ok = v_result.at( index ) == 24; } v_result = v * 2.0; for( size_t index = 0; ok && index < 4; ++index ) { ok = v_result.at( index ) == v.at( index ) * 2.0; } v_result = v; v_result *= 2.0; for( size_t index = 0; ok && index < 4; ++index ) { ok = v_result.at( index ) == v.at( index ) * 2.0; } log( "operator*, operator*=", ok ); if ( ! ok ) { std::stringstream error; error << "\n" << "v " << v << "v_other " << v_other << "v_result " << v_result << std::endl; log_error( error.str() ); } } // tests operator/ function ok = true; { vector< 4, double > v_other; vector< 4, double > v_result; v = data; double datad[] = { 2, 4, 6, 8 }; v_other = datad; v_result = v / v_other; for( size_t index = 0; ok && index < 4; ++index ) { ok = ( v_result.at( index ) - 0.5 ) < 1e-12; } v_result = v; v_result /= v_other; for( size_t index = 0; ok && index < 4; ++index ) { ok = ( v_result.at( index ) - 0.5 ) < 1e-12; } v_result = v / 1.5; for( size_t index = 0; ok && index < 4; ++index ) { ok = ( v_result.at( index ) - ( v.at( index ) / 1.5 ) ) < 1e-12; } v_result = v; v_result /= 1.5; for( size_t index = 0; ok && index < 4; ++index ) { ok = ( v_result.at( index ) - ( v.at( index ) / 1.5 ) ) < 1e-12; } log( "operator/, operator/=", ok ); if ( !ok ) { std::stringstream error; error << "\n" << "v " << v << "v_other " << v_other << "v_result " << v_result << std::endl; log_error( error.str() ); } } // tests norm / normSquared (length/lengthSquared) computation ok = true; { vector< 4, double > vec; vec = data; double normSquared = vec.squared_length(); ok = normSquared == 1 * 1 + 2 * 2 + 3 * 3 + 4 * 4; double norm = vec.length(); if ( ok ) ok = sqrt( normSquared ) == norm; log( "length(), squared_length()", ok ); } // tests normalize ok = true; { vector< 4, double > vec; vec = data; vec.normalize(); ok = vec.length() == 1.0; log( "normalize(), maximum precision", ok, true ); if ( ! ok ) { ok = vec.length() - 1.0 < 1e-15; log( "normalize(), tolerance 1e-15", ok ); } if ( ! ok ) { std::stringstream ss; ss << "length after normalize() " << vec.length() << std::endl; log_error( ss.str() ); } } // constructor tests { bool ok = true; double vData[] = { 1, 2, 3, 4 }; vector< 4, double > v4( 1, 2, 3, 4 ); vector< 2, double > v2C; v2C = vData; vector< 2, double > v2( 1, 2 ); if ( ok && v2 != v2C ) ok = false; vector< 3, double > v3C; v3C = vData; vector< 3, double > v3( 1, 2, 3 ); if ( ok && v3 != v3C ) ok = false; vector< 4, double > v4C; v4C = vData; if ( ok && v4 != v4C ) ok = false; double vData2[] = { 23, 23, 23, 23 }; v4C = vData2; vector< 4, double > v4_( 23 ); if ( ok && v4_ != v4C ) ok = false; v3 = vData; v4C = vData; vector< 4, double > v4from3_1( v3, vData[ 3 ] ); if ( ok && v4from3_1 != v4C ) ok = false; double hvData[] = { 1., 2., 3., 0.25 }; double xvData[] = { 4.0, 8.0, 12.0 }; vector< 4, double > homogenous; homogenous.iter_set( hvData, hvData + 4 ); vector< 3, double > nonh; nonh.iter_set( xvData, xvData + 3 ); vector< 4, double > htest( nonh ); // to-homogenous-coordinates ctor if ( ok && htest != vector< 4, double >( 4, 8., 12., 1. ) ) { ok = false; } vector< 3, double > nhtest( homogenous ); // from homogenous-coordiates ctor if ( ok && nhtest != nonh ) { ok = false; } log( "constructors ", ok ); } // set tests { bool ok = true; vector< 4, double > vec; vec.set( 2, 3, 4, 5 ); vector< 4, double > vecCorrect; double vCData[] = { 2, 3, 4, 5 }; vecCorrect = vCData; if ( vec != vecCorrect ) ok = false; vec.set( 2 ); double vCData2[] = { 2, 2, 2, 2 }; vecCorrect = vCData2; if ( vec != vecCorrect ) ok = false; vector< 3, double > v( 2, 3, 4 ); // uncommenting the following line will throw a compiler error because the number // of arguments to set is != M //v.set( 2, 3, 4, 5 ); vecCorrect = vCData; vec.set( v, 5 ); if ( vec != vecCorrect ) ok = false; log( "set() functions", ok ); } // component accessors { bool ok = true; vector< 4, double > vd( 1, 2, 3, 4 ); if ( vd.x() == 1 && vd.y() == 2 && vd.z() == 3 && vd.w() == 4 ) {} else ok = false; log( "component accessors ( x(), y(), z(), w() )", ok ); } // dot product { bool ok = true; vector< 3, float > v0( 1, 2, 3 ); vector< 3, float > v1( -6, 5, -4 ); if ( v0.dot( v1 ) != -8 ) ok = false; log( "dot product, dot()", ok ); } // cross product { bool ok = true; vector< 3, float > v0( 1, 2, 3 ); vector< 3, float > v1( -6, 5, -4 ); vector< 3, float > vcorrect( -23, -14, 17 ); if ( v0.cross( v1 ) != vcorrect ) ok = false; log( "cross product, cross()", ok ); } { // TODO vector< 3, float > v0( 1, 2, 3 ); vector< 3, float > v1( -6, 5, -4 ); vector< 3, float > v2( -2, 2, -1 ); v0.squared_distance( v1 ); vector< 3, float > n; n.compute_normal( v0, v1, v2 ); vector< 3, double > vd( 3, 2, 1 ); v0 = vd; } { vector< 4, float > vf( -1.0f, 3.0f, -99.0f, -0.9f ); vector< 4, size_t > vui( 0, 5, 2, 4 ); bool ok = true; size_t index = vf.find_min_index(); float f = vf.find_min(); if ( index != 2 || f != -99.0f ) ok = false; if ( ok ) { index = vf.find_max_index(); f = vf.find_max(); if ( index != 1 || f != 3.0f ) ok = false; } size_t ui; if ( ok ) { index = vui.find_min_index(); ui = vui.find_min(); if ( index != 0 || ui != 0 ) { ok = false; } } if ( ok ) { index = vui.find_max_index(); ui = vui.find_max(); if ( index != 1 || ui != 5 ) { ok = false; } } log( "find_min/max(), find_min_index/max_index()", ok ); } { vector< 4, float > v( -1.0f, 3.0f, -99.0f, -0.9f ); float f = 4.0f; vector< 4, float > v_scaled = f * v; ok = true; if ( v_scaled != vector< 4, float >( -4.0f, 12.0f, -396.0f, -3.6f ) ) { ok = false; } log( "operator*( float, vector )", ok ); } { vector< 3, float > vf( 3.0, 2.0, 1.0 ); vector< 3, double > vd( vf ); vector< 3, double >::const_iterator it = vd.begin(), it_end = vd.end(); vector< 3, float >::const_iterator fit = vf.begin(); bool ok = true; for( ; ok && it != it_end; ++it, ++fit ) { if ( *it != *fit ) ok = false; } vd = 0.0; vd = vf; for( ; ok && it != it_end; ++it, ++fit ) { if ( *it != *fit ) ok = false; } // to-homogenous-coords and from-homogenous-coords assignment ops // are already tested in the tests for the respective ctors, // since the ctors call the assignment ops log( "conversion operator=, conversion ctor", ok ); } { vector< 4, float > vf( 3.0, 2.0, 1.0, 1.0 ); vector< 3, float >& v3 = vf.get_sub_vector< 3 >(); bool ok = v3.x() == vf.x() && v3.y() == vf.y(); v3.normalize(); if ( ok ) ok = v3.x() == vf.x() && v3.y() == vf.y(); log( "get_sub_vector< N >()", ok ); } #ifndef VMMLIB_NO_CONVERSION_OPERATORS { vector< 4, double > v; double* array = v; //const double* const_array = v; array[ 1 ] = 2.0; //const_array[ 2 ] = 3.0; } #endif { //elementwise sqrt vector< 4, float > vsq( 9.0, 4.0, 1.0, 2.0 ); vector< 4, float > vsq_check( 3.0, 2.0, 1.0, 1.414213538169861 ); vsq.sqrt_elementwise(); bool ok = vsq == vsq_check; log( "elementwise sqrt ", ok ); } { //elementwise sqrt vector< 4, float > vr( 9.0, 4.0, 1.0, 2.0 ); vector< 4, float > vr_check( 0.1111111119389534, 0.25, 1, 0.5 ); vr.reciprocal(); bool ok = vr == vr_check; log( "reciprocal ", ok ); } { //l2 norm vector< 4, float > vr( 9.0, 4.0, 1.0, 2.0 ); double v_norm_check = 10.09950493836208; double v_norm = vr.norm(); bool ok = ((v_norm - v_norm_check) < 0.0001); log( "l2 norm ", ok ); } return ok; }
int ForEachStatement::execRef(QoreValue& return_value, ExceptionSink* xsink) { int rc = 0; // instantiate local variables LVListInstantiator lvi(lvars, xsink); ParseReferenceNode* r = reinterpret_cast<ParseReferenceNode*>(list); // here we get the runtime reference ReferenceHolder<ReferenceNode> vr(r->evalToRef(xsink), xsink); if (*xsink) return 0; // get the current value of the lvalue expression ReferenceHolder<AbstractQoreNode> tlist(vr->eval(xsink), xsink); if (!code || *xsink || is_nothing(*tlist)) return 0; QoreListNode* l_tlist = tlist->getType() == NT_LIST ? reinterpret_cast<QoreListNode*>(*tlist) : 0; if (l_tlist && l_tlist->empty()) return 0; // execute "foreach" body ReferenceHolder<AbstractQoreNode> ln(0, xsink); unsigned i = 0; if (l_tlist) ln = new QoreListNode; while (true) { { LValueHelper n(var, xsink); if (!n) return 0; // assign variable to current value in list if (n.assign(l_tlist ? l_tlist->get_referenced_entry(i) : tlist.release())) return 0; } // set offset in thread-local data for "$#" ImplicitElementHelper eh(l_tlist ? (int)i : 0); // execute "for" body rc = code->execImpl(return_value, xsink); if (*xsink) return 0; // get value of foreach variable AbstractQoreNode* nv = var->eval(xsink); if (*xsink) return 0; // assign new value to temporary variable for later assignment to referenced lvalue if (l_tlist) reinterpret_cast<QoreListNode*>(*ln)->push(nv); else ln = nv; if (rc == RC_BREAK) { // assign remaining values to list unchanged if (l_tlist) while (++i < l_tlist->size()) reinterpret_cast<QoreListNode*>(*ln)->push(l_tlist->get_referenced_entry(i)); rc = 0; break; } if (rc == RC_RETURN) break; else if (rc == RC_CONTINUE) rc = 0; i++; // break out of loop if appropriate if (!l_tlist || i == l_tlist->size()) break; } // write the value back to the lvalue LValueHelper val(**vr, xsink); if (!val) return 0; if (val.assign(ln.release())) return 0; return rc; }
int main() { //Stel onderstaande poorten in op Output en laad allemaal enen in DDRA=0xFF; DDRB=0xFF; DDRC=0xFF; PORTA=0xFF; PORTB=0xFF; PORTC=0xFF; //Stel de timer in die een interrupt genereert bij en overflow TCCR0=0x05; TIMSK=0x01; //Stel odnerstaande poorten in op Input en laad allemaal enen in DDRE=0x00; PINE=0xFF; serial.init(); // Aanmaken van de verschillende autolichtobjecten AutoLicht azl(0xFE, 0xFD, 0xFB, ADRESPORTB); AutoLicht azr(0xF7, 0xEF, 0xDF, ADRESPORTB); AutoLicht ahl(0xFE, 0xFD, 0xFB, ADRESPORTC); AutoLicht ahr(0xF7, 0xEF, 0xDF, ADRESPORTC); // Aanmaken van de verschillende voetgangerlichtobjecten VoetgangerLicht vhr(0xFE, 0xFD, ADRESPORTA); VoetgangerLicht vz(0xBF, 0x7F, ADRESPORTB); VoetgangerLicht vhl(0xBF, 0x7F, ADRESPORTC); List<VoetgangerLicht*> l1, l2, l3; List<Scenario*> s; //Lijst l1 vullen l1.push_back(&azl); l1.push_back(&azr); //Lijst l2 vullen l2.push_back(&ahl); l2.push_back(&ahr); //Lijst l3 vullen l3.push_back(&vhr); l3.push_back(&vz); l3.push_back(&vhl); //Scenario's definieren Scenario s1(&l1, &variabelebeheerder); Scenario s2(&l2, &variabelebeheerder); Scenario s3(&l3, &variabelebeheerder); s.push_back(&s1); s.push_back(&s2); s.push_back(&s3); variabelebeheerder.zetAantalScenarios(3); //Scenario's toekennen aan sensoren svz.kenScenarioToe(&s3); svhr.kenScenarioToe(&s3); svhl.kenScenarioToe(&s3); sahr.kenScenarioToe(&s2); sahl.kenScenarioToe(&s2); sazl.kenScenarioToe(&s1); sazr.kenScenarioToe(&s1); VerkeersRegelaar vr(&s, &wachtrijbeheerder, &variabelebeheerder); sei(); //Zet interrupts aan while(1) { vr.kiesFunctie(); } }
//用了彭老师书上介绍的求交方法,但是transform之后就有问题 bool Triangle::intersect(const Ray &r, Hit &h, float tmin) { Matrix A; A.SetToIdentity(); A.Set(0,0,a.x()-b.x()); A.Set(1,0,a.x()-c.x()); A.Set(2,0,r.getDirection().x()); A.Set(0,1,a.y()-b.y()); A.Set(1,1,a.y()-c.y()); A.Set(2,1,r.getDirection().y()); A.Set(0,2,a.z()-b.z()); A.Set(1,2,a.z()-c.z()); A.Set(2,2,r.getDirection().z()); Vec4f vr(a.x()-r.getOrigin().x(),a.y()-r.getOrigin().y(),a.z()-r.getOrigin().z(),1); if(fabs(r.getDirection().Dot3(normal))>0.0f) { A.Inverse(); A.Transform(vr); if((vr.x()+vr.y())<=1 && vr.x()>=0 && vr.y()>=0 && vr.z()>tmin && vr.z()<h.getT()) { h.set(vr.z(),material,normal,r); return 1; } } return 0; //为什么当使用transform之后,这里的求交函数就不能用了? 用没有加速的程序检测了一下,也无法求交,应该是这里的求交写错掉了 //Vec3f origin = r.getOrigin(); //Vec3f direct = r.getDirection(); //float isParallel = normal.Dot3(direct); //Vec3f tempbeta0; //Vec3f tempbeta1; //Vec3f tempbeta2; //float beta0; //float beta1; //float beta2; //if(fabs(isParallel)>0.0f) //{ // float dist = -(normal.Dot3(origin)+d)/isParallel; // Vec3f q = origin + direct*dist; // Vec3f::Cross3(tempbeta0,(c-b),(q-b)); // Vec3f::Cross3(tempbeta1,(a-c),(q-c)); // Vec3f::Cross3(tempbeta2,(b-a),(q-a)); // if(i0 == 0) // { // beta0 = tempbeta0.x()/normal.x(); // beta1 = tempbeta1.x()/normal.x(); // beta2 = tempbeta2.x()/normal.x(); // } // else if(i0 == 1) // { // beta0 = tempbeta0.y()/normal.y(); // beta1 = tempbeta1.y()/normal.y(); // beta2 = tempbeta2.y()/normal.y(); // } // else // { // beta0 = tempbeta0.z()/normal.z(); // beta1 = tempbeta1.z()/normal.z(); // beta2 = tempbeta2.z()/normal.z(); // } // if(beta0>=0 && beta0<=1 && beta1>=0 && beta1<=1 && beta2>=0 && beta2<=1) // { // if(dist > tmin && dist < h.getT()) // { // h.set(dist,material,normal,r); // return true; // } // } //} //return false; }
PView *GMSH_EigenvectorsPlugin::execute(PView *v) { int scale = (int)EigenvectorsOptions_Number[0].def; int iView = (int)EigenvectorsOptions_Number[1].def; PView *v1 = getView(iView, v); if(!v1) return v; PViewData *data1 = getPossiblyAdaptiveData(v1); if(data1->hasMultipleMeshes()){ Msg::Error("Eigenvectors plugin cannot be run on multi-mesh views"); return v; } PView *min = new PView(); PView *mid = new PView(); PView *max = new PView(); PViewDataList *dmin = getDataList(min); PViewDataList *dmid = getDataList(mid); PViewDataList *dmax = getDataList(max); int nbcomplex = 0; fullMatrix<double> mat(3, 3), vl(3, 3), vr(3, 3); fullVector<double> dr(3), di(3); for(int ent = 0; ent < data1->getNumEntities(0); ent++){ for(int ele = 0; ele < data1->getNumElements(0, ent); ele++){ if(data1->skipElement(0, ent, ele)) continue; int numComp = data1->getNumComponents(0, ent, ele); if(numComp != 9) continue; int type = data1->getType(0, ent, ele); int numNodes = data1->getNumNodes(0, ent, ele); std::vector<double> *outmin = dmin->incrementList(3, type, numNodes); std::vector<double> *outmid = dmid->incrementList(3, type, numNodes); std::vector<double> *outmax = dmax->incrementList(3, type, numNodes); if(!outmin || !outmid || !outmax) continue; double xyz[3][8]; for(int nod = 0; nod < numNodes; nod++) data1->getNode(0, ent, ele, nod, xyz[0][nod], xyz[1][nod], xyz[2][nod]); for(int i = 0; i < 3; i++){ for(int nod = 0; nod < numNodes; nod++){ outmin->push_back(xyz[i][nod]); outmid->push_back(xyz[i][nod]); outmax->push_back(xyz[i][nod]); } } for(int step = 0; step < data1->getNumTimeSteps(); step++){ for(int nod = 0; nod < numNodes; nod++){ for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) data1->getValue(step, ent, ele, nod, 3 * i + j, mat(i, j)); if(mat.eig(dr, di, vl, vr, true)){ if(!scale) dr(0) = dr(1) = dr(2) = 1.; for(int i = 0; i < 3; i++){ double res; res = dr(0) * vr(i, 0); outmin->push_back(res); res = dr(1) * vr(i, 1); outmid->push_back(res); res = dr(2) * vr(i, 2); outmax->push_back(res); } if(di(0) || di(1) || di(2)) nbcomplex++; } else{ Msg::Error("Could not compute eigenvalues/vectors"); } } } } } if(nbcomplex) Msg::Error("%d tensors have complex eigenvalues", nbcomplex); for(int i = 0; i < data1->getNumTimeSteps(); i++){ double time = data1->getTime(i); dmin->Time.push_back(time); dmid->Time.push_back(time); dmax->Time.push_back(time); } dmin->setName(data1->getName() + "_MinEigenvectors"); dmin->setFileName(data1->getName() + "_MinEigenvectors.pos"); dmin->finalize(); dmid->setName(data1->getName() + "_MidEigenvectors"); dmid->setFileName(data1->getName() + "_MidEigenvectors.pos"); dmid->finalize(); dmax->setName(data1->getName() + "_MaxEigenvectors"); dmax->setFileName(data1->getName() + "_MaxEigenvectors.pos"); dmax->finalize(); return 0; }
//--------------------------------------------------------- void NDG2D::MakeCylinder2D ( const IMat& faces, double ra, double xo, double yo ) //--------------------------------------------------------- { // Function: MakeCylinder2D(faces, ra, xo, yo) // Purpose: Use Gordon-Hall blending with an isoparametric // map to modify a list of faces so they conform // to a cylinder of radius r centered at (xo,yo) int NCurveFaces = faces.num_rows(); IVec vflag(VX.size()); IMat VFlag(EToV.num_rows(),EToV.num_cols()); int n=0,k=0,f=0,v1=0,v2=0; double theta1=0.0,theta2=0.0,x1=0.0,x2=0.0,y1=0.0,y2=0.0; double newx1=0.0,newx2=0.0,newy1=0.0,newy2=0.0; DVec vr, fr, theta, fdx,fdy, vdx, vdy, blend,numer,denom; IVec va,vb,vc, ks, Fm_f, ids; DMat Vface, Vvol; for (n=1; n<=NCurveFaces; ++n) { // move vertices of faces to be curved onto circle k = faces(n,1); f = faces(n,2); v1 = EToV(k, f); v2 = EToV(k, umMOD(f,Nfaces)+1); theta1 = atan2(VY(v1),VX(v1)); theta2 = atan2(VY(v2),VX(v2)); newx1 = xo + ra*cos(theta1); newy1 = yo + ra*sin(theta1); newx2 = xo + ra*cos(theta2); newy2 = yo + ra*sin(theta2); // update mesh vertex locations VX(v1) = newx1; VX(v2) = newx2; VY(v1) = newy1; VY(v2) = newy2; // store modified vertex numbers vflag(v1) = 1; vflag(v2) = 1; } // map modified vertex flag to each element //vflag = vflag(EToV); VFlag.resize(EToV); VFlag.set_map(EToV, vflag); // (map, values) // locate elements with at least one modified vertex //ks = find(sum(vflag,2)>0); ks = find(VFlag.row_sums(), '>', 0); // build coordinates of all the corrected nodes IMat VA=EToV(ks,1), VB=EToV(ks,2), VC=EToV(ks,3); // FIXME: loading 2D mapped data into 1D vectors int Nr=VA.num_rows(); va.copy(Nr,VA.data()); vb.copy(Nr,VB.data()); vc.copy(Nr,VC.data()); // Note: outer products of (Vector,MappedRegion1D) x(All,ks) = 0.5*(-(r+s)*VX(va)+(1.0+r)*VX(vb)+(1.0+s)*VX(vc)); y(All,ks) = 0.5*(-(r+s)*VY(va)+(1.0+r)*VY(vb)+(1.0+s)*VY(vc)); // deform specified faces for (n=1; n<=NCurveFaces; ++n) { k = faces(n,1); f = faces(n,2); // find vertex locations for this face and tangential coordinate if (f==1) { v1=EToV(k,1); v2=EToV(k,2); vr=r; } else if (f==2) { v1=EToV(k,2); v2=EToV(k,3); vr=s; } else if (f==3) { v1=EToV(k,1); v2=EToV(k,3); vr=s; } fr = vr(Fmask(All,f)); x1 = VX(v1); y1 = VY(v1); x2 = VX(v2); y2 = VY(v2); // move vertices at end points of this face to the cylinder theta1 = atan2(y1-yo, x1-xo); theta2 = atan2(y2-yo, x2-xo); // check to make sure they are in the same quadrant if ((theta2 > 0.0) && (theta1 < 0.0)) { theta1 += 2*pi; } if ((theta1 > 0.0) && (theta2 < 0.0)) { theta2 += 2*pi; } // distribute N+1 nodes by arc-length along edge theta = 0.5*theta1*(1.0-fr) + 0.5*theta2*(1.0+fr); // evaluate deformation of coordinates fdx = xo + ra*apply(cos,theta) - x(Fmask(All,f),k); fdy = yo + ra*apply(sin,theta) - y(Fmask(All,f),k); // build 1D Vandermonde matrix for face nodes and volume nodes Vface = Vandermonde1D(N, fr); Vvol = Vandermonde1D(N, vr); // compute unblended volume deformations vdx = Vvol * (Vface|fdx); vdy = Vvol * (Vface|fdy); // blend deformation and increment node coordinates ids = find(abs(1.0-vr), '>', 1e-7); // warp and blend denom = 1.0-vr(ids); if (1==f) { numer = -(r(ids)+s(ids)); } else if (2==f) { numer = (r(ids)+1.0 ); } else if (3==f) { numer = -(r(ids)+s(ids)); } blend = numer.dd(denom); x(ids,k) += (blend.dm(vdx(ids))); y(ids,k) += (blend.dm(vdy(ids))); } // repair other coordinate dependent information Fx = x(Fmask, All); Fy = y(Fmask, All); ::GeometricFactors2D(x,y,Dr,Ds, rx,sx,ry,sy,J); Normals2D(); Fscale = sJ.dd(J(Fmask,All)); }
Float evaluate_sequences(vector<vector<int> > &goldS,vector<vector<int> > &predicted,vector<string> &LIS ,int num_labels,vector<verbose_res> &VR){ int numtag,numctag,numbtag; numtag=numctag=numbtag=0; int num_class = ( num_labels / 2 ) + 1; vector<int> ccount(num_class,0),pcount(num_class,0),ncorrect(num_class,0), nleft(num_class,0),nright(num_class,0), nbcorrect(num_class,0),nbleft(num_class,0),nbright(num_class,0); int match,bmatch; match=bmatch=0; int num_seq = goldS.size(); for (int i = 0; i < num_seq ; ++i){ // For each sequence unsigned int N = goldS[i].size(); if ( N != predicted[i].size() ) { cerr << "Unmatching length of labels for sentence" << i << "\n"; abort(); } for ( unsigned int n = 0 ; n < N ; ++n, ++numtag ) { int clabel = goldS[i][n]; int cclass = class_type( clabel ); int cbraket = braket_type( n, goldS[i] ); if ( cbraket == SBrac || cbraket == BBrac ) { ccount[cclass]++; } int plabel = predicted[i][n]; int pclass = class_type( plabel ); int pbraket = braket_type( n, predicted[i] ); if ( pbraket == SBrac || pbraket == BBrac ) { pcount[pclass]++; } if ( cbraket == pbraket ) numbtag++; if ( clabel == plabel && cbraket == pbraket ) numctag++; if ( pbraket == SBrac && cbraket == SBrac ) { nbcorrect[pclass]++; nbleft[pclass]++; nbright[pclass]++; if( pclass == cclass ) { ncorrect[pclass]++; nleft[pclass]++; nright[pclass]++; } } else if ( pbraket == SBrac && cbraket == EBrac ) { nbright[pclass]++; if( pclass == cclass ) { nright[pclass]++; } } else if ( pbraket == SBrac && cbraket == BBrac ) { nbleft[pclass]++; if( pclass == cclass ) { nleft[pclass]++; } } else if ( pbraket == BBrac && cbraket == SBrac ) { nbleft[pclass]++; if( pclass == cclass ) { nleft[pclass]++; } } else if ( pbraket == BBrac && cbraket == BBrac ) { nbleft[pclass]++; bmatch=1; if( pclass == cclass ) { nleft[pclass]++; match=1;} } if ( pbraket != cbraket || pbraket == none ) bmatch = 0; if ( cclass != pclass || !bmatch ) match = 0; if ( pbraket == EBrac && cbraket == SBrac ) { nbright[pclass]++; if( pclass == cclass ) { nright[pclass]++; } } if ( pbraket == EBrac && cbraket == EBrac ) { if( bmatch ) nbcorrect[pclass]++; nbright[pclass]++; if( pclass == cclass ) { if ( match && ncorrect[pclass] <= pcount[pclass]) ncorrect[pclass]++; nright[pclass]++; } } } } Float score; int numans = getsum(pcount), numref = getsum(ccount); verbose_res vr("ALL",int(numref),int(numans)); if ( !numref ) cerr << "\n\nNo names in reference!\n"; if ( !numans ) cerr << "\n\nNo names in answers!\n"; Float ret_val = compute_score(getsum(ncorrect),numans,numref,"FULLY CORRECT answer",vr); VR.push_back(vr); if (num_class > 2) for( unsigned int cl = 1 ; cl < pcount.size() ; ++cl ) { string cl_str = LIS[reverse_class_type(cl)]; verbose_res vr_cl(string(cl_str,2,int(cl_str.size()-2)),ccount[cl],pcount[cl]); score = compute_score(ncorrect[cl],pcount[cl],ccount[cl],"FULLY CORRECT answer",vr_cl); VR.push_back(vr_cl); } if (ret_val>1.0) ret_val=1.0; return ret_val; }
void BackendScene::generateVPL( size_t vplNum, const char* vplFile,size_t vpldepth ) { this->vpls.clear(); SET_CLAMPING_DISTANCE( 0.05 * sceneradius ); //------------------------- READ FILE IF IT DOES EXIST-------------------------------------- if( strcmp(vplFile,"")){ FILE *ptr; ptr = fopen(vplFile,"rb"); if (ptr) { size_t siz; fread(&siz,sizeof(size_t),1,ptr); vpls.resize(siz); for (size_t i = 0 ; i<siz; ++i) vpls[i].read(ptr); fclose(ptr); std::cout << "Vpl file read. Total # of vpls:"<< vpls.size()<<std::endl; return; } else std::cout << "Unable to read vpl file."<< std::endl; } //------------------------- OTHERWISE GENERATE VPLS-------------------------------------- Random rnd(RND_SEED); // Place VPLs that substitute the original lights (direct VPLs) std::vector<Ref<Light> >::iterator it = allLights.begin(); for ( ; it !=allLights.end(); ++it) { // Replace TriangleLight if( (*it).dynamicCast<TriangleLight>() ) { Ref<TriangleLight> tr = (*it).dynamicCast<TriangleLight>(); Color I = tr->L * length(cross(tr->e1,tr->e2)) * 0.5; int triangleSamples = 1024; // HACK to avoid too many VPLs for many quads... if (allLights.size() > 2000) triangleSamples = 100; for (int i=0 ; i < triangleSamples ; ++i) { Vector3f pos = uniformSampleTriangle(rnd.getFloat(),rnd.getFloat(),tr->v0,tr->v1,tr->v2); this->vpls.push_back(vplVPL(pos, -tr->Ng, I * rcp((float)triangleSamples) ) ); } } // Replace SpotLight else if ((*it).dynamicCast<SpotLight>()) { Ref<SpotLight> sl = (*it).dynamicCast<SpotLight>(); if ( sl->cosAngleMax >= 0.05 || sl->cosAngleMin <= 0.95 ) throw std::runtime_error("Not supporting spotlights with other than 90 degree falloff for VPL generation."); this->vpls.push_back(vplVPL(sl->P,sl->_D,sl->I)); } // Replace environment map else if ((*it).dynamicCast<HDRILight>()) { Ref<HDRILight> hd = (*it).dynamicCast<HDRILight>(); int envmapSamples = 32768; float dirlightdistance = DIR_LIGHT_DISTANCE; for (int i=0 ; i < envmapSamples ; ++i) { Vector3f pos(uniformSampleSphere(rnd.getFloat(),rnd.getFloat())); Vector3f dir = -pos; pos *= dirlightdistance; pos += scenecenter; // CHECK below line later it is not completely precise Color I = hd->Le(-dir) * four_pi * rcp((float)envmapSamples) * dirlightdistance * dirlightdistance; this->vpls.push_back(vplVPL(pos, -dir , I )); } } else if ((*it).dynamicCast<DirectionalLight>()) { Ref<DirectionalLight> sl = (*it).dynamicCast<DirectionalLight>(); float distance = 100000; this->vpls.push_back(vplVPL(sl->_wo*distance,sl->_wo,sl->E*distance*distance)); } else throw std::runtime_error("Not supported light type for VPL generation."); } // Place VPLs (indirect VPLs) size_t direct = this->vpls.size(); size_t orig = this->allLights.size(); if (vpldepth <=1) return; while (this->vpls.size() < (vplNum+direct)) { // Sample orig lights for photons Ref<Light> vp = this->allLights[rnd.getInt(orig)]; Vector3f pos; Sample3f dir; Vec2f vr(rnd.getFloat(),rnd.getFloat()); Vec2f vs(rnd.getFloat(),rnd.getFloat()); Color I = vp->samplePhoton(dir,pos,vr,vs,sceneradius,scenecenter); if (dir.pdf==0.0f) continue; I *= (float) orig * rcp(dir.pdf); // Generate a path for the photon and add VPLs int maxdepth = int(vpldepth) - 1; // -1 because 1 for pt means only direct light while ( maxdepth-- && (I != zero ) ) { Ray ray (pos,dir,32*std::numeric_limits<float>::epsilon(), inf); DifferentialGeometry dg; rtcIntersect(this->scene,(RTCRay&)ray); this->postIntersect(ray,dg); if (!ray)//nothing is hit break; /*! face forward normals */ if (dot(dg.Ng, ray.dir) > 0) { dg.Ng = -dg.Ng; dg.Ns = -dg.Ns; } CompositedBRDF brdfs; if (dg.material) dg.material->shade(ray, Medium::Vacuum(), dg, brdfs); BRDFType diffuseBRDFTypes = (BRDFType)(DIFFUSE); Vec2f s = Vec2f(rnd.getFloat(),rnd.getFloat()); Color c = brdfs.sample(-ray.dir,dg, dir,diffuseBRDFTypes,s,rnd.getFloat(),diffuseBRDFTypes); if (c==zero || dir.pdf==0.0f) break; // the dot prod should not be zero since then c would be zero float dott = dot(dir,dg.Ns); if (dott==0.0f) break; Color contrib = I * c * rcp(dott) * rcp((float)vplNum) ; //if (std::isnan(contrib.r) || std::isnan(contrib.g) || std::isnan(contrib.b)) // break; this->vpls.push_back(vplVPL(dg.P,-dg.Ns,contrib)); Color contribScale = c * rcp(dir.pdf); float rrProb = min(1.0f, reduce_avg(contribScale)); if(rrProb == 0.0f)break; if (rnd.getFloat() > rrProb) break; I *= contribScale * rcp(rrProb); pos = dg.P; } } //------------------------------PERTURB VPLS WITH THE SAME POSITION----------------------------------------------------------- auto vplComp = [] (const vplVPL& vp1,const vplVPL& vp2) { return vp1.P < vp2.P; }; std::sort(this->vpls.begin(),this->vpls.end(),vplComp); std::vector<vplVPL>::iterator itt = this->vpls.begin(); while(itt != ( vpls.end() - 1 ) && itt != vpls.end()) { vplVPL& v1 = *itt, & v2 = *(itt+1); if(v1.P == v2.P) { v2.I += v1.I; itt = this->vpls.erase(itt); } else ++itt; } //------------------------------WRITE OUT VPLS INTO A FILE----------------------------------------------------------- // writing out the VPLs FILE *ptr; ptr = fopen(vplFile,"wb"); if (ptr) { size_t siz = this->vpls.size(); fwrite(&siz,sizeof(size_t),1,ptr); if (vpls.size()) for (size_t i = 0 ; i<siz; ++i) vpls[i].write(ptr); fclose(ptr); std::cout << "Vpl file written. Total # of vpls:"<< vpls.size()<<std::endl; } else std::cout << "Unable to write vpl file. Total # of vpls: "<<vpls.size() << std::endl; return; }
PView *GMSH_HarmonicToTimePlugin::execute(PView * v) { int rIndex = (int)HarmonicToTimeOptions_Number[0].def; int iIndex = (int)HarmonicToTimeOptions_Number[1].def; int nSteps = (int)HarmonicToTimeOptions_Number[2].def; int iView = (int)HarmonicToTimeOptions_Number[3].def; PView *v1 = getView(iView, v); if(!v1) return v; PViewData *data1 = v1->getData(); if(data1->hasMultipleMeshes()){ Msg::Error("HarmonicToTime plugin cannot be applied to multi-mesh views"); return v1; } if(rIndex < 0 || rIndex >= data1->getNumTimeSteps() || iIndex < 0 || iIndex >= data1->getNumTimeSteps()){ Msg::Error("Wrong real or imaginary part index"); return v1; } if(nSteps <= 0){ Msg::Error("nSteps should be > 0"); return v1; } PView *v2 = new PView(); PViewDataList *data2 = getDataList(v2); for(int ent = 0; ent < data1->getNumEntities(0); ent++){ for(int ele = 0; ele < data1->getNumElements(0, ent); ele++){ if(data1->skipElement(0, ent, ele)) continue; int numNodes = data1->getNumNodes(0, ent, ele); int type = data1->getType(0, ent, ele); int numComp = data1->getNumComponents(0, ent, ele); std::vector<double> *out = data2->incrementList(numComp, type, numNodes); std::vector<double> x(numNodes), y(numNodes), z(numNodes); std::vector<double> vr(numNodes * numComp), vi(numNodes * numComp); for(int nod = 0; nod < numNodes; nod++){ data1->getNode(0, ent, ele, nod, x[nod], y[nod], z[nod]); for(int comp = 0; comp < numComp; comp++){ data1->getValue(rIndex, ent, ele, nod, comp, vr[numComp * nod + comp]); data1->getValue(iIndex, ent, ele, nod, comp, vi[numComp * nod + comp]); } } for(int nod = 0; nod < numNodes; nod++) out->push_back(x[nod]); for(int nod = 0; nod < numNodes; nod++) out->push_back(y[nod]); for(int nod = 0; nod < numNodes; nod++) out->push_back(z[nod]); for(int t = 0; t < nSteps; t++) { double p = 2. * M_PI * t / nSteps; for(int nod = 0; nod < numNodes; nod++) { for(int comp = 0; comp < numComp; comp++) { double val = vr[numComp * nod + comp] * cos(p) - vi[numComp * nod + comp] * sin(p); out->push_back(val); } } } } } for(int i = 0; i < nSteps; i++){ double p = 2. * M_PI * i / (double)nSteps; data2->Time.push_back(p); } data2->setName(data1->getName() + "_HarmonicToTime"); data2->setFileName(data1->getName() + "_HarmonicToTime.pos"); data2->finalize(); return v2; }