plugins_manager.cpp 15.4 KB
Newer Older
1 2 3
/* ALTA --- Analysis of Bidirectional Reflectance Distribution Functions

   Copyright (C) 2014, 2015 CNRS
4
   Copyright (C) 2013, 2014, 2015 Inria
5 6 7 8 9 10 11

   This file is part of ALTA.

   This Source Code Form is subject to the terms of the Mozilla Public
   License, v. 2.0.  If a copy of the MPL was not distributed with this
   file, You can obtain one at http://mozilla.org/MPL/2.0/.  */

12
#include "plugins_manager.h"
13 14
#include "rational_function.h"
#include "vertical_segment.h"
15

pacanows's avatar
pacanows committed
16
#ifdef _WIN32
17
    #include <windows.h>
18 19 20
#else
    #include <dlfcn.h>
#endif
21
#include <cstdlib>
22
#include <stdio.h>
23
#include <list>
24

25 26 27
//#define DEBUG


28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
//! Add dynamic library extension (.so or .dll) to a dynamic object as well as
//! prepending 'lib' depending on the plateform.
std::string library_name(const std::string name) 
{
	std::string filename;

	const int n = name.length();
#if defined( _WIN32)
	if(name.substr(n-4, n) != std::string("dll")) {
		filename.append(name);
		filename.append(".dll");
	}
#elif defined(__APPLE__)
	if(name.substr(n-5, n) != std::string("dylib")) {
		filename.append("lib");
		filename.append(name);
		filename.append(".dylib");
	}
#else
	if(name.substr(n-2, n) != std::string("so")) {
		filename.append("lib");
		filename.append(name);
		filename.append(".so");
	}
#endif
	else {
		filename.append(name);
	}

	return filename;
}

60 61 62 63 64
void get_library_dirs(std::list<std::string>& dirs)
{
	dirs.push_back("");

	std::string obj_str ;
65
	const char *env_str = std::getenv("ALTA_LIB") ;
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85

	if(env_str == NULL) {
		obj_str = "" ;
	} else {
		obj_str = std::string(env_str)+":" ;
	}

	while(true)	{
		int lb = obj_str.find_first_not_of(":",0) ;
		int le = obj_str.find_first_of(":",lb) ;

		if(lb < le)	{
			dirs.push_back(obj_str.substr(lb,le-lb)) ;
			obj_str = obj_str.substr(le+1,obj_str.size()) ;
		} else {
			break ;
		}
	}
}

86 87 88 89 90
//! \brief Open a dynamic library file (.so or .dll) and extract the associated
//! provide function. The template argument is used to cast the library to a
//! specific type.
template<typename T> T open_library(const std::string& filename, const char* function)
{
91 92 93 94 95 96
	std::list<std::string> basename;
	get_library_dirs(basename);

	std::list<std::string>::iterator iter;
	for(iter = basename.begin(); iter != basename.end(); ++iter)
	{
97 98
	 std::string libname = *iter;
	 libname.append(library_name(filename));
99

100

pacanows's avatar
pacanows committed
101
#ifdef _WIN32
102
    HINSTANCE handle = LoadLibraryA(libname.c_str());
103 104 105 106 107 108
    if(handle != NULL)
    {
        T res = (T)GetProcAddress(handle, function);

        if(res == NULL)
        {
109 110 111 112
#ifdef DEBUG_CORE
			  std::cerr << "<<ERROR>> unable to load the symbol \"" << function << "\" from " << filename << std::endl;
#endif
			  continue;
113 114 115 116 117 118 119 120
        }
#ifdef DEBUG_CORE
        std::cout << "<<DEBUG>> will provide a " << function << " for library \"" << filename << "\"" << std::endl;
#endif
        return res;
    }
    else
    {
121
#ifdef DEBUG_CORE
122
        std::cerr << "<<ERROR>> unable to load the dynamic library file \"" << libname << "\"" << std::endl;
123
        std::cerr << "          cause: \"" << GetLastError() << "\"" << std::endl;
124 125
#endif
		 continue;
126
    }
127
#else
128
    void* handle = dlopen(libname.c_str(), RTLD_GLOBAL | RTLD_LAZY);
129

130
	 if(handle != NULL)
131 132 133
	 {
		 void (*res)();
		 *(void **)(&res) = dlsym(handle, function);
134 135 136

        if(dlerror() != NULL)
        {
137
#ifdef DEBUG_CORE
138
            std::cerr << "<<ERROR>> unable to load the symbol \"" << function << "\" from " << libname << std::endl;
139
#endif
140
            continue;
141 142
        }
#ifdef DEBUG_CORE
143
        std::cout << "<<DEBUG>> will provide a " << function << " for library \"" << libname << "\"" << std::endl;
144 145 146 147 148
#endif
        return (T)res;
    }
    else
    {
149
#ifdef DEBUG_CORE
150
        std::cerr << "<<ERROR>> unable to load the dynamic library file \"" << libname << "\"" << std::endl;
151
		  std::cerr << "          cause: \"" << dlerror() << "\"" << std::endl;
152
#endif
153
        continue;
154 155
    }
#endif
156
	}
157 158 159
   
	std::cerr << "<<ERROR>> unable to load the symbol \"" << function << "\" from " << filename << std::endl;
	return NULL;
160 161
}

162
//! \brief load a function from the ALTA input file.
163
function* plugins_manager::load_function(const std::string& filename)
164 165 166 167 168 169
{
	std::ifstream file;
	file.open(filename.c_str()) ;
	if(!file.is_open())
	{
		std::cerr << "<<ERROR>> unable to open file \"" << filename << "\"" << std::endl ;
170
		return NULL;
171 172
	}

173 174 175
	// Set the precision of the input
	file.precision(10);

176 177
	// Parameters of the function object
	int nX, nY;
178
	params::input param_in   = params::UNKNOWN_INPUT;
179
	params::output param_out = params::UNKNOWN_OUTPUT;
180 181 182 183 184 185 186 187
	arguments args;

	// Test for the first line of the file. Should be a ALTA FUNC HEADER
	std::string line ;
	std::getline(file, line) ;
	if(line != "#ALTA FUNC HEADER")
	{
		std::cerr << "<<ERROR>> this is not a function file" << std::endl;
188 189 190

    //RP: Returning NULL immediately now
    return NULL;
191 192 193 194
	}

	// Parse the header for the function command line and the dimension
	// of the function
195
	arguments header = arguments::parse_header(file);
196

197
	std::pair<int, int> dim = header.get_pair<int>("DIM");
198 199
	nX = dim.first;
	nY = dim.second;
200

201 202
	param_in = params::parse_input(header.get_string("PARAM_IN", "UNKNOWN_INPUT"));
	param_out = params::parse_output(header.get_string("PARAM_OUT", "UNKNOWN_OUTPUT"));
203
	args = arguments::create_arguments(header["CMD"]);
204 205 206 207 208

	// Create the function from the command line
	function* f = get_function(args);
	f->setDimX(nX);
	f->setDimY(nY);
209 210 211 212
  if(f->input_parametrization() == params::UNKNOWN_INPUT)
  {
    f->setParametrization(param_in);
  }
213
	f->setParametrization(param_out);
214 215

	// Load the function part from the file object
216 217 218 219
  if( f->load(file) )
  {
    return f;
  }
220

221 222
  std::cout << "<<ERROR>> COULD NOT LOAD THE BRDF from File " << filename << std::endl;
	 return NULL;
223 224
}

225
//! Get an instance of the function selected based on the name <em>n</em>.
226
//! Return NULL if none exists.
227
function* plugins_manager::get_function(const arguments& args)
228
{
229 230 231 232 233 234 235
  #ifdef DEBUG
  std::cout << __FILE__ << " " << __LINE__ << std::endl;
  std::cout << " INitial args = " << args << std::endl;
  #endif

  if(!args.is_defined("func"))
  {
PACANOWSKI Romain's avatar
PACANOWSKI Romain committed
236 237 238 239
    #ifdef DEBUG
    std::cout << "<<DEBUG>> no function plugin specified, returning a rational function" << std::endl;
    #endif
    return new rational_function();
240 241 242 243 244 245 246 247 248 249
  }

  // The function to be returned.
  function* func = NULL;

  if(args.is_vec("func")) //Checking if  the argument prodived with --func is of the form --func [ arg1, arg2, arg3]
  {
    #ifdef DEBUG
    std::cout << __FILE__ << " " << __LINE__ << " ARGUMENTS of --func are forming a VECTOR " << std::endl;
    #endif 
250

251
    std::vector<std::string> args_vec = args.get_vec("func");
Laurent Belcour's avatar
Laurent Belcour committed
252

253 254
    // Treating the case []
    if(args_vec.size() == 0)
255
    {
256 257
        return NULL;
    }
258

259
	 //! create a *compound* class to store multiple ! functions in it.
260
    compound_function* compound = new compound_function();
261

262 263
	 //! For each args_vec element, create a function object and add ! it to the
	 //compound one.
264 265 266 267
    for(unsigned int i=0; i<args_vec.size(); ++i)
    {
      std::string n("--func ");
      n.append(args_vec[i]);
PACANOWSKI Romain's avatar
PACANOWSKI Romain committed
268 269

      #ifdef DEBUG
270 271 272
      std::cout << __FILE__ << " " << __LINE__ << std::endl
                << " at i=" << i << " n=" << n << std::endl;
      std::cout << "<<DEBUG>> load function with args: " << n << std::endl;
PACANOWSKI Romain's avatar
PACANOWSKI Romain committed
273 274
      #endif
      
275
      arguments temp_args = arguments::create_arguments(n);
276

277 278
      //Recursive call
      function* f = get_function(temp_args);
279 280
      nonlinear_function *nl_f = dynamic_cast<nonlinear_function*>(f);
      if(nl_f == NULL)
281 282 283 284 285
      {
          std::cerr << "<<ERROR>> only non-linear functions are compatible with a compound" << std::endl;
      }
      else
      {
286
          compound->push_back(ptr<nonlinear_function>(nl_f), temp_args);
287 288
      }
    }
289

290
		  //! return the compound class 
291
		  func = compound;
292 293 294
      #ifdef DEBUG
      std::cout << __FILE__ << " " << __LINE__ << " WE HAVE A COMPOUND " << std::endl;
      #endif
PACANOWSKI Romain's avatar
PACANOWSKI Romain committed
295 296 297 298 299 300 301 302 303 304 305 306
  }
  else //Here we check if the argument provided with --func is file describing a function
  {
    const std::string filename = args["func"];
    FunctionPrototype myFunction = open_library<FunctionPrototype>(filename, "provide_function");
    if(myFunction != NULL)
    {
      #ifdef DEBUG
      std::cout << "<<DEBUG>> using function provider in file \"" << filename << "\"" << std::endl;
      #endif
      
      func =  myFunction();
307
    }
PACANOWSKI Romain's avatar
PACANOWSKI Romain committed
308
    else
309
    {
PACANOWSKI Romain's avatar
PACANOWSKI Romain committed
310 311
      std::cerr << "<<ERROR>> no function provider found in file \"" << filename << "\"" << std::endl;
      return new rational_function() ;
312
    }
PACANOWSKI Romain's avatar
PACANOWSKI Romain committed
313
  }
314

PACANOWSKI Romain's avatar
PACANOWSKI Romain committed
315 316 317
  // Treat the case of the Fresnel
  if(args.is_defined("fresnel"))
  {
318 319 320 321 322
      #ifdef DEBUG
      std::cout << __FILE__ << " " << __LINE__ << std::endl;
      std::cout << " INSIDE fresnel args = " << args << std::endl;
      #endif

PACANOWSKI Romain's avatar
PACANOWSKI Romain committed
323 324 325 326 327 328 329 330 331 332
      // Cast into a non linear function, only those are permitted to use
      // a Fresnel term.
      nonlinear_function* nl_func = dynamic_cast<nonlinear_function*>(func);
      if(nl_func == NULL)
      {
       std::cerr << "<<ERROR>> only non-linear function are permitted to use Fresnel" << std::endl;
       return func;
      }

      std::cout << "<<DEBUG>> multiplying by a Fresnel term" << std::endl;
333

PACANOWSKI Romain's avatar
PACANOWSKI Romain committed
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
      std::string n("--func ");
      if(args.is_vec("fresnel"))
      {
       std::string temp = args["fresnel"];
       n.append(temp.substr(1, temp.size()-2));
      }
      else
      {
       std::string fname = args["fresnel"];
       if(fname.empty()) // Nothing to do except print error, no plugin defined
       {
      	 std::cerr << "<<ERROR>> Fresnel plugin not defined" << std::endl;
      	 std::cerr << "<<ERROR>> using --fresnel alone is not permitted" << std::endl;
      	 return func;
       }
       else // Case where the fresnel parameters is only the plugin filename
       {
      	 n.append(fname);
       }
      }

355 356 357 358 359
      #ifdef DEBUG
      std::cout << __FILE__ << " " << __LINE__ << std::endl;
      std::cout << " n = " << n << std::endl;
      #endif
       
PACANOWSKI Romain's avatar
PACANOWSKI Romain committed
360 361 362
      nonlinear_function* func_fres = dynamic_cast<nonlinear_function*>(get_function(arguments::create_arguments(n)));
      if(func_fres != NULL)
      {
363 364 365 366 367 368 369 370 371 372 373 374
        bool const fresnel_is_fixed = (args.is_defined("fixed-fresnel")) ? (true) : (false);
        bool const lobe_is_fixed    = (args.is_defined("fixed-lobe")) ? (true) : (false);
       
        if( fresnel_is_fixed )
        {
          std::cout << "<<DEBUG>> The Fresnel term is fixed" << std::endl;
        }
        if( lobe_is_fixed )
        {
          std::cout << "<<DEBUG>> The lobe is fixed" << std::endl;
        }

375 376 377
        return new product_function(ptr<nonlinear_function>(nl_func),
                                    ptr<nonlinear_function>(func_fres),
                                    lobe_is_fixed, fresnel_is_fixed);
PACANOWSKI Romain's avatar
PACANOWSKI Romain committed
378 379 380
      }
      else
      {
381 382
        std::cerr << "<<ERROR>> the right part of the product is not a nonlinear function. Will use only the left part." << std::endl;
        return func;
PACANOWSKI Romain's avatar
PACANOWSKI Romain committed
383
      }
384
	 }
PACANOWSKI Romain's avatar
PACANOWSKI Romain committed
385 386

   
387
/*
388 389 390 391 392 393 394
	 // Correction of the data by 1/cosine(theta_L)
	 if(args.is_defined("data-correct-cosine"))
	 {
		 nonlinear_function* cosine = new cosine_function();
		 func = new product_function(cosine, dynamic_cast<nonlinear_function*>(func));
	 }
	 // End of correction
395
*/
PACANOWSKI Romain's avatar
PACANOWSKI Romain committed
396 397


398
    return func;
399
}
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417


ptr<function> plugins_manager::get_function(const std::string& n)
{
    if(n.empty())
    {
#ifdef DEBUG
        std::cout << "<<DEBUG>> no function plugin specified, returning nothing" << std::endl;
#endif
        return NULL;
    }

	 FunctionPrototype myFunc = open_library<FunctionPrototype>(n, "provide_function");
    if(myFunc != NULL)
    {
#ifdef DEBUG
        std::cout << "<<DEBUG>> using function provider in file \"" << n << "\"" << std::endl;
#endif
418
        return ptr<function>(myFunc());
419 420 421 422 423 424 425 426 427
    }
    else
    {
        std::cerr << "<<ERROR>> no function provider found in file \"" << n << "\"" << std::endl;
        return NULL;
    }
}


428
ptr<data> plugins_manager::get_data(const std::string& n, const arguments& args)
429
{
430
    if(n.empty() || n == "vertical_segment")
431
    {
432
#ifdef DEBUG
433
        std::cout << "<<DEBUG>> no data plugin specified, returning a vertical_segment loader" << std::endl;
434
#endif
435
        return ptr<data>(new vertical_segment());
436 437
    }

438
	 DataPrototype myData = open_library<DataPrototype>(n, "provide_data");
439 440
    if(myData != NULL)
    {
441
#ifdef DEBUG
442
        std::cout << "<<DEBUG>> using data provider in file \"" << n << "\"" << std::endl;
443
#endif
444
        return ptr<data>(myData(args));
445 446 447 448
    }
    else
    {
        std::cerr << "<<ERROR>> no data provider found in file \"" << n << "\"" << std::endl;
449
        return ptr<data>(new vertical_segment()) ;
450
    }
451
}
452
ptr<fitter> plugins_manager::get_fitter(const std::string& n)
453
{
Laurent Belcour's avatar
Laurent Belcour committed
454 455 456 457 458
    if(n.empty())
    {
#ifdef DEBUG
        std::cout << "<<DEBUG>> no fitter plugin specified, returning null" << std::endl;
#endif
459
        return NULL;
Laurent Belcour's avatar
Laurent Belcour committed
460 461
    }

462
    FitterPrototype myFitter = open_library<FitterPrototype>(n, "provide_fitter");
Laurent Belcour's avatar
Laurent Belcour committed
463 464 465
    if(myFitter != NULL)
    {
#ifdef DEBUG
466
        std::cout << "<<DEBUG>> using fitter provider in file \"" << n << "\"" << std::endl;
Laurent Belcour's avatar
Laurent Belcour committed
467
#endif
468
        return ptr<fitter>(myFitter());
Laurent Belcour's avatar
Laurent Belcour committed
469 470 471
    }
    else
    {
472
        std::cerr << "<<ERROR>> no fitter provider found in file \"" << n << "\"" << std::endl;
473
        return NULL ;
Laurent Belcour's avatar
Laurent Belcour committed
474
    }
475
}
476

477 478 479
void plugins_manager::check_compatibility( ptr<data>& d, 
                                           const ptr<function>& f,
                                           const arguments& args)
Laurent Belcour's avatar
Laurent Belcour committed
480
{
481 482
	if(d->input_parametrization() == params::UNKNOWN_INPUT &&
		f->input_parametrization() == params::UNKNOWN_INPUT)
Laurent Belcour's avatar
Laurent Belcour committed
483
	{
484
		std::cout << "<<WARNING>> both function and data objects have no parametrization" << std::endl;
Laurent Belcour's avatar
Laurent Belcour committed
485 486 487
	}
	else
	{
488 489 490 491 492 493 494 495 496 497
		if(d->input_parametrization() == params::UNKNOWN_INPUT)
		{
			std::cout << "<<WARNING>> unknown parametrization for data" << std::endl;
		}

		if(f->input_parametrization() == params::UNKNOWN_INPUT)
		{
			std::cout << "<<DEBUG>> function will take the parametrization of the data" << std::endl;
			f->setParametrization(d->input_parametrization());
		}
498
		else if(d->input_parametrization() != f->input_parametrization() && args.is_defined("change-param"))
499
		{
500
			std::cout << "<<INFO>> has to change the parametrization of the input data " << params::get_name(d->input_parametrization()) << std::endl;
501
      std::cout << "<<INFO>> to " << params::get_name(f->input_parametrization()) << std::endl;
502
			ptr<data_params> dd = ptr<data_params>(new data_params(d, f->input_parametrization()));
503
			d = dynamic_pointer_cast<data>(dd) ;
504 505 506 507 508
		}
		else
		{
			std::cout << "<<DEBUG>> no change was made to the parametrization" << std::endl;
		}
Laurent Belcour's avatar
Laurent Belcour committed
509 510 511 512
	}

	if(f->dimY() != d->dimY())
	{
513
    f->setDimY(d->dimY());
Laurent Belcour's avatar
Laurent Belcour committed
514 515 516 517 518 519 520 521 522 523 524
	}

	/*
	// Check is the data has to be clusterized
	if(args.is_defined("cluster-dim"))
	{
	clustering* cluster = new clustering(d, args);
	d = cluster;
	}
	*/
}
525

526
// \todo implement the Darwin (MACOS) version.
527 528
// \todo : Why not move these functions to common.h ?
#ifdef _WIN32
529
#include <windows.h>
530
size_t plugins_manager::get_system_memory()
531 532 533 534 535 536
{
	MEMORYSTATUSEX status;
	status.dwLength = sizeof(status);
	GlobalMemoryStatusEx(&status);
	return status.ullTotalPhys;
}
537 538 539 540 541
#elif defined(__APPLE__)
#include <unistd.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/sysctl.h>
542 543
size_t plugins_manager::get_system_memory()
{
544 545 546 547 548 549 550 551 552
  int mib[2];
  mib[0] = CTL_HW;
  mib[1] = HW_MEMSIZE;    
  int64_t size = 0;   
	size_t len = sizeof( size );
  if ( sysctl( mib, 2, &size, &len, NULL, 0 ) == 0 )
    return (size_t)size;
  
  return 0L;
553
}
554 555
#else
#include <unistd.h>
556
size_t plugins_manager::get_system_memory()
557 558 559 560 561 562
{
	long pages = sysconf(_SC_PHYS_PAGES);
	long page_size = sysconf(_SC_PAGE_SIZE);
	return pages * page_size;
}
#endif