Example #1
0
static void
set_progress_val(int i, int n, const char *name)
{
  double frac;
  char msgbuf[1024];

  if (i == 0) {
    set_progress(0, "", 0);
  }

  frac = 1.0 * i / (n + 1);
  snprintf(msgbuf, sizeof(msgbuf), _("drawing %s (%.1f%%)"), name, frac * 100);
  set_progress(1, msgbuf, frac);
}
Example #2
0
void LocalZipTask::update_state(const QString& msg)
{
    set_msg(msg);
    const int progress = (0 == _total_files ? 100 : _compressed_files * 100 / _total_files);
    set_progress(progress > 100 ? 100 : progress);
    state_changed();
}
Example #3
0
void dialog_label::set_value(const std::string& key, const variant& v)
{
	if(key == "progress") {
		set_progress(v.as_int());
	}
	label::set_value(key, v);
}
Example #4
0
void ts::scene::Loading_sequence::poll()
{
    if (stage_loader_)
    {
        set_progress(stage_loader_->progress());
        set_max_progress(stage_loader_->max_progress());
    }

    else if (script_loader_.loading_interface())
    {
        set_progress(script_loader_.loading_interface()->progress());
        set_max_progress(script_loader_.loading_interface()->max_progress());
    }

    scene_loader_.poll();
    audio_loader_.poll();
    script_loader_.poll();
}
Example #5
0
    bool start()
    {
        /*update_display_message("Connecting to patch server...");

        thread = boost::thread(patch_thread);*/

		update_display_message("Welcome to VTank. Click \"PLAY\" to begin.");
		set_progress(100);
		set_done(true);

        return true;
    }
static void
update_text (study_screen_info *info)
{
  set_progress ((double)info->current / (double)get_item_count ());

  char *print_me = malloc (sizeof (char) * 25);
  char *wordish = number_to_wordish(info->current);
  char **items;

  items = get_items ();


  sprintf(print_me, "%s%s%s", "The ", wordish, " item is:");
  gtk_label_set_text (GTK_LABEL (info->instruction_label), print_me);

  gtk_label_set_text (GTK_LABEL (info->text), items[info->current-1]);
  free (print_me);
  free (wordish);
}
static void
on_previous (GtkButton *entry,
             gpointer  user_data)
{
  if(info->current == get_item_count ())
    gtk_button_set_label(GTK_BUTTON (info->next_button), "Next");
  info->current--;
  if(info->current < 1)
  {
    info->current = 0;
    gtk_label_set_text (GTK_LABEL (info->instruction_label), "click next to begin");
    gtk_label_set_text (GTK_LABEL (info->text), "");
    set_progress (0);
  }
  else
  {
    update_text(info);
  }
}
Example #8
0
static enum FitError 
fituser(struct objlist *obj,struct fitlocal *fitlocal, const char *func,
	int deriv,double converge,double *data,int num,int disp,
	int weight,double *wdata)
/*
  return
         FitError_Interrupt
         FitError_Convergence
         FitError_Range
         FitError_syntax
         FitError_Equation
         FitError_Matrix
         FitError_Small
         FitError_Success
         FitError_Fatal
*/
{
  int ecode;
  int *needdata;
  int tbl[10],dim,n,count,err,err2,err3;
  double yy,y,y1,y2,y3,sy,spx,spy,dxx,dxxc,xx,derror,correlation;
  double b[10],x2[10],parerr[10];
  MathValue par[10], par2[10], var;
  MathEquationParametar *prm;
  matrix m;
  int i,j,k;
  char buf[1024];
  double wt,sum;
/*
  matrix m2;
  int count2;
  double sum2;
  double lambda,s0;
*/
  if (num<1) return FitError_Small;
  if (fitlocal->codef==NULL) return FitError_Equation;

  prm = math_equation_get_parameter(fitlocal->codef, 0, NULL);
  dim = prm->id_num;
  needdata = prm->id;
  if (deriv) {
    for (i = 0; i < dim; i++) {
      if (fitlocal->codedf[needdata[i]] == NULL) return FitError_Equation;
    }
  }
  for (i = 0; i < dim; i++) tbl[i] = needdata[i];
  for (i = 0; i < 10; i++) {
    par[i].type = MATH_VALUE_NORMAL;
    par[i].val = fitlocal->coe[i];
  }
  ecode=FitError_Success;
/*
  err2=FALSE;
  n=0;
  sum=0;
  yy=0;
  lambda=0.001;
  for (k=0;k<num;k++) {
    if (weight) wt=wdata[k];
    else wt=1;
    sum+=wt;
    spx=data[k*2];
    spy=data[k*2+1];
    err=FALSE;
    rcode=calculate(fitlocal->codef,1,spx,MATH_VALUE_NORMAL,0,0,0,0,
                    0,0,0,0,0,0,0,0,0,0,0,0,
                    par,parstat,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                    NULL,NULL,NULL,0,NULL,NULL,NULL,0,&y1);
    if (rcode!=MATH_VALUE_NORMAL) err=TRUE;
    if (!err) {
      if (fabs(yy)>1e100) return FitError_Range;
      y2=spy-y1;
      if ((fabs(y2)>1e50) || (fabs(spy)>1e50)) err=TRUE;
    }
    if (!err) {
      n++;
      yy+=wt*y2*y2;
    } else err2=TRUE;
  }
  if (err2) error(obj,ERRMATH);
  if (n<1) {
    ecode=FitError_Small;
    goto errexit;
  }
  s0=yy/sum;
*/

  count=0;
  err3=FALSE;
  do {
    yy=0;
    y=0;
    y3=0;
    for (i=0;i<dim;i++) {
      b[i]=0;
      for (j=0;j<dim;j++) m[j][i]=0;
    }
    err2=FALSE;
    n=0;
    sum=0;
    for (k=0;k<num;k++) {
      if (weight) wt=wdata[k];
      else wt=1;
      sum+=wt;
      spx=data[k*2];
      spy=data[k*2+1];
      err=FALSE;
      var.val = spx;
      var.type = MATH_VALUE_NORMAL;
      math_equation_set_parameter_data(fitlocal->codef, 0, par);
      math_equation_set_var(fitlocal->codef, 0, &var);
      math_equation_calculate(fitlocal->codef, &var);
      y1 = var.val;
      if (var.type!=MATH_VALUE_NORMAL) err=TRUE;
      if (deriv) {
        for (j=0;j<dim;j++) {
	  var.val = spx;
	  var.type = MATH_VALUE_NORMAL;
	  math_equation_set_parameter_data(fitlocal->codedf[tbl[j]], 0, par);
	  math_equation_set_var(fitlocal->codedf[tbl[j]], 0, &var);
	  math_equation_calculate(fitlocal->codedf[tbl[j]], &var);
	  x2[j] = var.val;
	  if (var.type!=MATH_VALUE_NORMAL) err=TRUE;
        }
      } else {
        for (j=0;j<dim;j++) {
          for (i=0;i<10;i++) par2[i]=par[i];
          dxx = par2[j].val * converge * 1e-6;
          if (dxx == 0) dxx = 1e-6;
          par2[tbl[j]].val += dxx;
	  var.val = spx;
	  var.type = MATH_VALUE_NORMAL;
	  math_equation_set_parameter_data(fitlocal->codef, 0, par2);
	  math_equation_set_var(fitlocal->codef, 0, &var);
	  math_equation_calculate(fitlocal->codef, &var);
	  x2[j] = var.val;
	  if (var.type!=MATH_VALUE_NORMAL) err=TRUE;
          x2[j]=(x2[j]-y1)/dxx;
        }
      }
      if (!err) {
        if ((fabs(yy)>1e100) || (fabs(y3)>1e100)) return FitError_Range;
        y2=spy-y1;
        if ((fabs(y2)>1e50) || (fabs(spy)>1e50)) err=TRUE;
      }
      if (!err) {
        n++;
        yy+=wt*y2*y2;
        y+=wt*spy;
        y3+=wt*spy*spy;
        for (j=0;j<dim;j++) b[j]+=wt*x2[j]*y2;
        for (j=0;j<dim;j++)
          for (i=0;i<dim;i++) m[j][i]=m[j][i]+wt*x2[j]*x2[i];
      } else err2=TRUE;
    }
    if (!err3 && err2) {
      error(obj,ERRMATH);
      err3=TRUE;
    }
    if (n<1) {
      ecode=FitError_Small;
      goto errexit;
    }

    count++;

    derror=fabs(yy)/sum;
    sy=y3/sum-(y/sum)*(y/sum);
    if ((sy==0) || (1-derror/sy<0)) correlation=-1;
    else correlation=sqrt(1-derror/sy);
    if (correlation>1) correlation=-1;
    derror=sqrt(derror);
    /*
    if (disp) {
      i=0;
      i += sprintf(buf + i, "fit:^%d\n", fitlocal->oid);
      i+=sprintf(buf+i,"Eq: User defined\n\n");
      for (j=0;j<dim;j++)
        i+=sprintf(buf+i,"       %%0%d = %+.7e\n",tbl[j],par[tbl[j]]);
      i+=sprintf(buf+i,"\n");
      i+=sprintf(buf+i,"    points = %d\n",n);
      if (count==1) i+=sprintf(buf+i,"     delta = \n");
      else i+=sprintf(buf+i,"     delta = %+.7e\n",dxxc);
      i+=sprintf(buf+i,"    <DY^2> = %+.7e\n",derror);
      if (correlation>=0)
        i+=sprintf(buf+i,"|r| or |R| = %+.7e\n",correlation);
      else
        i+=sprintf(buf+i,"|r| or |R| = -------------\n");
      i+=sprintf(buf+i," Iteration = %d\n",count);
      ndisplaydialog(buf);
    }
    */
    if (count & 0x100) {
      sprintf(buf,"fit:^%d Iteration = %d delta = %g", fitlocal->oid, count, dxxc);
      set_progress(0, buf, -1);
    }
    if (ninterrupt()) {
      ecode=FitError_Interrupt;
      goto errexit;
    }

/*
    count2=0;
    sum2=sum;
    while (TRUE) {
      count2++;
      sprintf(buf,"Iteration = %d:%d",count,count2);
      ndisplaystatus(buf);
      for (j=0;j<dim;j++)
        for (i=0;i<dim;i++) m2[j][i]=m[j][i];
      for (i=0;i<dim;i++) m2[i][i]=m[i][i]+sum2*lambda;
      if (matsolv(dim,m2,b,parerr)) goto repeat;
      for (i=0;i<dim;i++) par2[tbl[i]]=par[tbl[i]]+parerr[i];
      n=0;
      err2=FALSE;
      sum=0;
      yy=0;
      for (k=0;k<num;k++) {
        if (weight) wt=wdata[k];
        else wt=1;
        sum+=wt;
        spx=data[k*2];
        spy=data[k*2+1];
        err=FALSE;
        rcode=calculate(fitlocal->codef,1,spx,MATH_VALUE_NORMAL,0,0,0,0,
                        0,0,0,0,0,0,0,0,0,0,0,0,
                     par2,parstat,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                        NULL,NULL,NULL,0,NULL,NULL,NULL,0,&y1);
        if (rcode!=MATH_VALUE_NORMAL) err=TRUE;
        if (!err) {
          if (fabs(yy)>1e100) goto repeat;
          y2=spy-y1;
          if ((fabs(y2)>1e50) || (fabs(spy)>1e50)) err=TRUE;
        }
        if (!err) {
          n++;
          yy+=wt*y2*y2;
        }
      }
      if (n<1) goto repeat;
      if (yy/sum<=s0) {
        s0=yy/sum;
        break;
      }
repeat:
      lambda*=10;
      if (lambda>1e100) return FitError_Convergence;
    }

    lambda/=10;
*/
    if (matsolv(dim,m,b,parerr)) return FitError_Matrix;

    dxxc=0;
    xx=0;
    for (i=0;i<dim;i++) {
      dxxc += parerr[i] * parerr[i];
      par[tbl[i]].val += parerr[i];
      xx += par[tbl[i]].val * par[tbl[i]].val;
    }
    dxxc=sqrt(dxxc);
    xx=sqrt(xx);


  } while ((dxxc>xx*converge/100) && ((xx>1e-6) || (dxxc>1e-6*converge/100)));

  if (disp && show_user_result(fitlocal, func, dim, tbl, par, n, dxxc, derror, correlation)) {;
    return FitError_Fatal;
  }

errexit:
  if ((ecode==FitError_Success) || (ecode==FitError_Range)) {
    for (i = 0; i < 10; i++) {
      fitlocal->coe[i] = par[i].val;
    }
    fitlocal->dim=dim;
    fitlocal->derror=derror;
    fitlocal->correlation=correlation;
    fitlocal->num=n;
    if (show_user_equation(fitlocal, func, par, disp)) {
      ecode = FitError_Fatal;
    }
  }
  return ecode;
}
Example #9
0
int terrain_filter(
    float *data,        // input/output: array of data to process (row-major order)
    double detail,      // input: "detail" exponent to be applied
    int    nrows,       // input: number of rows    in data array
    int    ncols,       // input: number of columns in data array
    double xdim,        // input: spacing between pixel columns (in degrees or meters)
    double ydim,        // input: spacing between pixel rows    (in degrees or meters)
    enum Terrain_Coord_Type
    coord_type,  // input: coordinate type for xdim & ydim (degrees or meters)
    double center_lat,  // input: latitude in degrees at center of data array
    //        (ignored if coord_type == TERRAIN_METERS)
    const struct Terrain_Progress_Callback
    *progress     // optional callback functor for status; NULL for none
//  enum Terrain_Reg registration   // feature not yet implemented
)
// Computes operator (-Laplacian)^(detail/2) applied to data array.
// Returns 0 on success, nonzero if an error occurred (see enum Terrain_Filter_Errors).
// Mean of data array is always (approximately) zero on output.
// On input, vertical units (data array values) should be in meters.
{
    enum Terrain_Reg registration = TERRAIN_REG_CELL;

    int num_threads = 1;    // number of threads used to parallelize the three DCT loops

    // approximate relative amount of time spent in each step
    // (actual times vary with data array size, memory size, and DCT algorithms chosen):
    const float step_times[6] =
    { 0.5, 2.0/num_threads, 1.0, 4.0/num_threads, 1.0, 2.0/num_threads };

    const int total_steps = sizeof( step_times ) / sizeof( *step_times );

    struct Terrain_Progress_Info
    progress_info = init_progress( progress, step_times, total_steps );

    struct Transpose_Progress_Callback
        sub_progress = { relay_progress, &progress_info };

    const double steepness = 2.0;

    int error;

    int type_fwd, type_bwd;

    int i, j;
    float *ptr;

    float data_min, data_max;

    double normalizer;

    double xres,   yres;
    double xscale, yscale;
    double xsize,  ysize;

    struct Terrain_Operator_Info info;

    // Determine pixel dimensions:

    if (coord_type == TERRAIN_DEGREES) {
        geographic_scale( center_lat, &xsize, &ysize );

        // convert degrees to meters (approximately)
        xres = xdim * xsize;
        yres = ydim * ysize;
    } else {
        xres = xdim;
        yres = ydim;
    }

    xscale = fabs( 1.0 / xres );
    yscale = fabs( 1.0 / yres );

    switch (registration) {
    case TERRAIN_REG_GRID:
        type_fwd = 1;
        type_bwd = 1;
        break;
    case TERRAIN_REG_CELL:
        type_fwd = 2;
        type_bwd = 3;
        break;
    default:
        return TERRAIN_FILTER_INVALID_PARAM;
    }

    if (progress && report_progress( &progress_info )) {
        return TERRAIN_FILTER_CANCELED;
    }

    data_min = data[0];
    data_max = data[0];

    for (i=0, ptr=data; i<nrows; ++i, ptr+=ncols) {
        //float *ptr = data + (LONG)i * (LONG)ncols;
        for (j=0; j<ncols; ++j) {
            if (ptr[j] < data_min) {
                data_min = ptr[j];
            } else if (ptr[j] > data_max) {
                data_max = ptr[j];
            }
        }
    }

    normalizer  = pow( 2.0 / (data_max - data_min), 1.0 - detail );
    normalizer *= pow( steepness, -detail );

    for (i=0, ptr=data; i<nrows; ++i, ptr+=ncols) {
        //float *ptr = data + (LONG)i * (LONG)ncols;
        for (j=0; j<ncols; ++j) {
            ptr[j] *= normalizer;
        }
    }

    error = setup_operator( detail, ncols, nrows, xscale, yscale, registration, &info );
    if (error) {
        return error;
    }

    set_progress( &progress_info, 1 );

    if (progress && report_progress( &progress_info )) {
        return TERRAIN_FILTER_CANCELED;
    }

    // CONCURRENCY NOTE: The iterations of the loop below will be
    // independent and can be executed in parallel, if each thread has
    // its own dct_plan with separate calls to setup_dcts() and cleanup_dcts().
    {
        struct Dct_Plan dct_plan = setup_dcts( type_fwd, ncols );

        if (!dct_plan.dct_buffer) {
            return TERRAIN_FILTER_MALLOC_ERROR;
        }

        for (i=0; i<nrows-1; i+=2) {
            float *ptr = data + (LONG)i * (LONG)ncols;
            two_dcts( ptr, ncols, &dct_plan );
            if (progress && update_progress( &progress_info, i+2, nrows ))
            {
                return TERRAIN_FILTER_CANCELED;
            }
        }
        if (nrows & 1) {
            float *ptr = data + (LONG)(nrows - 1) * (LONG)ncols;
            single_dct( ptr, ncols, &dct_plan );
        }

        cleanup_dcts( &dct_plan );
    }

    set_progress( &progress_info, 2 );

    if (progress && report_progress( &progress_info )) {
        return TERRAIN_FILTER_CANCELED;
    }

    error = transpose_inplace( data, nrows, ncols, progress ? &sub_progress : NULL );
    if (error) {
        if (error > 0) {
            return TERRAIN_FILTER_MALLOC_ERROR;
        } else {
            return TERRAIN_FILTER_CANCELED;
        }
    }

    set_progress( &progress_info, 3 );

    if (progress && report_progress( &progress_info )) {
        return TERRAIN_FILTER_CANCELED;
    }

    // CONCURRENCY NOTE: The iterations of the loop below will be
    // independent and can be executed in parallel, if each thread has
    // its own fwd_plan and bwd_plan with separate calls to setup_dcts()
    // and cleanup_dcts().
    {
        struct Dct_Plan fwd_plan = setup_dcts( type_fwd, nrows );
        struct Dct_Plan bwd_plan = setup_dcts( type_bwd, nrows );

        if (!fwd_plan.dct_buffer || !bwd_plan.dct_buffer) {
            return TERRAIN_FILTER_MALLOC_ERROR;
        }

        for (i=0; i<ncols-1; i+=2) {
            float *ptr = data + (LONG)i * (LONG)nrows;

            two_dcts( ptr, nrows, &fwd_plan );
            apply_operator( data, i,   nrows, info );
            apply_operator( data, i+1, nrows, info );
            two_dcts( ptr, nrows, &bwd_plan );

            if (progress && update_progress( &progress_info, i+2, ncols ))
            {
                return TERRAIN_FILTER_CANCELED;
            }
        }

        if (ncols & 1) {
            float *ptr = data + (LONG)(ncols - 1) * (LONG)nrows;

            single_dct( ptr, nrows, &fwd_plan );
            apply_operator( data, ncols-1, nrows, info );
            single_dct( ptr, nrows, &bwd_plan );
        }

        cleanup_dcts( &bwd_plan );
        cleanup_dcts( &fwd_plan );
    }

    if (flt_isnan( data[0] )) {
        return TERRAIN_FILTER_NULL_VALUES;
    }

    set_progress( &progress_info, 4 );

    if (progress && report_progress( &progress_info )) {
        return TERRAIN_FILTER_CANCELED;
    }

    error = transpose_inplace( data, ncols, nrows, progress ? &sub_progress : NULL );
    if (error) {
        if (error > 0) {
            return TERRAIN_FILTER_MALLOC_ERROR;
        } else {
            return TERRAIN_FILTER_CANCELED;
        }
    }

    set_progress( &progress_info, 5 );

    if (progress && report_progress( &progress_info )) {
        return TERRAIN_FILTER_CANCELED;
    }

    // CONCURRENCY NOTE: The iterations of the loop below will be
    // independent and can be executed in parallel, if each thread has
    // its own dct_plan with separate calls to setup_dcts() and cleanup_dcts().
    {
        struct Dct_Plan dct_plan = setup_dcts( type_bwd, ncols );

        if (!dct_plan.dct_buffer) {
            return TERRAIN_FILTER_MALLOC_ERROR;
        }

        for (i=0; i<nrows-1; i+=2) {
            float *ptr = data + (LONG)i * (LONG)ncols;
            two_dcts( ptr, ncols, &dct_plan );
            if (progress && update_progress( &progress_info, i+2, nrows ))
            {
                return TERRAIN_FILTER_CANCELED;
            }
        }
        if (nrows & 1) {
            float *ptr = data + (LONG)(nrows - 1) * (LONG)ncols;
            single_dct( ptr, ncols, &dct_plan );
        }

        cleanup_dcts( &dct_plan );
    }

    cleanup_operator( info );

    set_progress( &progress_info, 6 );

    if (progress) {
        // report final progress; ignore any cancel request at this point
        report_progress( &progress_info );
    }

    return TERRAIN_FILTER_SUCCESS;
}
void threaded_process_status::set_progress(t_size p_state,t_size p_max)
{
	set_progress( progress_min + MulDiv_Size(p_state,progress_max-progress_min,p_max) );
}
Example #11
0
    auto run_simulation(const wayverb::core::geo::box& boundary,
                        const util::aligned::vector<glm::vec3>& receivers,
                        const wayverb::waveguide::coefficients_canonical&
                        coefficients) const {
        const auto scene_data = wayverb::core::geo::get_scene_data(
                                    boundary,
                                    wayverb::core::make_surface<wayverb::core::simulation_bands>(
                                        0, 0));

        auto mesh = wayverb::waveguide::compute_mesh(
                        cc_,
                        make_voxelised_scene_data(
                            scene_data,
                            5,
                            wayverb::waveguide::compute_adjusted_boundary(
                                wayverb::core::geo::compute_aabb(
                                    scene_data.get_vertices()),
                                source_position_,
                                divisions_)),
                        divisions_,
                        speed_of_sound);

        mesh.set_coefficients({coefficients});

        const auto source_index =
            compute_index(mesh.get_descriptor(), source_position_);

        const auto input = [&] {
            const util::aligned::vector<float> raw_input{1.0f};
            auto ret = wayverb::waveguide::make_transparent(
                           raw_input.data(), raw_input.data() + raw_input.size());
            ret.resize(steps, 0);
            return ret;
        }();

        auto prep = wayverb::waveguide::preprocessor::make_soft_source(
                        source_index, input.begin(), input.end());

        auto output_holders = util::map_to_vector(
        begin(receivers), end(receivers), [&](auto i) {
            const auto receiver_index{
                compute_index(mesh.get_descriptor(), i)};
            if (!wayverb::waveguide::is_inside(mesh, receiver_index)) {
                throw std::runtime_error{
                    "receiver is outside of mesh!"};
            }
            return wayverb::core::callback_accumulator<
            wayverb::waveguide::postprocessor::node> {
                receiver_index
            };
        });

        util::progress_bar pb{};
        wayverb::waveguide::run(
            cc_,
            mesh,
            prep,
        [&](auto& queue, const auto& buffer, auto step) {
            for (auto& i : output_holders) {
                i(queue, buffer, step);
            }
            set_progress(pb, step, steps);
        },
        true);

        return util::map_to_vector(
        begin(output_holders), end(output_holders), [](const auto& i) {
            return i.get_output();
        });
    }
Example #12
0
/// The actual test described in section V A from the sheaffer2014 paper.
void test_from_paper() {
    //  Set up all the generic features of the simulation.

    const wayverb::core::geo::box box{glm::vec3{-3}, glm::vec3{3}};
    const auto sample_rate = 16000.0;
    const auto speed_of_sound = 340.0;

    const wayverb::core::compute_context cc{};

    const glm::vec3 receiver{0};
    const auto radius = 1.5;
    const glm::vec3 source{
            std::sin(M_PI / 4) * radius, 0, std::cos(M_PI / 4) * radius};

    auto voxels_and_mesh = wayverb::waveguide::compute_voxels_and_mesh(
            cc,
            wayverb::core::geo::get_scene_data(
                    box,
                    wayverb::core::make_surface<
                            wayverb::core::simulation_bands>(0, 0)),
            receiver,
            sample_rate,
            speed_of_sound);

    {
        constexpr auto absorption = 0.005991;
        voxels_and_mesh.mesh.set_coefficients(
                wayverb::waveguide::to_flat_coefficients(absorption));
    }

    const auto input_node =
            compute_index(voxels_and_mesh.mesh.get_descriptor(), source);
    const auto output_node =
            compute_index(voxels_and_mesh.mesh.get_descriptor(), receiver);

    //  Now we get to do the interesting new bit:
    //  Set up a physically modelled source signal.

    const auto length = 1 << 12;
    auto pulse_shaping_filter =
            wayverb::waveguide::maxflat(0.075, 16, 250e-6, length);
    wayverb::core::filter::biquad mechanical_filter{
            wayverb::waveguide::mech_sphere(
                    0.025, 100 / sample_rate, 0.7, 1 / sample_rate)};
    run_one_pass(mechanical_filter,
                 pulse_shaping_filter.signal.begin(),
                 pulse_shaping_filter.signal.end());
    const auto one_over_two_T = sample_rate / 2;
    wayverb::core::filter::biquad injection_filter{
            {one_over_two_T, 0, -one_over_two_T, 0, 0}};
    run_one_pass(injection_filter,
                 pulse_shaping_filter.signal.begin(),
                 pulse_shaping_filter.signal.end());
    const auto input_signal = pulse_shaping_filter;

    //  Run the simulation.
    auto prep = wayverb::waveguide::preprocessor::make_soft_source(
            input_node, input_signal.signal.begin(), input_signal.signal.end());

    wayverb::core::callback_accumulator<wayverb::waveguide::postprocessor::node>
            postprocessor{output_node};

    util::progress_bar pb;
    wayverb::waveguide::run(cc,
                            voxels_and_mesh.mesh,
                            prep,
                            [&](auto& a, const auto& b, auto c) {
                                postprocessor(a, b, c);
                                set_progress(pb, c, input_signal.signal.size());
                            },
                            true);

    write("test_from_paper", postprocessor.get_output(), sample_rate);
}
Example #13
0
void other_tests() {
    //  Set up all the generic features of the simulation.

    const wayverb::core::geo::box box{glm::vec3{-3}, glm::vec3{3}};
    const auto sample_rate = 4000.0;
    const auto acoustic_impedance = 400.0;
    const auto speed_of_sound = 340.0;

    const wayverb::core::compute_context cc{};

    const glm::vec3 receiver{0};
    const auto radius = 1.5;
    const glm::vec3 source{
            std::sin(M_PI / 4) * radius, 0, std::cos(M_PI / 4) * radius};

    auto voxels_and_mesh = wayverb::waveguide::compute_voxels_and_mesh(
            cc,
            wayverb::core::geo::get_scene_data(
                    box,
                    wayverb::core::make_surface<
                            wayverb::core::simulation_bands>(0, 0)),
            receiver,
            sample_rate,
            speed_of_sound);

    voxels_and_mesh.mesh.set_coefficients(
            wayverb::waveguide::to_flat_coefficients(0.005991));

    const auto input_node =
            compute_index(voxels_and_mesh.mesh.get_descriptor(), source);
    const auto output_node =
            compute_index(voxels_and_mesh.mesh.get_descriptor(), receiver);

    //  Now we get to do the interesting new bit:
    //  Set up a physically modelled source signal.

    const auto run_tests = [&](auto name, auto signals) {
        auto count = 0;
        for (const auto& input_signal : signals) {
            write(util::build_string(name, "_test_input_", count),
                  input_signal.signal,
                  sample_rate);

            //  Run the simulation.
            auto prep = wayverb::waveguide::preprocessor::make_soft_source(
                    input_node,
                    input_signal.signal.begin(),
                    input_signal.signal.end());

            wayverb::core::callback_accumulator<
                    wayverb::waveguide::postprocessor::node>
                    postprocessor{output_node};

            util::progress_bar pb;
            wayverb::waveguide::run(
                    cc,
                    voxels_and_mesh.mesh,
                    prep,
                    [&](auto& a, const auto& b, auto c) {
                        postprocessor(a, b, c);
                        set_progress(pb, c, input_signal.signal.size());
                    },
                    true);

            write(util::build_string(name, "_test_output_", count),
                  postprocessor.get_output(),
                  sample_rate);

            count += 1;
        }
    };

    // run_tests("mass", get_mass_test_signals(sample_rate));
    run_tests("cutoff",
              get_cutoff_test_signals(
                      acoustic_impedance, speed_of_sound, sample_rate));
}
Example #14
0
// Aborts and returns 1 if an error is encountered.
int PackageRenderer::render_package(RenderPackage *package)
{
	int audio_done = 0;
	int video_done = 0;
	int samples_rendered = 0;


	result = 0;
	this->package = package;

// printf(
// "PackageRenderer::render_package: audio s=%lld l=%lld video s=%lld l=%lld\n",
// 	package->audio_start, 
// 	package->audio_end - package->audio_start, 
// 	package->video_start, 
// 	package->video_end - package->video_start);


// FIXME: The design that we only get EDL once does not give us neccessary flexiblity to do things the way they should be donek
	default_asset->video_data = package->video_do;
	default_asset->audio_data = package->audio_do;
	Render::check_asset(edl, *default_asset);
	
	create_output();

	if(!asset->video_data) video_done = 1;
	if(!asset->audio_data) audio_done = 1;

// Create render engine
	if(!result)
	{
		create_engine();

//printf("PackageRenderer::render_package 5 %d\n", result);

// Main loop
		while((!audio_done || !video_done) && !result)
		{
			int need_audio = 0, need_video = 0;




// Calculate lengths to process.  Audio fragment is constant.
			if(!audio_done)
			{
				if(audio_position + audio_read_length >= package->audio_end)
				{
					audio_done = 1;
					audio_read_length = package->audio_end - audio_position;
				}

				samples_rendered = audio_read_length;
				need_audio = 1;
			}

//printf("PackageRenderer::render_package 6 %d\n", samples_rendered);

			if(!video_done)
			{
				if(audio_done)
				{
					video_read_length = package->video_end - video_position;
// Packetize video length so progress gets updated
					video_read_length = (int)MIN(asset->frame_rate, video_read_length);
					video_read_length = MAX(video_read_length, 30);
				}
				else
// Guide video with audio
				{
					video_read_length = Units::to_int64(
						(double)(audio_position + audio_read_length) / 
						asset->sample_rate * 
						asset->frame_rate) - 
						video_position;
				}

// Clamp length
				if(video_position + video_read_length >= package->video_end)
				{
					video_done = 1;
					video_read_length = package->video_end - video_position;
				}

// Calculate samples rendered for progress bar.
				if(audio_done)
					samples_rendered = Units::round((double)video_read_length /
						asset->frame_rate *
						asset->sample_rate);

				need_video = 1;
			}

//printf("PackageRenderer::render_package 1 %d %lld %lld\n", result, audio_read_length, video_read_length);
			if(need_video && !result) do_video();
//printf("PackageRenderer::render_package 7 %d %d\n", result, samples_rendered);
			if(need_audio && !result) do_audio();


			if(!result) set_progress(samples_rendered);





			if(!result && progress_cancelled()) result = 1;

// printf("PackageRenderer::render_package 10 %d %d %d %d\n", 
// audio_read_length, video_read_length, samples_rendered, result);
			if(result) 
				set_result(result);
			else
				result = get_result();
		}

//printf("PackageRenderer::render_package 20\n");
		stop_engine();
//printf("PackageRenderer::render_package 30\n");

		stop_output();
//printf("PackageRenderer::render_package 40\n");


	}



//printf("PackageRenderer::render_package 50\n");
	close_output();
//printf("PackageRenderer::render_package 60\n");


	set_result(result);
//printf("PackageRenderer::render_package 70\n");



	return result;
}
Example #15
0
void loadscreen::increment_progress(const int percentage, const std::string &text, const bool commit) {
	set_progress(prcnt_ + percentage, text, commit);
}
//#################### PRIVATE METHODS ####################
void DICOMVolumeLoader::execute_impl()
try
{
	typedef itk::GDCMImageIO ImageIO;
	typedef itk::Image<int,2> Image2D;
	typedef itk::Image<int,3> Image3D;
	typedef itk::JoinSeriesImageFilter<Image2D,Image3D> Joiner;
	typedef itk::ImageFileReader<Image2D> Reader;
	typedef itk::RegionOfInterestImageFilter<Image2D,Image2D> RegionExtractor;

	// Set up the desired region for each of the slices.
	Image2D::RegionType region;
	itk::Index<2> index = {{m_volumeChoice.minX, m_volumeChoice.minY}};
	itk::Size<2> size = {{m_volumeChoice.maxX + 1 - m_volumeChoice.minX, m_volumeChoice.maxY + 1 - m_volumeChoice.minY}};
	region.SetIndex(index);
	region.SetSize(size);

	std::vector<std::string> imageFilenames = m_dicomdir->image_filenames(m_volumeChoice.patientKey, m_volumeChoice.studyKey, m_volumeChoice.seriesKey);
	std::vector<Image2D::Pointer> images(imageFilenames.size());
	for(int i=m_volumeChoice.minZ; i<=m_volumeChoice.maxZ; ++i)
	{
		std::string imageFilename = m_volumeChoice.filePrefix + imageFilenames[i];

		if(!is_aborted())
		{
			set_progress(i - m_volumeChoice.minZ);
			set_status("Loading image " + imageFilename + "...");
		}
		else return;

		// Load the image.
		Reader::Pointer reader = Reader::New();
		reader->SetFileName(imageFilename);
		ImageIO::Pointer gdcmImageIO = ImageIO::New();
		reader->SetImageIO(gdcmImageIO);
		reader->Update();

		// Extract the relevant sub-region.
		RegionExtractor::Pointer extractor = RegionExtractor::New();
		extractor->SetInput(reader->GetOutput());
		extractor->SetRegionOfInterest(region);
		extractor->Update();

		// Store the image.
		images[i] = extractor->GetOutput();
		images[i]->SetMetaDataDictionary(reader->GetMetaDataDictionary());
	}

	// Get the window centre and width if they haven't been explicitly specified by the user.
	if(m_volumeChoice.windowSettings.unspecified())
	{
		std::string windowCentreStr = read_header_field(images[m_volumeChoice.minZ], "0028|1050");
		std::string windowWidthStr = read_header_field(images[m_volumeChoice.minZ], "0028|1051");
		std::string validChars = "-0123456789";
		windowCentreStr = windowCentreStr.substr(0, windowCentreStr.find_first_not_of(validChars));
		windowWidthStr = windowWidthStr.substr(0, windowWidthStr.find_first_not_of(validChars));
		double windowCentre = lexical_cast<double>(windowCentreStr);
		double windowWidth = lexical_cast<double>(windowWidthStr);
		m_volumeChoice.windowSettings = WindowSettings(windowCentre, windowWidth);
	}

	// Make the images into a volume.
	Joiner::Pointer joiner = Joiner::New();

	double minSliceLocation = 0;
	try							{ minSliceLocation = lexical_cast<double>(read_header_field(images[m_volumeChoice.minZ], "0020|1041")); }
	catch(bad_lexical_cast&)	{ throw Exception("The SliceLocation value for the slice was not of the appropriate type"); }
	joiner->SetOrigin(minSliceLocation);

	double sliceThickness = 0;
	if(m_volumeChoice.minZ + 1 <= m_volumeChoice.maxZ)
	{
		try
		{
			double nextSliceLocation = lexical_cast<double>(read_header_field(images[m_volumeChoice.minZ+1], "0020|1041"));
			sliceThickness = fabs(nextSliceLocation - minSliceLocation);
		}
		catch(bad_lexical_cast&)	{}
	}
	if(sliceThickness == 0)
	{
		try							{ sliceThickness = lexical_cast<double>(read_header_field(images[m_volumeChoice.minZ], "0018|0050")); }
		catch(bad_lexical_cast&)	{ throw Exception("The SliceThickness value for the slice was not of the appropriate type"); }
	}
	joiner->SetSpacing(sliceThickness);

	for(int i=m_volumeChoice.minZ; i<=m_volumeChoice.maxZ; ++i) joiner->PushBackInput(images[i]);
	joiner->Update();
	Image3D::Pointer volumeImage = joiner->GetOutput();

	// Determine the modality of the images.
	DICOMVolume::Modality modality = DICOMVolume::UNSUPPORTED_MODALITY;
	std::string modalityString = read_header_field(images[m_volumeChoice.minZ], "0008|0060");
	if(modalityString == "CT")		modality = DICOMVolume::CT;
	else if(modalityString == "MR")	modality = DICOMVolume::MR;

	if(modality == DICOMVolume::UNSUPPORTED_MODALITY)
	{
		throw Exception("Cannot currently handle modalities other than CT and MR - sorry!");
	}

	m_volume.reset(new DICOMVolume(volumeImage, modality));
}
catch(std::exception& e)
{
	abort();
	set_status(e.what());
}
Example #17
0
int main(int argc, char** argv) {
    try {
        constexpr auto surface =
                wayverb::core::surface<wayverb::core::simulation_bands>{
                        {{0.07, 0.09, 0.11, 0.12, 0.13, 0.14, 0.16, 0.17}},
                        {{0.07, 0.09, 0.11, 0.12, 0.13, 0.14, 0.16, 0.17}}};

        if (argc != 2) {
            throw std::runtime_error{"Expected a scene file."};
        }

        auto scene_data = load_scene(argv[1]);
        scene_data.set_surfaces(surface);

        // const auto box = wayverb::core::geo::box{glm::vec3{0},
        //                                         glm::vec3{5.56, 3.97, 2.81}};
        // const auto scene_data =
        //        wayverb::core::geo::get_scene_data(box, surface);

        const auto aabb_centre = centre(
                wayverb::core::geo::compute_aabb(scene_data.get_vertices()));

        const auto source = aabb_centre + glm::vec3{0, 0, 0.2};
        const auto receiver = aabb_centre + glm::vec3{0, 0, -0.2};

        const auto rays = 1 << 16;
        const auto img_src_order = 4;

        const auto cutoff = 1000;
        const auto usable_portion = 0.6;

        const auto output_sample_rate = 44100.0;

        const auto params = wayverb::waveguide::single_band_parameters{cutoff, usable_portion};

        //  Set up simulation.
        wayverb::combined::engine engine{
                wayverb::core::compute_context{},
                scene_data,
                source,
                receiver,
                wayverb::core::environment{},
                wayverb::raytracer::simulation_parameters{rays, img_src_order},
                wayverb::combined::make_waveguide_ptr(params)};

        //  When the engine changes, print a nice progress bar.

        util::progress_bar pb{std::cout};
        engine.connect_engine_state_changed([&](auto state, auto progress) {
            set_progress(pb, progress);
        });

        //  Run simulation.
        const auto intermediate = engine.run(true);

        //  Do directional postprocessing.
        const wayverb::core::orientation receiver_orientation{};
        std::vector<util::named_value<
                std::unique_ptr<wayverb::combined::capsule_base>>>
                capsules;
        capsules.emplace_back(
                "microphone",
                wayverb::combined::make_capsule_ptr(
                        wayverb::core::attenuator::microphone{
                                wayverb::core::orientation{}, 0.5},
                        receiver_orientation));
        capsules.emplace_back(
                "hrtf",
                wayverb::combined::make_capsule_ptr(
                        wayverb::core::attenuator::hrtf{
                                wayverb::core::orientation{},
                                wayverb::core::attenuator::hrtf::channel::left},
                        receiver_orientation));

        auto output_channels = util::map_to_vector(
                begin(capsules), end(capsules), [&](const auto& i) {
                    return map(
                            [&](const auto& i) {
                                return i->postprocess(*intermediate,
                                                      output_sample_rate);
                            },
                            i);
                });

        //  Reduce volume to reasonable level.
        constexpr auto volume_factor = 0.05;
        for (auto& i : output_channels) {
            wayverb::core::mul(i.value, volume_factor);
        }

        //  Write out.
        for (const auto& i : output_channels) {
            write(util::build_string(i.name, ".wav").c_str(),
                  i.value,
                  output_sample_rate,
                  audio_file::format::wav,
                  audio_file::bit_depth::pcm16);
        }

    } catch (const std::exception& e) {
        std::cerr << e.what() << '\n';
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}
void threaded_process_status::set_progress_float(double p_state)
{
	if (p_state < 0.0) set_progress(progress_min);
	else if (p_state < 1.0) set_progress( progress_min + (t_size)(p_state * (progress_max - progress_min)));
	else set_progress(progress_max);
}