multimodel.cpp 14.6 KB
Newer Older
1 2 3 4 5 6 7 8 9
////////////////////////////////////////////////////////
//
// GEM - Graphics Environment for Multimedia
//
// zmoelnig@iem.kug.ac.at
//
// Implementation file
//
//    Copyright (c) 1997-1999 Mark Danks.
zmoelnig's avatar
zmoelnig committed
10
//    Copyright (c) Günther Geiger.
zmoelnig's avatar
zmoelnig committed
11
//    Copyright (c) 2001-2011 IOhannes m zmölnig. forum::für::umläute. IEM. zmoelnig@iem.at
12 13 14 15
//    For information on usage and redistribution, and for a DISCLAIMER OF ALL
//    WARRANTIES, see the file, "GEM.LICENSE.TERMS" in this distribution.
//
/////////////////////////////////////////////////////////
16

17
#include "multimodel.h"
18
#include "Gem/State.h"
19 20 21
#include "plugins/modelloader.h"
#include <algorithm> // std::min
#include <string.h>
22
#include <stdio.h>
23

24 25 26 27 28 29 30 31 32 33 34
namespace {
static char mytolower(char in)
{
  if(in<='Z' && in>='A') {
    return in-('Z'-'z');
  }
  return in;
}
};


35 36
CPPEXTERN_NEW_WITH_FOUR_ARGS(multimodel, t_symbol *, A_DEFSYM, t_floatarg,
                             A_DEFFLOAT, t_floatarg, A_DEFFLOAT, t_floatarg, A_DEFFLOAT);
37 38 39 40 41 42 43 44 45 46

/////////////////////////////////////////////////////////
//
// multimodel
//
/////////////////////////////////////////////////////////
// Constructor
//
/////////////////////////////////////////////////////////
multimodel :: multimodel(t_symbol *filename, t_floatarg baseModel,
IOhannes m zmölnig's avatar
IOhannes m zmölnig committed
47
                         t_floatarg topModel, t_floatarg skipRate)
48 49 50 51 52 53
  :  m_loader(NULL),
     m_size_change_flag(false),
     m_position(256,3),
     m_texture (256,2),
     m_color   (256,4),
     m_normal  (256,3),
54 55
     m_infoOut(gem::RTE::Outlet(this)),
     m_drawType(GL_TRIANGLES)
56
{
57 58 59 60 61 62 63 64
  m_drawTypes.clear();
  m_drawTypes["default"]=m_drawType;
  m_drawTypes["point"]=GL_POINTS;
  m_drawTypes["points"]=GL_POINTS;
  m_drawTypes["line"]=GL_LINES;
  m_drawTypes["lines"]=GL_LINES;
  m_drawTypes["fill"]=GL_TRIANGLES;

65
  inlet_new(this->x_obj, &this->x_obj->ob_pd, &s_float, gensym("mdl_num"));
66

67
  // make sure that there are some characters
68
  if (filename&&filename->s_name&&*filename->s_name) {
69
    openMess(filename->s_name, baseModel, topModel, skipRate);
70
  }
71 72
}

73
/////////////////////////////////////////////////////////
74 75 76
// Destructor
//
/////////////////////////////////////////////////////////
77
multimodel :: ~multimodel(void)
78
{
79
  close();
80 81 82
}

/////////////////////////////////////////////////////////
83
// close
84 85
//
/////////////////////////////////////////////////////////
86
void multimodel :: close(void)
87
{
88 89
  unsigned int i;
  for(i=0; i<m_loaders.size(); i++) {
90 91
    if (m_loaders[i]) {
      m_loaders[i]->close();
92
      delete m_loaders[i];
93
    }
94
    m_loaders[i]=NULL;
95
  }
96
  m_loaders.clear();
97 98 99 100 101 102 103 104 105 106 107 108 109 110
  m_loader = NULL;
}


void multimodel :: applyProperties(void)
{
#if 0
  std::vector<std::string>keys=m_properties.keys();
  unsigned int i;
  for(i=0; i<keys.size(); i++) {
    post("key[%d]=%s ... %d", i, keys[i].c_str(), m_properties.type(keys[i]));
  }
#endif

111
  if(m_loader) {
112
    m_loader->setProperties(m_properties);
113
  }
114 115 116
}

/////////////////////////////////////////////////////////
117
// materialMess
118 119
//
/////////////////////////////////////////////////////////
120 121 122 123 124 125 126 127
void multimodel :: materialMess(int material)
{
  gem::any value=material;
  m_properties.set("usematerials", value);
  applyProperties();
}

/////////////////////////////////////////////////////////
128
// textureMess
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
//
/////////////////////////////////////////////////////////
void multimodel :: textureMess(int state)
{
  std::string textype;
  switch(state) {
  case 0:
    textype="linear";
    break;
  case 1:
    textype="spheremap";
    break;
  case 2:
    textype="UV";
    break;
  default:
    break;
  }
  if(textype.empty()) {
    m_properties.erase("textype");
  } else {
    gem::any value=textype;
    m_properties.set("textype", value);
  }
  applyProperties();
}

/////////////////////////////////////////////////////////
// smoothMess
//
/////////////////////////////////////////////////////////
void multimodel :: smoothMess(t_float fsmooth)
{
  m_properties.set("smooth", fsmooth);
  applyProperties();
}

/////////////////////////////////////////////////////////
167
// reverseMess
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
//
/////////////////////////////////////////////////////////
void multimodel :: reverseMess(bool reverse)
{
  gem::any value=(double)reverse;
  m_properties.set("reverse", value);
  applyProperties();
}
/////////////////////////////////////////////////////////
// matrialMess
//
/////////////////////////////////////////////////////////
void multimodel :: rescaleMess(bool state)
{
  gem::any value=(double)state;
  m_properties.set("rescale", value);
  applyProperties();
}

/////////////////////////////////////////////////////////
188
// groupMess
189 190 191 192 193 194 195 196 197
//
/////////////////////////////////////////////////////////
void multimodel :: groupMess(int state)
{
  gem::any value=state;
  m_properties.set("group", value);
  applyProperties();
}

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
/////////////////////////////////////////////////////////
// drawStyle
//
/////////////////////////////////////////////////////////
void multimodel :: drawMess(int type)
{
  /* raw */
  m_drawType = type;
}

void multimodel :: drawMess(std::string name)
{
  if(0==m_drawTypes.size()) {
    error("unable to change drawstyle");
    return;
  }

  std::transform(name.begin(), name.end(), name.begin(), mytolower);

  std::map<std::string, GLenum>::iterator it=m_drawTypes.find(name);
  if(m_drawTypes.end() == it) {
    error ("unknown draw style '%s'... possible values are:", name.c_str());
    it=m_drawTypes.begin();
    while(m_drawTypes.end() != it) {
      error("\t %s", it->first.c_str());
      ++it;
    }
    return;
  }
  m_drawType=it->second;
}


231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
/////////////////////////////////////////////////////////
// backendMess
//
/////////////////////////////////////////////////////////
void multimodel :: backendMess(t_symbol*s, int argc, t_atom*argv)
{
#if 0
  gem::any value=ids;
  m_properties.set("backends", value);
  applyProperties();
#endif
  int i;

  m_backends.clear();
  if(argc) {
    for(i=0; i<argc; i++) {
      if(A_SYMBOL == argv->a_type) {
        t_symbol *b=atom_getsymbol(argv+i);
        m_backends.push_back(b->s_name);
      } else {
        error("%s must be symbolic", s->s_name);
      }
    }
  } else {
    /* no backend requested, just enumerate them */
    if(m_loader) {
      std::vector<gem::any>atoms;
      gem::any value;
      t_atom at;
      t_atom*ap=&at;
      gem::Properties props;
      std::vector<std::string> backends;
      props.set("backends", value);
      m_loader->getProperties(props);
      if(props.type("backends")!=gem::Properties::UNSET) {
        props.get("backends", backends);
      }
      atoms.clear();
      atoms.push_back(value=(int)(backends.size()));
      m_infoOut.send("loaders", atoms);
      if(!backends.empty()) {
        for(i=0; i<backends.size(); i++) {
          atoms.clear();
          atoms.push_back(value=backends[i]);
          post("loader[%d] %s", i, backends[i].c_str());
          m_infoOut.send("loader", atoms);
        }
      } else {
        post("no model-loading backends found!");
      }
    }
  }
}

/////////////////////////////////////////////////////////
// openMess
//
/////////////////////////////////////////////////////////
void multimodel :: openMess(const std::string&filename,
                            float baseModel, float topModel, float skipRate)
{
  int skipRatei=static_cast<int>(skipRate);
  int topModeli=static_cast<int>(topModel);
  int baseModeli=static_cast<int>(baseModel);
  if (skipRatei == 0) {
296
    if (topModeli == 0) {
297
      open(filename, 0, baseModeli, 1);
298
    } else {
299
      open(filename, baseModeli, topModeli, 1);
300 301 302
    }
  } else {
    open(filename, baseModeli, topModeli, skipRatei);
303 304
  }
}
305 306
void multimodel :: open(const std::string&filename, int baseModel,
                        int topModel, int skipRate)
307
{
308 309 310 311
  gem::Properties wantProps = m_properties;
  if(!m_backends.empty()) {
    wantProps.set("backends", m_backends);
  }
312
  std::vector<gem::plugins::modelloader*>loaders;
313

314
  if (!topModel) {
315
    error("requires an int for number of models");
316 317 318
    return;
  }
  if (baseModel > topModel) {
319
    error("top range less than base model");
320 321
    return;
  }
322 323 324
  if (skipRate < 1) {
    skipRate = 1;
  }
325 326
  char preName[256];
  char postName[256];
327

328
  int i = 0;
329
  const char *strPtr = filename.c_str();
330 331 332 333
  while (strPtr[i] && strPtr[i] != '*') {
    preName[i] = strPtr[i];
    i++;
  }
334

335
  if (!strPtr[i]) {
336
    error("unable to find * in file name");
337 338 339
    return;
  }

340
  preName[i] = '\0';
341 342
  strncpy(postName, &(strPtr[i+1]), 255);
  postName[255]='\0';
343

344
  // need to figure out how many filenames there are to load
345
  int numModels = (topModel + 1 - baseModel) / skipRate;
346 347 348

  int realNum = baseModel;
  char bufName[MAXPDSTRING];
349 350
  canvas_makefilename(const_cast<t_canvas*>(getCanvas()), preName, bufName,
                      MAXPDSTRING);
351

IOhannes m zmölnig's avatar
IOhannes m zmölnig committed
352 353
  char newName[MAXPDSTRING];
  newName[0]=0;
354

355
  for (i = 0; i < numModels; i++, realNum += skipRate) {
IOhannes m zmölnig's avatar
IOhannes m zmölnig committed
356 357 358
    snprintf(newName, MAXPDSTRING, "%s%d%s", bufName, realNum, postName);
    newName[MAXPDSTRING-1]=0;
    verbose(1, "trying to load '%s'", newName);
359 360

    gem::plugins::modelloader*loader=gem::plugins::modelloader::getInstance();
361 362 363
    if(!loader) {
      break;
    }
364

365
    if(loader->open(newName, wantProps)) {
366
      loaders.push_back(loader);
367
    } else {
368
      delete loader;
369
      break;
370
    }
371 372
  }

373
  if(loaders.size()!=numModels) {
374
    /* ouch, something went wrong! */
375 376
    error("failed to load model#%d of %d (%s)...resetting to original models",
          i, numModels, newName);
377 378
    unsigned int ui;
    for(ui=0; ui<loaders.size(); ui++) {
379
      if(loaders[ui]) {
380
        delete loaders[ui];
381
      }
382
      loaders[ui]=NULL;
383 384 385
    }
    loaders.clear();
    return;
386 387
  }

388
  close();
389
  m_loaders=loaders;
390
  if(m_loaders.size()>0) {
391
    m_loader = m_loaders[0];
392
  }
393

394
  post("loaded models: %s %s from %d to %d skipping %d",
395 396
       bufName, postName, baseModel, topModel, skipRate);

397 398
  getVBOarray();
  setModified();
399 400
}

401
/////////////////////////////////////////////////////////
402
// changeModel
403 404
//
/////////////////////////////////////////////////////////
405
void multimodel :: changeModel(int modelNum)
406
{
407 408 409
  if (modelNum < 0 || ((unsigned int)modelNum) >= m_loaders.size()) {
    error("selection %d out of range: 0..%d", modelNum, m_loaders.size()-1);
    return;
410
  }
411
  m_loader = m_loaders[modelNum];
412

413 414
  getVBOarray();
  setModified();
415
}
416

417 418 419
void multimodel :: startRendering()
{
  if (m_loader) {
420 421 422 423 424
    copyArray(m_loader->getVector("vertices"), m_position);
    copyArray(m_loader->getVector("texcoords"), m_texture);
    copyArray(m_loader->getVector("normals"), m_normal);
    copyArray(m_loader->getVector("colors"), m_color);
  }
425 426 427 428 429
}
/////////////////////////////////////////////////////////
// render
//
/////////////////////////////////////////////////////////
430
void multimodel :: render(GemState *state)
431
{
432 433 434
  if(!m_loader) {
    return;
  }
435

436 437
  if ( !m_position.vbo || !m_texture.vbo || !m_color.vbo || !m_normal.vbo
       || m_size_change_flag ) {
438 439 440 441
    createVBO();
    m_size_change_flag = false;
  }
  getVBOarray();
442

443
  std::vector<unsigned int> sizeList;
444

445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
  if(m_position.render()) {
    glVertexPointer(m_position.dimen, GL_FLOAT, 0, 0);
    glEnableClientState(GL_VERTEX_ARRAY);
    sizeList.push_back(m_position.size);
  }
  if(m_texture.render()) {
    glTexCoordPointer(m_texture.dimen, GL_FLOAT, 0, 0);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    sizeList.push_back(m_texture.size);
  }
  if(m_color.render()) {
    glColorPointer(m_color.dimen, GL_FLOAT, 0, 0);
    glEnableClientState(GL_COLOR_ARRAY);
    sizeList.push_back(m_color.size);
  }
  if(m_normal.render()) {
    glNormalPointer(GL_FLOAT, 0, 0);
    glEnableClientState(GL_NORMAL_ARRAY);
    sizeList.push_back(m_normal.size);
464
  }
465

466 467
  if ( sizeList.size() > 0 ) {
    unsigned int npoints = *std::min_element(sizeList.begin(),sizeList.end());
468
    glDrawArrays(m_drawType, 0, npoints);
469 470 471 472 473 474 475 476 477 478 479 480 481
  }

  if ( m_position.enabled ) {
    glDisableClientState(GL_VERTEX_ARRAY);
  }
  if ( m_color.enabled    ) {
    glDisableClientState(GL_COLOR_ARRAY);
  }
  if ( m_texture.enabled  ) {
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  }
  if ( m_normal.enabled   ) {
    glDisableClientState(GL_NORMAL_ARRAY);
482
  }
483 484 485 486 487 488 489 490
}

/////////////////////////////////////////////////////////
// static member function
//
/////////////////////////////////////////////////////////
void multimodel :: obj_setupCallback(t_class *classPtr)
{
491
  CPPEXTERN_MSG4(classPtr, "open", openMess, std::string, float, float, float);
492
  CPPEXTERN_MSG1(classPtr, "mdl_num", changeModel, int);
493

494 495
  CPPEXTERN_MSG1(classPtr, "rescale", rescaleMess, bool);
  CPPEXTERN_MSG1(classPtr, "smooth", smoothMess, float);
496 497 498 499 500 501
  CPPEXTERN_MSG1(classPtr, "revert", reverseMess, bool);
  CPPEXTERN_MSG1(classPtr, "material", materialMess, int);
  CPPEXTERN_MSG1(classPtr, "texture", textureMess, int);
  CPPEXTERN_MSG1(classPtr, "group", groupMess, int);
  CPPEXTERN_MSG (classPtr, "loader", backendMess);

502 503
  CPPEXTERN_MSG1(classPtr, "draw", drawMess, std::string);
}
504 505 506 507 508 509 510 511 512

void multimodel :: createVBO(void)
{
  m_position.create();
  m_texture .create();
  m_color   .create();
  m_normal  .create();
}

513
void multimodel :: copyArray(const std::vector<std::vector<float> >&tab,
514
                             gem::VertexBuffer&vb)
515 516 517 518
{
  unsigned int size(0), i(0), npts(0);

  //~std::vector<std::vector<float> > tab = m_loader->getVector(vectorName);
519 520 521
  if ( tab.empty() ) {
    return;
  }
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
  size=tab.size();

  if(size!=vb.size) {
    vb.resize(size);
    m_size_change_flag=true;
  }

  for ( i = 0 ; i < size ; i++ ) {
    for ( int j=0 ; j< std::min(vb.dimen,(unsigned int)tab[i].size()) ; j++) {
      vb.array[i*vb.dimen + j] = tab[i][j];
    }
  }
  vb.dirty=true;
  vb.enabled=true;
}

538 539 540
void multimodel :: copyAllArrays()
{
  if (m_loader && m_loader->needRefresh()) {
541 542 543 544 545 546 547 548
    copyArray(m_loader->getVector("vertices"), m_position);
    copyArray(m_loader->getVector("texcoords"), m_texture);
    copyArray(m_loader->getVector("normals"), m_normal);
    copyArray(m_loader->getVector("colors"), m_color);
    m_loader->unsetRefresh();
  }
}

549 550 551
void multimodel :: getVBOarray()
{
  if (m_loader && m_loader->needRefresh()) {
552

553 554
    std::vector<gem::plugins::modelloader::VBOarray>  vboArray =
      m_loader->getVBOarray();
555

556
    if ( vboArray.empty() ) {
557 558
      copyAllArrays();
    } else {
559 560
      for (int i = 0; i<vboArray.size(); i++) {
        switch (vboArray[i].type) {
IOhannes m zmölnig's avatar
IOhannes m zmölnig committed
561 562 563 564 565 566 567 568 569 570 571 572 573 574
        case gem::VertexBuffer::GEM_VBO_VERTICES:
          copyArray(*vboArray[i].data, m_position);
          break;
        case gem::VertexBuffer::GEM_VBO_TEXCOORDS:
          copyArray(*vboArray[i].data, m_texture);
          break;
        case gem::VertexBuffer::GEM_VBO_NORMALS:
          copyArray(*vboArray[i].data, m_normal);
          break;
        case gem::VertexBuffer::GEM_VBO_COLORS:
          copyArray(*vboArray[i].data, m_color);
          break;
        default:
          error("VBO type %d not supported\n",vboArray[i].type);
575 576 577 578 579 580
        }
      }
      m_loader->unsetRefresh();
    }
  }
}