bsp.c 32 KB

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