bsp.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. #include "bsp.h"
  2. #include "atlas.h"
  3. #include "vbsp.h"
  4. #include "collection.h"
  5. #include "mempools.h"
  6. #include "common.h"
  7. // DEBUG
  8. #include "texture.h"
  9. #define R2S(r) bspLoadResultString(r)
  10. const char *bspLoadResultString(enum BSPLoadResult result) {
  11. switch(result) {
  12. case BSPLoadResult_Success: return "BSPLoadResult_Success";
  13. case BSPLoadResult_ErrorFileOpen: return "BSPLoadResult_ErrorFileOpen";
  14. case BSPLoadResult_ErrorFileFormat: return "BSPLoadResult_ErrorFileFormat";
  15. case BSPLoadResult_ErrorMemory: return "BSPLoadResult_ErrorMemory";
  16. case BSPLoadResult_ErrorTempMemory: return "BSPLoadResult_ErrorTempMemory";
  17. case BSPLoadResult_ErrorCapabilities: return "BSPLoadResult_ErrorCapabilities";
  18. default: return "UNKNOWN";
  19. }
  20. }
  21. struct AnyLump {
  22. const void *p;
  23. uint32_t n;
  24. };
  25. struct Lumps {
  26. uint32_t version;
  27. #define LIST_LUMPS \
  28. BSPLUMP(Entity, char, entities); \
  29. BSPLUMP(Plane, struct VBSPLumpPlane, planes); \
  30. BSPLUMP(TexData, struct VBSPLumpTexData, texdata); \
  31. BSPLUMP(Vertex, struct VBSPLumpVertex, vertices); \
  32. \
  33. BSPLUMP(Node, struct VBSPLumpNode, nodes); \
  34. BSPLUMP(TexInfo, struct VBSPLumpTexInfo, texinfos); \
  35. BSPLUMP(Face, struct VBSPLumpFace, faces); \
  36. BSPLUMP(LightMap, struct VBSPLumpLightMap, lightmaps); \
  37. \
  38. BSPLUMP(Leaf, struct VBSPLumpLeaf, leaves); \
  39. \
  40. BSPLUMP(Edge, struct VBSPLumpEdge, edges); \
  41. BSPLUMP(Surfedge, int32_t, surfedges); \
  42. BSPLUMP(Model, struct VBSPLumpModel, models); \
  43. \
  44. BSPLUMP(LeafFace, uint16_t, leaffaces); \
  45. \
  46. BSPLUMP(DispInfo, struct VBSPLumpDispInfo, dispinfos); \
  47. \
  48. BSPLUMP(DispVerts, struct VBSPLumpDispVert, dispverts); \
  49. \
  50. BSPLUMP(PakFile, uint8_t, pakfile); \
  51. \
  52. BSPLUMP(TexDataStringData, char, texdatastringdata); \
  53. BSPLUMP(TexDataStringTable, int32_t, texdatastringtable);
  54. #define BSPLUMP(name,type,field) struct{const type *p;uint32_t n;} field
  55. LIST_LUMPS
  56. #undef BSPLUMP
  57. };
  58. /* data needed for making lightmap atlas */
  59. struct Face {
  60. const struct VBSPLumpFace *vface;
  61. /* read directly from lumps */
  62. int vertices;
  63. int indices;
  64. int width, height;
  65. const struct VBSPLumpLightMap *samples;
  66. const struct VBSPLumpTexInfo *texinfo;
  67. const struct VBSPLumpTexData *texdata;
  68. const struct VBSPLumpDispInfo *dispinfo;
  69. int dispquadvtx[4]; // filled only when displaced
  70. int dispstartvtx;
  71. const struct Material *material;
  72. /* filled as a result of atlas allocation */
  73. int atlas_x, atlas_y;
  74. };
  75. struct LoadModelContext {
  76. struct Stack *tmp;
  77. struct ICollection *collection;
  78. const struct Lumps *lumps;
  79. const struct VBSPLumpModel *model;
  80. struct Face *faces;
  81. int faces_count;
  82. int vertices;
  83. int indices;
  84. int max_draw_vertices;
  85. struct {
  86. int pixels;
  87. int max_width;
  88. int max_height;
  89. AGLTexture texture;
  90. } lightmap;
  91. int draws_to_alloc;
  92. };
  93. /* TODO change this to Ok|Skip|Inconsistent,
  94. * print verbose errors for inconsistent */
  95. enum FacePreload {
  96. FacePreload_Ok,
  97. FacePreload_Skip,
  98. FacePreload_Inconsistent
  99. };
  100. static inline int shouldSkipFace(const struct VBSPLumpFace *face, const struct Lumps *lumps) {
  101. (void)(face); (void)(lumps);
  102. //const struct VBSPLumpTexInfo *tinfo = lumps->texinfos.p + face->texinfo;
  103. return /*(tinfo->flags & (VBSP_Surface_NoDraw | VBSP_Surface_NoLight)) ||*/ face->lightmap_offset == 0xffffffffu
  104. || face->lightmap_offset < 4;
  105. }
  106. static enum FacePreload bspFacePreloadMetadata(struct LoadModelContext *ctx,
  107. struct Face *face, unsigned index) {
  108. const struct Lumps * const lumps = ctx->lumps;
  109. #define FACE_CHECK(cond) \
  110. if (!(cond)) { PRINTF("F%d: check failed: (%s)", index, #cond); return FacePreload_Inconsistent; }
  111. FACE_CHECK(index < lumps->faces.n);
  112. const struct VBSPLumpFace * const vface = lumps->faces.p + index;
  113. face->vface = vface;
  114. if (vface->texinfo < 0) return FacePreload_Skip;
  115. FACE_CHECK((unsigned)vface->texinfo < lumps->texinfos.n);
  116. face->texinfo = lumps->texinfos.p + vface->texinfo;
  117. if (shouldSkipFace(vface, lumps)) return FacePreload_Skip;
  118. FACE_CHECK(face->texinfo->texdata < lumps->texdata.n);
  119. face->texdata = lumps->texdata.p + face->texinfo->texdata;
  120. FACE_CHECK(face->texdata->name_string_table_id < lumps->texdatastringtable.n);
  121. const int32_t texdatastringdata_offset = lumps->texdatastringtable.p[face->texdata->name_string_table_id];
  122. FACE_CHECK(texdatastringdata_offset >= 0 && (uint32_t)texdatastringdata_offset < lumps->texdatastringdata.n);
  123. /* FIXME validate string: has \0 earlier than end */
  124. const char *texture = lumps->texdatastringdata.p + texdatastringdata_offset;
  125. //PRINTF("F%u: texture %s", index, face->texture);
  126. face->material = materialGet(texture, ctx->collection, ctx->tmp);
  127. if (!face->material)
  128. return FacePreload_Skip;
  129. if (vface->dispinfo >= 0) {
  130. FACE_CHECK((unsigned)vface->dispinfo < lumps->dispinfos.n);
  131. face->dispinfo = lumps->dispinfos.p + vface->dispinfo;
  132. const int side = (1 << face->dispinfo->power) + 1;
  133. FACE_CHECK(vface->num_edges == 4);
  134. face->vertices = side * side;
  135. face->indices = (side - 1) * (side - 1) * 6; /* triangle list */
  136. if (face->dispinfo->min_tess != 0)
  137. PRINTF("Power: %d, min_tess: %d, vertices: %d",
  138. face->dispinfo->power, face->dispinfo->min_tess, face->vertices);
  139. face->dispstartvtx = 0;
  140. } else {
  141. face->dispinfo = 0;
  142. face->vertices = vface->num_edges;
  143. face->indices = (face->vertices - 2) * 3;
  144. }
  145. /* Check for basic reference consistency */
  146. FACE_CHECK(vface->plane < lumps->planes.n);
  147. FACE_CHECK(vface->num_edges > 2);
  148. FACE_CHECK(vface->first_edge < lumps->surfedges.n && lumps->surfedges.n - vface->first_edge >= (unsigned)vface->num_edges);
  149. FACE_CHECK(vface->lightmap_offset % sizeof(struct VBSPLumpLightMap) == 0);
  150. const int lm_width = vface->lightmap_size[0] + 1;
  151. const int lm_height = vface->lightmap_size[1] + 1;
  152. const unsigned lightmap_size = lm_width * lm_height;
  153. const unsigned sample_offset = vface->lightmap_offset / sizeof(struct VBSPLumpLightMap);
  154. FACE_CHECK(sample_offset < lumps->lightmaps.n && lumps->lightmaps.n - sample_offset >= lightmap_size);
  155. const int32_t *surfedges = lumps->surfedges.p + vface->first_edge;
  156. unsigned int prev_end = 0xffffffffu;
  157. for (int i = 0; i < vface->num_edges; ++i) {
  158. uint32_t edge_index;
  159. int istart;
  160. if (surfedges[i] >= 0) {
  161. edge_index = surfedges[i];
  162. istart = 0;
  163. } else {
  164. edge_index = -surfedges[i];
  165. istart = 1;
  166. }
  167. if (edge_index >= lumps->edges.n) {
  168. PRINTF("Error: face%u surfedge%u/%u references edge %u > max edges %u",
  169. index, i, vface->num_edges, edge_index, lumps->edges.n);
  170. return FacePreload_Inconsistent;
  171. }
  172. const unsigned int vstart = lumps->edges.p[edge_index].v[istart];
  173. const unsigned int vend = lumps->edges.p[edge_index].v[1^istart];
  174. if (face->dispinfo) {
  175. face->dispquadvtx[i] = vstart;
  176. if (fabs(lumps->vertices.p[vstart].x - face->dispinfo->start_pos.x) < .5f
  177. && fabs(lumps->vertices.p[vstart].y - face->dispinfo->start_pos.y) < .5f
  178. && fabs(lumps->vertices.p[vstart].z - face->dispinfo->start_pos.z) < .5f) {
  179. face->dispstartvtx = i;
  180. }
  181. }
  182. FACE_CHECK(vstart < lumps->vertices.n);
  183. FACE_CHECK(prev_end == 0xffffffffu || prev_end == vstart);
  184. prev_end = vend;
  185. }
  186. face->width = lm_width;
  187. face->height = lm_height;
  188. face->samples = lumps->lightmaps.p + sample_offset;
  189. if (lm_width > ctx->lightmap.max_width) ctx->lightmap.max_width = lm_width;
  190. if (lm_height > ctx->lightmap.max_height) ctx->lightmap.max_height = lm_height;
  191. ctx->lightmap.pixels += lightmap_size;
  192. ctx->vertices += face->vertices;
  193. ctx->indices += face->indices;
  194. ctx->faces_count++;
  195. return FacePreload_Ok;
  196. }
  197. const int c_max_draw_vertices = 65536;
  198. static enum BSPLoadResult bspLoadModelPreloadFaces(struct LoadModelContext *ctx) {
  199. ctx->faces = stackGetCursor(ctx->tmp);
  200. int current_draw_vertices = 0;
  201. for (int i = 0; i < ctx->model->num_faces; ++i) {
  202. struct Face face;
  203. const enum FacePreload result = bspFacePreloadMetadata(ctx, &face, ctx->model->first_face + i);
  204. if (result == FacePreload_Ok) {
  205. if (current_draw_vertices + face.vertices > c_max_draw_vertices) {
  206. if (ctx->max_draw_vertices < current_draw_vertices)
  207. ctx->max_draw_vertices = current_draw_vertices;
  208. ++ctx->draws_to_alloc;
  209. current_draw_vertices = 0;
  210. }
  211. current_draw_vertices += face.vertices;
  212. struct Face *stored_face = stackAlloc(ctx->tmp, sizeof(struct Face));
  213. if (!stored_face) {
  214. PRINTF("Error: cannot allocate %zu temp bytes", sizeof(struct Face));
  215. return BSPLoadResult_ErrorTempMemory;
  216. }
  217. *stored_face = face;
  218. continue;
  219. }
  220. if (result != FacePreload_Skip) {
  221. return BSPLoadResult_ErrorFileFormat;
  222. }
  223. }
  224. if (!ctx->faces_count) {
  225. PRINTF("Error: no visible faces found%s", "");
  226. return BSPLoadResult_ErrorFileFormat; /* FIXME handle this */
  227. }
  228. if (ctx->max_draw_vertices < current_draw_vertices)
  229. ctx->max_draw_vertices = current_draw_vertices;
  230. ++ctx->draws_to_alloc;
  231. return BSPLoadResult_Success;
  232. }
  233. static enum BSPLoadResult bspLoadModelLightmaps(struct LoadModelContext *ctx) {
  234. /* TODO optional sort lightmaps */
  235. struct AtlasContext atlas_context;
  236. atlas_context.temp_storage.ptr = stackGetCursor(ctx->tmp);
  237. atlas_context.temp_storage.size = stackGetFree(ctx->tmp);
  238. atlas_context.width = 16; /* TODO opengl caps */
  239. atlas_context.height = 16;
  240. atlas_context.rects = (void*)(&ctx->faces[0].width);
  241. atlas_context.rects_count = ctx->faces_count;
  242. atlas_context.rects_stride = sizeof(ctx->faces[0]);
  243. atlas_context.pos = (void*)(&ctx->faces[0].atlas_x);
  244. atlas_context.pos_stride = sizeof(ctx->faces[0]);
  245. while (atlas_context.width < (unsigned)ctx->lightmap.max_width) atlas_context.width <<= 1;
  246. while (atlas_context.height < (unsigned)ctx->lightmap.max_height) atlas_context.height <<= 1;
  247. while (atlas_context.width * atlas_context.height < (unsigned)ctx->lightmap.pixels)
  248. if (atlas_context.width < atlas_context.height) atlas_context.width <<= 1; else atlas_context.height <<= 1;
  249. for(;;) {
  250. const enum AtlasResult result = atlasCompute(&atlas_context);
  251. PRINTF("atlas: %u %u %u", atlas_context.width, atlas_context.height, result);
  252. if (result == Atlas_Success)
  253. break;
  254. if (result == Atlas_ErrorInsufficientTemp)
  255. return BSPLoadResult_ErrorTempMemory;
  256. if (atlas_context.width < atlas_context.height) atlas_context.width <<= 1; else atlas_context.height <<= 1;
  257. if (atlas_context.width > 2048 || atlas_context.height > 2048) /* TODO limit based on GL driver caps */
  258. return BSPLoadResult_ErrorCapabilities;
  259. }
  260. /* Build an atlas texture based on calculated fragment positions */
  261. const size_t atlas_size = sizeof(uint16_t) * atlas_context.width * atlas_context.height;
  262. uint16_t *const pixels = stackAlloc(ctx->tmp, atlas_size);
  263. if (!pixels) return BSPLoadResult_ErrorTempMemory;
  264. memset(pixels, 0x0f, atlas_size); /* TODO debug pattern */
  265. for (int i = 0; i < ctx->faces_count; ++i) {
  266. const struct Face *const face = ctx->faces + i;
  267. ASSERT((unsigned)face->atlas_x + face->width <= atlas_context.width);
  268. ASSERT((unsigned)face->atlas_y + face->height <= atlas_context.height);
  269. for (int y = 0; y < face->height; ++y) {
  270. for (int x = 0; x < face->width; ++x) {
  271. const struct VBSPLumpLightMap *const pixel = face->samples + x + y * face->width;
  272. unsigned int
  273. r = pixel->r,
  274. g = pixel->g,
  275. b = pixel->b;
  276. if (pixel->exponent >= 0) {
  277. r <<= pixel->exponent;
  278. g <<= pixel->exponent;
  279. b <<= pixel->exponent;
  280. } else {
  281. r >>= -pixel->exponent;
  282. g >>= -pixel->exponent;
  283. b >>= -pixel->exponent;
  284. }
  285. (r > 255) ? r = 255 : 0;
  286. (g > 255) ? g = 255 : 0;
  287. (b > 255) ? b = 255 : 0;
  288. pixels[face->atlas_x + x + (face->atlas_y + y) * atlas_context.width]
  289. = ((r&0xf8) << 8) | ((g&0xfc) << 3) | (b >> 3);
  290. } /* for x */
  291. } /* for y */
  292. } /* fot all visible faces */
  293. ctx->lightmap.texture = aGLTextureCreate();
  294. AGLTextureUploadData upload;
  295. upload.x = upload.y = 0;
  296. upload.width = atlas_context.width;
  297. upload.height = atlas_context.height;
  298. upload.format = AGLTF_U565_RGB;
  299. upload.pixels = pixels;
  300. aGLTextureUpload(&ctx->lightmap.texture, &upload);
  301. ctx->lightmap.texture.min_filter = AGLTmF_Nearest;
  302. /* pixels buffer is not needed anymore */
  303. stackFreeUpToPosition(ctx->tmp, pixels);
  304. return BSPLoadResult_Success;
  305. }
  306. static inline struct AVec3f aVec3fLumpVec(struct VBSPLumpVertex v) { return aVec3f(v.x, v.y, v.z); }
  307. #ifdef DEBUG_DISP_LIGHTMAP
  308. static int shouldSwapUV(struct AVec3f mapU, struct AVec3f mapV, const struct AVec3f *v) {
  309. float mappedU = 0.f, mappedV = 0.f;
  310. for (int i = 0; i < 4; ++i) {
  311. const float U = aVec3fDot(mapU, aVec3fSub(v[(i+1)%4], v[i]));
  312. if (U > mappedU) mappedU = U;
  313. const float V = aVec3fDot(mapV, aVec3fSub(v[(i+1)%4], v[i]));
  314. if (V > mappedV) mappedV = V;
  315. }
  316. const float dX1 = aVec3fLength2(aVec3fSub(v[3], v[0]));
  317. const float dX2 = aVec3fLength2(aVec3fSub(v[2], v[1]));
  318. const float dY1 = aVec3fLength2(aVec3fSub(v[1], v[0]));
  319. const float dY2 = aVec3fLength2(aVec3fSub(v[2], v[3]));
  320. const float maxDX = (dX1 > dX2) ? dX1 : dX2;
  321. const float maxDY = (dY1 > dY2) ? dY1 : dY2;
  322. //PRINTF("mappedU=%f mappedV=%f maxDX=%f, maxDY=%f", mappedU, mappedV, maxDX, maxDY);
  323. return (mappedU > mappedV) != (maxDX > maxDY);
  324. }
  325. #endif /* DEBUG_DISP_LIGHTMAP */
  326. static void bspLoadDisplacement(
  327. const struct LoadModelContext *ctx,
  328. const struct Face *face,
  329. struct BSPModelVertex *out_vertices, uint16_t *out_indices, int index_shift) {
  330. const int side = (1 << face->dispinfo->power) + 1;
  331. const struct VBSPLumpVertex *const vertices = ctx->lumps->vertices.p;
  332. const struct VBSPLumpTexInfo * const tinfo = face->texinfo;
  333. const struct VBSPLumpDispVert *const dispvert = ctx->lumps->dispverts.p + face->dispinfo->vtx_start;
  334. //if (face->dispstartvtx != 0) PRINTF("dispstartvtx = %d", face->dispstartvtx);
  335. const struct AVec3f vec[4] = { /* bl, tl, tr, br */
  336. aVec3fLumpVec(vertices[face->dispquadvtx[(face->dispstartvtx + 0)%4]]),
  337. aVec3fLumpVec(vertices[face->dispquadvtx[(face->dispstartvtx + 1)%4]]),
  338. aVec3fLumpVec(vertices[face->dispquadvtx[(face->dispstartvtx + 2)%4]]),
  339. aVec3fLumpVec(vertices[face->dispquadvtx[(face->dispstartvtx + 3)%4]])};
  340. /*
  341. const struct AVec3f ovec[4] = {
  342. aVec3fAdd(vec[0], aVec3fMulf(aVec3f(dispvert[0].x, dispvert[0].y, dispvert[0].z), dispvert[0].dist)),
  343. aVec3fAdd(vec[1], aVec3fMulf(aVec3f(dispvert[side*(side-1)].x, dispvert[side*(side-1)].y, dispvert[side*(side-1)].z), dispvert[side*(side-1)].dist)),
  344. aVec3fAdd(vec[2], aVec3fMulf(aVec3f(dispvert[side*side-1].x, dispvert[side*side-1].y, dispvert[side*side-1].z), dispvert[side*side-1].dist)),
  345. aVec3fAdd(vec[3], aVec3fMulf(aVec3f(dispvert[side-1].x, dispvert[side-1].y, dispvert[side-1].z), dispvert[side-1].dist))};
  346. */
  347. const struct AVec3f lm_map_u = aVec3f(
  348. tinfo->lightmap_vecs[0][0], tinfo->lightmap_vecs[0][1], tinfo->lightmap_vecs[0][2]);
  349. const float luxels_per_unit = aVec3fLength(lm_map_u);
  350. float length_lm_u = luxels_per_unit * floatMax(
  351. aVec3fLength(aVec3fSub(vec[3], vec[0])),
  352. aVec3fLength(aVec3fSub(vec[2], vec[1])));
  353. float length_lm_v = luxels_per_unit * floatMax(
  354. aVec3fLength(aVec3fSub(vec[1], vec[0])),
  355. aVec3fLength(aVec3fSub(vec[2], vec[3])));
  356. const struct AVec4f tex_map_u = aVec4f(
  357. tinfo->texture_vecs[0][0], tinfo->texture_vecs[0][1],
  358. tinfo->texture_vecs[0][2], tinfo->texture_vecs[0][3]);
  359. const struct AVec4f tex_map_v = aVec4f(
  360. tinfo->texture_vecs[1][0], tinfo->texture_vecs[1][1],
  361. tinfo->texture_vecs[1][2], tinfo->texture_vecs[1][3]);
  362. #ifdef DEBUG_DISP_LIGHTMAP
  363. const int swap = shouldSwapUV(
  364. aVec3f(tinfo->lightmap_vecs[0][0], tinfo->lightmap_vecs[0][1], tinfo->lightmap_vecs[0][2]),
  365. aVec3f(tinfo->lightmap_vecs[1][0], tinfo->lightmap_vecs[1][1], tinfo->lightmap_vecs[1][2]), vec);
  366. #endif /*ifdef DEBUG_DISP_LIGHTMAP*/
  367. const struct AVec2f atlas_scale = aVec2f(1.f / ctx->lightmap.texture.width, 1.f / ctx->lightmap.texture.height);
  368. const struct AVec2f atlas_offset = aVec2f(
  369. .5f + face->atlas_x /*+ tinfo->lightmap_vecs[0][3] - face->face->lightmap_min[0]*/,
  370. .5f + face->atlas_y /*+ tinfo->lightmap_vecs[1][3] - face->face->lightmap_min[1]*/);
  371. if (length_lm_u < 0. || length_lm_u >= face->width
  372. || length_lm_v < 0. || length_lm_v >= face->height) {
  373. PRINTF("LM OOB: (%f, %f) (%d, %d)", length_lm_u, length_lm_v, face->width, face->height);
  374. if (length_lm_u >= face->width) length_lm_u = face->width - 1;
  375. if (length_lm_v >= face->height) length_lm_v = face->height - 1;
  376. }
  377. /*
  378. PRINTF("%f %f %f %f",
  379. tinfo->lightmap_vecs[0][3] * atlas_scale.x, face->face->lightmap_min[0] * atlas_scale.x,
  380. tinfo->lightmap_vecs[1][3] * atlas_scale.y, face->face->lightmap_min[1] * atlas_scale.y);
  381. */
  382. const float div_side = 1.f / (side - 1);
  383. for (int y = 0; y < side; ++y) {
  384. const float ty = (float)y * div_side;
  385. const struct AVec3f vl = aVec3fMix(vec[0], vec[1], ty);
  386. const struct AVec3f vr = aVec3fMix(vec[3], vec[2], ty);
  387. for (int x = 0; x < side; ++x) {
  388. const float tx = (float)x * div_side;
  389. struct BSPModelVertex * const v = out_vertices + y * side + x;
  390. const struct VBSPLumpDispVert * const dv = dispvert + y * side + x;
  391. v->vertex = aVec3fMix(vl, vr, tx);
  392. v->lightmap_uv = aVec2f(tx * length_lm_u, ty * length_lm_v);
  393. v->base0_uv = aVec2f(
  394. aVec4fDot(aVec4f3(v->vertex, 1.f), tex_map_u),
  395. aVec4fDot(aVec4f3(v->vertex, 1.f), tex_map_v));
  396. v->vertex = aVec3fAdd(aVec3fMix(vl, vr, tx), aVec3fMulf(aVec3f(dv->x, dv->y, dv->z), dv->dist));
  397. if (v->lightmap_uv.x < 0 || v->lightmap_uv.y < 0 || v->lightmap_uv.x > face->width || v->lightmap_uv.y > face->height)
  398. PRINTF("Error: DISP OOB LM F:V%u: x=%f y=%f z=%f tx=%f, ty=%f u=%f v=%f w=%d h=%d",
  399. x + y * side, v->vertex.x, v->vertex.y, v->vertex.z, tx, ty, v->lightmap_uv.x, v->lightmap_uv.y, face->width, face->height);
  400. v->lightmap_uv = aVec2fMul(aVec2fAdd(v->lightmap_uv, atlas_offset), atlas_scale);
  401. #ifdef DEBUG_DISP_LIGHTMAP
  402. v->normal = aVec3f(face->dispstartvtx/3.f, swap, dv->dist / 100.f);
  403. #else
  404. /* FIXME normal */
  405. v->normal = aVec3ff(0.f);
  406. #endif
  407. }
  408. }
  409. for (int y = 0; y < side - 1; ++y) {
  410. for (int x = 0; x < side - 1; ++x) {
  411. const int base = index_shift + y * side + x;
  412. *out_indices++ = base;
  413. *out_indices++ = base + side + 1;
  414. *out_indices++ = base + side;
  415. *out_indices++ = base;
  416. *out_indices++ = base + 1;
  417. *out_indices++ = base + side + 1;
  418. }
  419. }
  420. }
  421. static void bspLoadFace(
  422. const struct LoadModelContext *ctx,
  423. const struct Face *face,
  424. struct BSPModelVertex *out_vertices, uint16_t *out_indices, int index_shift) {
  425. const struct VBSPLumpFace *vface = face->vface;
  426. const struct VBSPLumpTexInfo * const tinfo = face->texinfo;
  427. struct AVec3f normal;
  428. normal.x = ctx->lumps->planes.p[vface->plane].x;
  429. normal.y = ctx->lumps->planes.p[vface->plane].y;
  430. normal.z = ctx->lumps->planes.p[vface->plane].z;
  431. if (vface->side) normal = aVec3fNeg(normal);
  432. const struct AVec4f lm_map_u = aVec4f(
  433. tinfo->lightmap_vecs[0][0], tinfo->lightmap_vecs[0][1],
  434. tinfo->lightmap_vecs[0][2], tinfo->lightmap_vecs[0][3] - vface->lightmap_min[0]);
  435. const struct AVec4f lm_map_v = aVec4f(
  436. tinfo->lightmap_vecs[1][0], tinfo->lightmap_vecs[1][1],
  437. tinfo->lightmap_vecs[1][2], tinfo->lightmap_vecs[1][3] - vface->lightmap_min[1]);
  438. const struct AVec4f tex_map_u = aVec4f(
  439. tinfo->texture_vecs[0][0], tinfo->texture_vecs[0][1],
  440. tinfo->texture_vecs[0][2], tinfo->texture_vecs[0][3]);
  441. const struct AVec4f tex_map_v = aVec4f(
  442. tinfo->texture_vecs[1][0], tinfo->texture_vecs[1][1],
  443. tinfo->texture_vecs[1][2], tinfo->texture_vecs[1][3]);
  444. const int32_t * const surfedges = ctx->lumps->surfedges.p + vface->first_edge;
  445. for (int iedge = 0; iedge < vface->num_edges; ++iedge) {
  446. const uint16_t vstart = (surfedges[iedge] >= 0)
  447. ? ctx->lumps->edges.p[surfedges[iedge]].v[0]
  448. : ctx->lumps->edges.p[-surfedges[iedge]].v[1];
  449. const struct VBSPLumpVertex * const lv = ctx->lumps->vertices.p + vstart;
  450. struct BSPModelVertex * const vertex = out_vertices + iedge;
  451. vertex->vertex = aVec3f(lv->x, lv->y, lv->z);
  452. vertex->normal = normal;
  453. vertex->lightmap_uv = aVec2f(
  454. aVec4fDot(aVec4f3(vertex->vertex, 1.f), lm_map_u),
  455. aVec4fDot(aVec4f3(vertex->vertex, 1.f), lm_map_v));
  456. vertex->base0_uv = aVec2f(
  457. aVec4fDot(aVec4f3(vertex->vertex, 1.f), tex_map_u),
  458. aVec4fDot(aVec4f3(vertex->vertex, 1.f), tex_map_v));
  459. if (vertex->lightmap_uv.x < 0 || vertex->lightmap_uv.y < 0 || vertex->lightmap_uv.x > face->width || vertex->lightmap_uv.y > face->height)
  460. PRINTF("Error: OOB LM F:V%u: x=%f y=%f z=%f u=%f v=%f w=%d h=%d", iedge, lv->x, lv->y, lv->z, vertex->lightmap_uv.x, vertex->lightmap_uv.y, face->width, face->height);
  461. vertex->lightmap_uv.x = (vertex->lightmap_uv.x + face->atlas_x + .5f) / ctx->lightmap.texture.width;
  462. vertex->lightmap_uv.y = (vertex->lightmap_uv.y + face->atlas_y + .5f) / ctx->lightmap.texture.height;
  463. if (iedge > 1) {
  464. out_indices[(iedge-2)*3+0] = index_shift + 0;
  465. out_indices[(iedge-2)*3+1] = index_shift + iedge;
  466. out_indices[(iedge-2)*3+2] = index_shift + iedge - 1;
  467. }
  468. }
  469. }
  470. static enum BSPLoadResult bspLoadModelDraws(const struct LoadModelContext *ctx, struct Stack *persistent,
  471. struct BSPModel *model) {
  472. struct BSPModelVertex * const vertices_buffer
  473. = stackAlloc(ctx->tmp, sizeof(struct BSPModelVertex) * ctx->max_draw_vertices);
  474. if (!vertices_buffer) return BSPLoadResult_ErrorTempMemory;
  475. /* each vertex after second in a vface is a new triangle */
  476. uint16_t * const indices_buffer = stackAlloc(ctx->tmp, sizeof(uint16_t) * ctx->indices);
  477. if (!indices_buffer) return BSPLoadResult_ErrorTempMemory;
  478. AGLBuffer vbo = aGLBufferCreate(AGLBT_Vertex);
  479. int vertex_pos = 0;
  480. int draw_indices_start = 0, indices_pos = 0;
  481. /*model->draws_count = ctx->draws_to_alloc;*/
  482. model->draws_count = ctx->faces_count;
  483. model->draws = stackAlloc(persistent, sizeof(struct BSPDraw) * model->draws_count);
  484. int idraw = 0;
  485. for (int iface = 0; iface < ctx->faces_count/* + 1*/; ++iface) {
  486. const struct Face *face = ctx->faces + iface;
  487. #if 0
  488. /*if (iface == ctx->faces_count || face->vertices + vertex_pos >= c_max_draw_vertices) {*/
  489. if (iface > 0) {
  490. struct BSPDraw *draw = model->draws + idraw;
  491. memset(draw, 0, sizeof *draw);
  492. draw->count = indices_pos - draw_indices_start;
  493. draw->start = draw_indices_start;
  494. PRINTF("Adding draw=%u start=%u count=%u", idraw, draw->start, draw->count);
  495. draw->vbo = vbo;
  496. draw->material = face->material;
  497. if (iface == ctx->faces_count) break;
  498. //vertex_pos = 0;
  499. draw_indices_start = indices_pos;
  500. ++idraw;
  501. ASSERT(idraw < model->draws_count);
  502. }
  503. #endif
  504. if (face->dispinfo) {
  505. bspLoadDisplacement(ctx, face, vertices_buffer + vertex_pos, indices_buffer + indices_pos, vertex_pos);
  506. } else {
  507. bspLoadFace(ctx, face, vertices_buffer + vertex_pos, indices_buffer + indices_pos, vertex_pos);
  508. }
  509. vertex_pos += face->vertices;
  510. indices_pos += face->indices;
  511. #if 1
  512. struct BSPDraw *draw = model->draws + idraw;
  513. memset(draw, 0, sizeof *draw);
  514. draw->count = indices_pos - draw_indices_start;
  515. draw->start = draw_indices_start;
  516. PRINTF("Adding draw=%u start=%u count=%u", idraw, draw->start, draw->count);
  517. draw->vbo = vbo;
  518. draw->material = face->material;
  519. /*
  520. PRINTF("Got texture size %dx%d",
  521. draw->material->base_texture[0]->gltex.width,
  522. draw->material->base_texture[0]->gltex.height);
  523. */
  524. //vertex_pos = 0;
  525. draw_indices_start = indices_pos;
  526. ++idraw;
  527. ASSERT(idraw <= model->draws_count);
  528. #endif
  529. }
  530. PRINTF("%d %d", idraw, model->draws_count);
  531. ASSERT(idraw == model->draws_count);
  532. aGLBufferUpload(&vbo, sizeof(struct BSPModelVertex) * vertex_pos, vertices_buffer);
  533. model->ibo = aGLBufferCreate(AGLBT_Index);
  534. aGLBufferUpload(&model->ibo, sizeof(uint16_t) * ctx->indices, indices_buffer);
  535. return BSPLoadResult_Success;
  536. }
  537. static enum BSPLoadResult bspLoadModel(
  538. struct ICollection *collection, struct BSPModel *model, struct Stack *persistent, struct Stack *temp,
  539. const struct Lumps *lumps, unsigned index) {
  540. struct LoadModelContext context;
  541. memset(&context, 0, sizeof context);
  542. ASSERT(index < lumps->models.n);
  543. context.tmp = temp;
  544. context.collection = collection;
  545. context.lumps = lumps;
  546. context.model = lumps->models.p + index;
  547. /* Step 1. Collect lightmaps for all faces */
  548. enum BSPLoadResult result = bspLoadModelPreloadFaces(&context);
  549. if (result != BSPLoadResult_Success) {
  550. PRINTF("Error: bspLoadModelPreloadFaces() => %s", R2S(result));
  551. return result;
  552. }
  553. /* Step 2. Build an atlas of all lightmaps */
  554. result = bspLoadModelLightmaps(&context);
  555. if (result != BSPLoadResult_Success) {
  556. PRINTF("Error: bspLoadModelLightmaps() => %s", R2S(result));
  557. return result;
  558. }
  559. /* Step 3. Generate draw operations data */
  560. result = bspLoadModelDraws(&context, persistent, model);
  561. if (result != BSPLoadResult_Success) {
  562. aGLTextureDestroy(&context.lightmap.texture);
  563. return result;
  564. }
  565. model->lightmap = context.lightmap.texture;
  566. model->aabb.min.x = context.model->min.x;
  567. model->aabb.min.y = context.model->min.y;
  568. model->aabb.min.z = context.model->min.z;
  569. model->aabb.max.x = context.model->max.x;
  570. model->aabb.max.y = context.model->max.y;
  571. model->aabb.max.z = context.model->max.z;
  572. return BSPLoadResult_Success;
  573. }
  574. static int lumpRead(const char *name, const struct VBSPLumpHeader *header,
  575. struct IFile *file, struct Stack *tmp,
  576. struct AnyLump *out_ptr, uint32_t item_size) {
  577. out_ptr->p = stackAlloc(tmp, header->size);
  578. if (!out_ptr->p) {
  579. PRINTF("Not enough temp memory to allocate storage for lump %s", name);
  580. return -1;
  581. }
  582. const size_t bytes = file->read(file, header->file_offset, header->size, (void*)out_ptr->p);
  583. if (bytes != header->size) {
  584. PRINTF("Cannot read full lump %s, read only %zu bytes out of %u", name, bytes, header->size);
  585. return -1;
  586. }
  587. PRINTF("Read lump %s, offset %u, size %u bytes / %u item = %u elements",
  588. name, header->file_offset, header->size, item_size, header->size / item_size);
  589. out_ptr->n = header->size / item_size;
  590. return 1;
  591. }
  592. enum BSPLoadResult bspLoadWorldspawn(struct BSPLoadModelContext context, const char *mapname) {
  593. enum BSPLoadResult result = BSPLoadResult_Success;
  594. struct IFile *file = 0;
  595. if (CollectionOpen_Success !=
  596. collectionChainOpen(context.collection, mapname, File_Map, &file)) {
  597. return BSPLoadResult_ErrorFileOpen;
  598. }
  599. void *tmp_cursor = stackGetCursor(context.tmp);
  600. struct VBSPHeader vbsp_header;
  601. size_t bytes = file->read(file, 0, sizeof vbsp_header, &vbsp_header);
  602. if (bytes < sizeof(vbsp_header)) {
  603. PRINTF("Size is too small: %zu <= %zu", bytes, sizeof(struct VBSPHeader));
  604. result = BSPLoadResult_ErrorFileFormat;
  605. goto exit;
  606. }
  607. if (vbsp_header.ident[0] != 'V' || vbsp_header.ident[1] != 'B' ||
  608. vbsp_header.ident[2] != 'S' || vbsp_header.ident[3] != 'P') {
  609. PRINTF("Error: invalid ident => %c%c%c%c != VBSP",
  610. vbsp_header.ident[0], vbsp_header.ident[1], vbsp_header.ident[2], vbsp_header.ident[3]);
  611. result = BSPLoadResult_ErrorFileFormat;
  612. goto exit;
  613. }
  614. if (vbsp_header.version != 19 && vbsp_header.version != 20) {
  615. PRINTF("Error: invalid version: %d != 19 or 20", vbsp_header.version);
  616. result = BSPLoadResult_ErrorFileFormat;
  617. goto exit;
  618. }
  619. PRINTF("VBSP version %u opened", vbsp_header.version);
  620. struct Lumps lumps;
  621. lumps.version = vbsp_header.version;
  622. #define BSPLUMP(name, type, field) \
  623. if (1 != lumpRead(#name, vbsp_header.lump_headers + VBSP_Lump_##name, file, context.tmp, \
  624. (struct AnyLump*)&lumps.field, sizeof(type))) { \
  625. result = BSPLoadResult_ErrorFileFormat; \
  626. goto exit; \
  627. }
  628. LIST_LUMPS
  629. #undef BSPLUMP
  630. result = bspLoadModel(context.collection, context.model, context.persistent, context.tmp, &lumps, 0);
  631. if (result != BSPLoadResult_Success)
  632. PRINTF("Error: bspLoadModel() => %s", R2S(result));
  633. exit:
  634. stackFreeUpToPosition(context.tmp, tmp_cursor);
  635. if (file) file->close(file);
  636. return result;
  637. }