MeshCompiler.hh 22 KB
Newer Older
1 2 3 4 5 6
#pragma once

#include "VertexDeclaration.hh"

#include <map>
#include <vector>
7
#include <cstdio>
8
#include <string>
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 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 167 168 169 170

/*

Mesh buffer assembler:

Builds a pair of vertex and index buffer based on a poly mesh.


- flexible processing pipeline
- uses index mapping only -> lower memory consumption
- independent of OpenMesh, OpenGL
- 



usage

1. Create a vertex declaration to specify your wanted
   vertex format, such as float3 pos, float3 normal..

2. Set your vertex data.
   Example in (float3 pos, float3 normal, float2 texc) format:
   
   float VertexPositions[100*3] = {..};
   float VertexNormals[120*3] = {..};
   float VertexUV[80*2] = {..};

   drawMesh->setVertices(100, VertexPositions, 12);
   drawMesh->setNormals(120, VertexNormals, 12);
   drawMesh->setTexCoords(80, VertexUV, 8);

   Note that different indices for vertices, normals and texcoords are allowed,
   hence the various element numbers 100, 120 and 80.


   Example 2 (interleaved input)

   float Vertices[100] = {
                            x0, y0, z0,   u0, v0,   nx0, ny0, nz0,
                            x1, y1, z1,   u1, v1,   nx1, ny1, nz1,
                            ...
                          };

   The stride is 8*4 = 32 bytes.
   We use parameters as follows.

   drawMesh->setVertices(100, Vertices, 32);
   drawMesh->setNormals(100, (char*)Vertices + 20, 32);
   drawMesh->setTexCoords(100, (char*)Vertices + 12, 32);
   
3. Set index data.

   Two methods are supported for this.

   You can either specify one index set for all vertex attributes
   or use another index buffer for each vertex attribute.
   The latter means having different indices for vertex and texcoords for example.


   drawMesh->setNumFaces(32, 96);


   for each face i
     int* faceVertexIndices = {v0, v1, v2, ...};
     setFaceVerts(i, 3, faceVertexIndices);

4. finish the initialization by calling the build() function

*/

namespace ACG{

class MeshCompilerFaceInput
{
  // face data input interface
  // allows flexible and memory efficient face data input

public:
  MeshCompilerFaceInput(){}
  virtual ~MeshCompilerFaceInput(){}

  virtual int getNumFaces() = 0;

  /** Get total number of indices in one attribute channel.
   *
   * i.e. total number of position indices of the whole mesh
  */
  virtual int getNumIndices() = 0;

  /** Get number of vertices per face.
   * @param _faceID face index
  */
  virtual int getFaceSize(int _faceID) const = 0;

  /** Get a single vertex-index entry of a face.
   *
   * @param _faceID face index
   * @param _faceCorner vertex corner of the face
   * @param _attrID attribute channel 
   * @return index-data if successful, -1 otherwise
  */
  virtual int getSingleFaceAttr(int _faceID, int _faceCorner, int _attrID);

  /** Get an index buffer of a face for a specific attribute channel.
   * @param _faceID face index
   * @param _attrID attribute channel
   * @param _out pointer to output buffer, use getFaceSize(_faceID) to get the size needed to store face data
   * @return true if successful, false otherwise
  */
  virtual bool getFaceAttr(int _faceID, int _attrID, int* _out) {return false;}

  /** Get an index buffer of a face for a specific attribute channel.
   * @param _faceID face index
   * @param _attrID attribute channel
   * @return array data of size "getFaceSize(_faceID)", allowed to return 0 when array data not permanently available in memory
  */
  virtual int* getFaceAttr(int _faceID, int _attrID) {return 0;}
};

class MeshCompilerDefaultFaceInput : public MeshCompilerFaceInput
{
public:
  MeshCompilerDefaultFaceInput(int _numFaces, int _numIndices);
  virtual ~MeshCompilerDefaultFaceInput(){}

  int getNumFaces() {return numFaces_;}
  int getNumIndices() {return numIndices_;}

  int getFaceSize(int _faceID) const {return faceSize_[_faceID];}

  int getSingleFaceAttr(int _faceID, int _faceCorner, int _attrID);

  bool getFaceAttr(int _faceID, int _attrID, int* _out);

  void dbgWriteToObjFile(FILE* _file, int _posAttrID = 0, int _normalAttrID = -1, int _texcAttrID = -1);


  void setFaceData(int _faceID, int _size, int* _data, int _attrID = 0);

protected:

  int numFaces_,
    numIndices_;

  // input data is stored in a sequence stream
  //  face offsets may not be in sequence
  std::vector<int> faceOffset_;
  std::vector<int> faceSize_;

  // face index buffer for each vertex attribute
  std::vector<int> faceData_[16];

};

class MeshCompiler
{
public:

  MeshCompiler(const VertexDeclaration& _decl);

  virtual ~MeshCompiler();

171 172 173 174 175
//===========================================================================
/** @name Vertex Data Input
* @{ */
//===========================================================================  

176 177 178 179 180 181 182 183 184 185
  /** set input vertex positions
   *
   * @param _num Number of vertex positions
   * @param _data Pointer to vertex data
   * @param _stride Difference in bytes between two vertex positions in _data. Default value 0 indicates a tight float3 position array without any other data or memory alignment.
   * @param _internalCopy Memory optimization flag: select true if the provided data address is only temporarily valid. Otherwise an internal copy must be made.
  */
  void setVertices(int _num, const void* _data, int _stride = 0, bool _internalCopy = false);

  /** set input normals
186 187 188 189 190
   *
   * @param _num Number of normals
   * @param _data Pointer to normals data
   * @param _stride Difference in bytes between two normals positions in _data. Default value 0 indicates a tight float3 position array without any other data or memory alignment.
   * @param _internalCopy Memory optimization flag: select true if the provided data address is only temporarily valid. Otherwise an internal copy must be made.
191 192 193 194
  */
  void setNormals(int _num, const void* _data, int _stride = 0, bool _internalCopy = false);

  /** set input texture coords
195 196 197 198 199
   *
   * @param _num Number of texture coords
   * @param _data Pointer to texture coord data
   * @param _stride Difference in bytes between two texture coordinate positions in _data. Default value 0 indicates a tight float3 position array without any other data or memory alignment.
   * @param _internalCopy Memory optimization flag: select true if the provided data address is only temporarily valid. Otherwise an internal copy must be made.
200 201 202 203 204 205
  */
  void setTexCoords(int _num, const void* _data, int _stride = 0, bool _internalCopy = false);

  /** Set custom input attribute.
  *
  * Alternatively allocates an internal buffer only, such that data can be provided via setAttrib().
206 207 208 209
  * @param _attrIdx      Attribute id from VertexDeclaration
  * @param _num          Number of attributes
  * @param _data         Input data buffer, may be null to only
  * @param _stride       Offset difference in bytes to the next attribute in _data. Default value 0 indicates no data alignment/memory packing.
210 211 212 213 214 215 216 217 218 219 220 221 222
  * @param _internalCopy Create an internal buffer and make a copy _data
  */
  void setAttribVec(int _attrIdx, int _num, const void* _data, int _stride = 0, bool _internalCopy = false);

  /** set one single vertex
      setVertices with internalCopy = true must be called before
      to have an effect
  */
  void setVertex(int _v, float* _f);
  void setVertex(int _v, float _x, float _y, float _z, float _w);

  void setAttrib(int _attrIdx, int _v, const void* _data);

223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
/** @} */  


//===========================================================================
/** @name Flexible Face Data Input
* @{ */
//===========================================================================  

  /** Set Face data input
   *
   * Making use of the MeshCompilerFaceInput interface completly overrides the default input behavior.
   * Any subsequent call to default input data functions such as setNumFaces(), setFaceVerts() etc. will be ignored
   *
   * @param _faceInput user defined face input (no internal copy made, do not delete while using MeshCompiler)
   */
  void setFaceInput(MeshCompilerFaceInput* _faceInput);

/** @} */  

//===========================================================================
/** @name Default Face Data Input
* @{ */
//===========================================================================  
246

247
  /** \brief Set number of faces and indices if known by user
248
   *
249 250 251 252
   * User may give a rough estimate of face/index count. 
   * A more accurate estimation improves efficiency: too low numbers result in performance hit, too high numbers in memory consumption
   * @param _numFaces Number of faces. Value 0 accepted at cost of performance
   * @param _numIndices Number of indices, i.e. 3 * numFaces for triangle meshes. Value 0 accepted at cost of performance
253 254 255 256
   */
  void setNumFaces(const int _numFaces, const int _numIndices);


257
  /** \brief Set index buffer for a triangle mesh.
258 259 260 261 262 263 264 265
   *
   * This should only be used if the input vertex buffer is interleaved already.
   * @param _numTris Number of triangles.
   * @param _indexSize Size in bytes of one index.
   * @param _indices Pointer to a buffer containing the index data.
   */
  void setIndexBufferInterleaved(int _numTris, int _indexSize, const void* _indices);

266
  /** \brief Set vertex ids per triangle.
267 268 269 270 271 272
   *
   * @param _i Face ID
   * @param _v0 1st vertex id
   * @param _v1 2nd vertex id
   * @param _v2 3rd vertex id
   */
273 274
  void setFaceVerts(int _i, int _v0, int _v1, int _v2);

275
  /** \brief Set vertex ids per face.
276 277 278 279 280 281 282
   *
   * @param _i Face id
   * @param _faceSize Size of face, ie. number of vertices of face
   * @param _v Vertex ids
   */
  void setFaceVerts(int _i, int _faceSize, int* _v);

283
  /** \brief Set normal ids per triangle.
284 285 286 287 288 289
   *
   * @param _i Face ID
   * @param _v0 1st normal id
   * @param _v1 2nd normal id
   * @param _v2 3rd normal id
   */
290
  void setFaceNormals(int _i, int _v0, int _v1, int _v2);
291
  
292
  /** \brief Set normal ids per face.
293 294 295 296 297 298
   *
   * @param _i Face id
   * @param _faceSize Size of face, ie. number of vertices of face
   * @param _v Normal ids
   */
  void setFaceNormals(int _i, int _faceSize, int* _v);
299

300
  /** \brief Set texcoord ids per triangle.
301 302 303 304 305 306
   *
   * @param _i Face ID
   * @param _v0 1st texcoord id
   * @param _v1 2nd texcoord id
   * @param _v2 3rd texcoord id
   */
307 308
  void setFaceTexCoords(int _i, int _v0, int _v1, int _v2);

309
  /** \brief Set texcoord ids per face.
310 311 312 313 314 315 316 317
   *
   * @param _i Face id
   * @param _faceSize Size of face, ie. number of vertices of face
   * @param _v Texcoord ids
   */
  void setFaceTexCoords(int _i, int _faceSize, int* _v);


318
  /** \brief Set attribute ids per triangle.
319 320 321 322 323 324 325
   *
   * @param _i Face id
   * @param _v0 1st element id
   * @param _v1 2nd element id
   * @param _v2 3rd element id
   * @param _attrID Which attribute: index of VertexDeclaration element array
   */
326 327
  void setFaceAttrib(int _i, int _v0, int _v1, int _v2, int _attrID);

328
  /** \brief Set attribute ids per face.
329
   *
330
   * @param _i        Face id
331
   * @param _faceSize Size of face, ie. number of vertices of face
332 333
   * @param _v        Element ids
   * @param _attrID   Which attribute: index of VertexDeclaration element array
334 335 336 337 338 339 340 341 342 343 344
   */
  void setFaceAttrib(int _i, int _faceSize, int* _v, int _attrID);


/** @} */  

//===========================================================================
/** @name Face Grouping and Subsets
* @{ */
//===========================================================================  

345

346
  /** \brief Specify face groups.
347 348 349
   *
   * Faces with the same group ID will be chunked together in the sorting process.
   * This feature may be used for material/texture subsets.
350
   * @param _i       Face ID
351 352 353 354
   * @param _groupID Custom group ID
   */
  void setFaceGroup(int _i, int _groupID);

355 356
  // subset/group management
  struct Subset
357
  {
358 359 360 361 362 363 364 365
    int id; // subset id
    unsigned int startIndex; // 1st occurrence of group in index buffer
    unsigned int numTris; // number of tris belonging to subset in index buffer

    unsigned int numFaces; // number of faces belonging to subset
    unsigned int startFace; // index into sorted list of faces
  };

366 367 368 369 370
  /** \brief get subset ID of a group
   *
   * @param _groupID Id of the group
   * @return Subset Id
   */
371
  int findGroupSubset(int _groupID);
372

373 374 375 376 377
  /** \brief Get Face Group of the given face
   *
   * @param _faceID Id of the face
   * @return Group Id
   */
378
  int getFaceGroup(int _faceID) const;
379 380 381 382 383 384

  /** \brief Get Group Id of the triangle
   *
   * @param _triID Id of the triangle
   * @return Group of the triangle
   */
385 386
  int getTriGroup(int _triID) const;

387 388 389 390
  /** \brief Get the number of subsets
   *
   * @return Number of subsets
   */
391
  int getNumSubsets() const {return (int)subsets_.size();}
392 393 394 395 396 397

  /** \brief get a specific subset
   *
   * @param _i  Id of the subset
   * @return    The subset
   */
398 399 400 401
  const Subset* getSubset(int _i) const;


/** @} */  
402

403 404 405 406 407 408
//===========================================================================
/** @name Mesh Compilation
* @{ */
//===========================================================================  


409
  /** \brief Build vertex + index buffer.
410
   * 
411 412
   * @param _optimizeVCache Reorder faces for optimized vcache usage. Low performance hit on build() execution time
   * @param _needPerFaceAttribute User wants to set per-face attributes in draw vertex buffer. The first referenced vertex of each face can be used to store per-face data. High performance hit on execution time
413 414 415 416
  */
  void build(bool _optimizeVCache = true, bool _needPerFaceAttribute = false);


417
  /** \brief Get vertex buffer ready for rendering.
418 419 420 421 422 423 424 425 426
   * 
   * Query final vertex buffer data.
   * Support vertex buffer batch uploads.
   * @param _dst [out] Pointer to memory address where the vertex buffer should be copied to
   * @param _offset Begin of vertex buffer batch
   * @param _range Size of vertex buffer batch. Copies rest of buffer if _range < 0.
  */
  void getVertexBuffer(void* _dst, const int _offset = 0, const int _range = -1);

427
  /** Get index buffer ready for rendering.
428
  */
429
  int* getIndexBuffer() const {return indices_;}
430 431 432 433 434

  /** Get number of triangles in final buffer.
  */
  int getNumTriangles() const;

435 436 437 438
  /** Get number of input faces.
  */
  int getNumFaces() const;

439 440 441 442 443
  /** \brief Get size of input face
   *
   * @param _i Index
   * @return Size
   */
444 445 446 447 448
  inline int getFaceSize(const int _i) const
  {
    return faceSize_[_i];
  }

449 450 451 452 453 454 455 456
  /** Get vertex in final draw vertex buffer.
  */
  void getVertex(int _id, void* _out) const;

  /** Get index in final draw index buffer.
  */
  int getIndex(int _i) const;

457 458 459 460 461 462 463 464 465 466 467

/** @} */  



//===========================================================================
/** @name Input/Output ID mapping
* @{ */
//===========================================================================  


468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
  /** Mapping from draw vertex id -> input vertex id
   *
   * @param _i Vertex ID in draw buffer
   * @param _faceID [out] Face ID in face input buffer
   * @param _cornerID [out] Corner of face corresponding to vertex.
  */
  void mapToOriginalVertexID(const int _i, int& _faceID, int& _cornerID) const;

  /** Mapping from draw tri id -> input face id
   *
   * @param _triID Triangle ID in draw index buffer
   * @return Input Face ID
  */
  int mapToOriginalFaceID(const int _triID) const;



  /** Mapping from input vertex id -> draw vertex id
   *
   * @param _faceID Face ID in input data
   * @param _cornerID Corner of face
   * @return Draw Vertex ID in output vertex buffer
  */
  int mapToDrawVertexID(const int _faceID, const int _cornerID) const;

  /** Mapping from input Face id -> draw vertex id
   *
   * @param _faceID Face ID in input data
   * @param _k triangle no. associated to face, offset 0
   * @param _numTrisOut [out] Number of triangles associated to face (if input face was n-poly)
   * @return Draw Triangle ID in output vertex buffer
  */
  int mapToDrawTriID(const int _faceID, const int _k = 0, int* _numTrisOut = 0) const;


503
/** @} */  
504 505 506 507 508 509 510





private:

511
  // compute adjacency information: vertex -> neighboring faces, face -> neighboring faces
512 513
  void computeAdjacency();

514
  // convert per-face vertices to unique ids
515 516 517 518 519 520 521 522 523 524
  void splitVertices();

private:

  // small helper functions

  /** i: face index
      j: corner index
      _out: output vertex (index for each attribute)
  */
525
  void getInputFaceVertex(int _face, int _corner, int* _out) const;
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582

  int getInputIndex(const int _face, const int _corner, const int _attrId) const;

private:

  // ====================================================
  // input data

  // vertex buffer input

  struct VertexElementInput 
  {
    VertexElementInput();
    ~VertexElementInput();

     /// mem alloc if attribute buffer managed by this class
    char* internalBuf;

    /** address to data input, will not be released by MeshCompiler
        - may be an external address provided by user of class
    */
    const char* data;

    /// # elements in buffer
    int count;

    /// offset in bytes from one element to the next
    int stride;

    /// size in bytes of one attribute
    int attrSize;


    // vertex data access

    /// read a vertex element
    void getElementData(int _idx, void* _dst) const;
  };
  
  // input vertex data
  VertexElementInput  input_[16];

  // convenient attribute indices
  int inputIDPos_;  // index of positions into input_ array
  int inputIDNorm_; // index of normals into input_ array
  int inputIDTexC_; // index of texcoords into input_ array

  int                 numAttributes_;
  VertexDeclaration   decl_;


  // input face data

  int   numFaces_, 
        numIndices_;
  std::vector<int>  faceStart_;    // start position in buf for each face
  std::vector<short> faceSize_;    // face size, copy of faceInput_->getFaceSize() for better performance
583
  size_t   maxFaceCorners_;           // max(faceCorners_)
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
  std::vector<int>  faceGroupIDs_; // group id for each face (optional input)
  int   curFaceInputPos_;          // current # indices set by user

  MeshCompilerFaceInput* faceInput_;   // face data input interface
  bool deleteFaceInputeData_;       // delete if face input data internally created


  std::vector<int>  faceBufSplit_; // index buffer for the interleaved vertex buffer
  std::vector<int>  faceRotCount_; // # rotation ccw face rotation applied, handled internally by getInputIndexOffset
  std::vector<int>  faceSortMap_;  // face IDs sorted by group; maps sortFaceID -> FaceID

  int   numTris_;
  std::vector<int>  triIndexBuffer_; // triangulated index buffer with interleaved vertices



  // face grouping with subsets for per-face materials
  int     numSubsets_;
  std::vector<Subset> subsets_;
  std::map<int, int> subsetIDMap_; // maps groupId -> subsetID

  // =====================================================

  struct AdjacencyList 
  {
    AdjacencyList();
    ~AdjacencyList();

    void init(int n);
    int  getAdj(int i, int k) const;
    int  getCount(int i) const;

    int* start;   // index to adjacency buffer
    int* count;   // # of adjacent faces
    int* buf;     // adjacency data
    int  bufSize; // size of buf
    int  num;     // # adjacency entries

    void dbgdump(FILE* file) const;
  };

  // adjacency list: vertex -> faces
  AdjacencyList adjacencyVert_;

  // adjacency: face -> faces
  AdjacencyList adjacencyFace_;



  struct VertexSplitter 
  {
    // worst case split: num entries in vertex adj list
    // estBufferIncrease: if numWorstCase == 0, then we estimate an increase in vertex buffer by this percentage
    VertexSplitter(int numAttribs,
                   int numVerts,
                   int numWorstCase = 0,
                   float estBufferIncrease = 0.5f);

    ~VertexSplitter();

    /// returns a unique index for a vertex-attribute combination
    int split(int* vertex);

    int  numAttribs;

    /// number of vertex combinations currently in use
    int  numVerts;

    /** split list format:
         for each vertex: [next split,  attribute ids]
          next split: -1 -> not split yet
                       i -> index into split list for next combination
                             with the same vertex position id (single linked list)

          attribute ids:
            array of attribute indices into input buffers,
            that makes up the complete vertex
            -1 -> vertex not used yet (relevant for split() only)
    */
//    int* splits;
    std::vector<int> splits;

    // split list access
    int  getNext(int id);
    int* getAttribs(int id);
    void setNext(int id, int next);
    void setAttribs(int id, int* attr);
  };

  VertexSplitter*  splitter_;

  // =====================================================

  // mappings

  /// maps from triangle ID to sorted face ID
  std::vector<int> triToSortFaceMap_;

  /// maps from optimized tri ID to unoptimized tri ID
  std::vector<int> triOptMap_;

  /// vertex index in vbo -> input (face id, corner id) pair
  std::vector<std::pair<int, int> > vertexMap_;

  /// input face index -> output tri index
  std::vector<int> faceToTriMap_;

  // =====================================================

  // final buffers used for drawing

  /// # vertices in vbo
  int numDrawVerts_;

  /// index buffer
  int*  indices_;

private:

  // return interleaved vertex id for input buffers
  int getInputIndexSplit(const int _face, const int _corner) const;

  void setInputIndexSplit(const int _face, const int _corner, const int _val);

  int mapTriToInputFace(int _tri);

  int getInputIndexOffset(const int _face, const int _corner, const bool _rotation = true) const;

712 713 714 715 716 717

  /// build() preparation
  void prepareData();

  // make sure each face has one vertex id without any references by neighboring faces
  // split vertices when necessary
718 719
  void forceUnsharedFaceVertex();

720
  // convert n-poly -> tris (triangle fans)
721 722
  void triangulate();

723
  // sort input faces by group ids
724 725
  void sortFacesByGroup();

726
  // v-cache optimization + vertex reorder
727 728
  void optimize();

729
  // create vertex mapping: input id <-> final buffer id
730
  void createVertexMap();
731 732

  // create face mapping: input id <-> final tri id
733 734 735
  void createFaceMap();

public:
736 737 738
  // debugging tools

  /// dump mesh info to text file
739
  void dbgdump(const char* _filename) const;
740 741

  /// dump mesh in wavefront obj format
742
  void dbgdumpObj(const char* _filename) const;
743 744

  /// dump adjacency list to text file
745 746
  void dbgdumpAdjList(const char* _filename) const;

747 748
  /// return memory consumption in bytes
  size_t getMemoryUsage() const;
749

750 751
  /// check for errors in input data
  std::string checkInputData() const;
752 753 754 755 756
};



}