Debian Codegraph @

tools/quake3/q3map2/convert_gltf.c

raw symbols SCIP
1 /* -------------------------------------------------------------------------------
2
3 Copyright (C) 2026 Netradiant contributors.
4 For a list of contributors, see the accompanying CONTRIBUTORS file.
5
6 This file is part of NetRadiant.
7
8 GtkRadiant is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
12
13 GtkRadiant is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GtkRadiant; if not, write to the Free Software
20 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21
22 ------------------------------------------------------------------------------- */
23
24
25
26 /* marker */
27 #define CONVERT_GLTF_C
28
29
30
31 /* dependencies */
32 #include "q3map2.h"
33
34 #include "cgltf.h"
35 #define CGLTF_WRITE_IMPLEMENTATION
36 #include "cgltf_write.h"
37
38 #include <float.h>
39 #include <ctype.h>
40 #include "png.h"
41
42
43 /*
44 stristr()
45 case-insensitive substring search
46 */
47 static const char *stristr( const char *haystack, const char *needle ){
48 if ( !haystack || !needle ) {
49 return NULL;
50 }
51 for ( ; *haystack; haystack++ ) {
52 const char *h = haystack;
53 const char *n = needle;
54 while ( *h && *n && tolower( (unsigned char)*h ) == tolower( (unsigned char)*n ) ) {
55 h++;
56 n++;
57 }
58 if ( !*n ) {
59 return haystack;
60 }
61 }
62 return NULL;
63 }
64
65 /*
66 PNGWriteCallback()
67 libpng write callback that appends to a dynamically growing buffer
68 */
69
70 typedef struct pngWriteBuffer_s {
71 unsigned char *data;
72 cgltf_size size;
73 cgltf_size capacity;
74 } pngWriteBuffer_t;
75
76 static void PNGWriteCallback( png_structp png, png_bytep data, png_size_t length ){
77 pngWriteBuffer_t *buf = (pngWriteBuffer_t *)png_get_io_ptr( png );
78 while ( buf->size + length > buf->capacity ) {
79 buf->capacity = buf->capacity ? buf->capacity * 2 : 4096;
80 buf->data = realloc( buf->data, buf->capacity );
81 }
82 memcpy( buf->data + buf->size, data, length );
83 buf->size += length;
84 }
85
86 static void PNGFlushCallback( png_structp png ){
87 (void)png;
88 }
89
90
91 /*
92 EncodePNG()
93 encodes RGBA pixel data into a PNG in memory
94 returns allocated buffer and sets outSize; caller must free()
95 */
96
97 static unsigned char *EncodePNG( const byte *pixels, int width, int height, cgltf_size *outSize ){
98 png_structp png;
99 png_infop info;
100 png_bytep *rowPointers;
101 pngWriteBuffer_t buf;
102 int i;
103
104 *outSize = 0;
105
106 png = png_create_write_struct( PNG_LIBPNG_VER_STRING, NULL, NULL, NULL );
107 if ( !png ) {
108 return NULL;
109 }
110 info = png_create_info_struct( png );
111 if ( !info ) {
112 png_destroy_write_struct( &png, NULL );
113 return NULL;
114 }
115 if ( setjmp( png_jmpbuf( png ) ) ) {
116 png_destroy_write_struct( &png, &info );
117 return NULL;
118 }
119
120 memset( &buf, 0, sizeof( buf ) );
121 png_set_write_fn( png, &buf, PNGWriteCallback, PNGFlushCallback );
122
123 png_set_IHDR( png, info, width, height, 8, PNG_COLOR_TYPE_RGBA,
124 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT );
125
126 rowPointers = safe_malloc( sizeof( png_bytep ) * height );
127 for ( i = 0; i < height; i++ ) {
128 rowPointers[ i ] = (png_bytep)( pixels + i * width * 4 );
129 }
130
131 png_set_rows( png, info, rowPointers );
132 png_write_png( png, info, PNG_TRANSFORM_IDENTITY, NULL );
133
134 png_destroy_write_struct( &png, &info );
135 free( rowPointers );
136
137 *outSize = buf.size;
138 return buf.data;
139 }
140
141
142
143 /*
144 ConvertBSPToGLTF()
145 exports a glTF 2.0 GLB file from the bsp
146 */
147
148 /* blend type classification for shader-to-gltf material mapping */
149 #define GLTF_BLEND_OPAQUE 0 /* fully opaque */
150 #define GLTF_BLEND_ALPHA 1 /* uses texture alpha (blendfunc blend) */
151 #define GLTF_BLEND_ADDITIVE 2 /* additive: black = transparent (blendfunc add) */
152 #define GLTF_BLEND_MASK 3 /* alpha test (alphaFunc) */
153
154 static int IsSurfaceExportable( int surfaceType ){
155 return surfaceType == MST_PLANAR || surfaceType == MST_TRIANGLE_SOUP || surfaceType == MST_PATCH;
156 }
157
158 int ConvertBSPToGLTF( char *bspName ){
159 int i, j, k, s, v, x, y, modelNum;
160 char name[ 1024 ], base[ 1024 ];
161 bspModel_t *model;
162 bspDrawSurface_t *ds;
163 bspDrawVert_t *dv;
164 entity_t *e;
165 vec3_t origin;
166 const char *key;
167
168 int totalSurfaces, totalVertices, totalIndices, numMeshes, numMaterials;
169 int *shaderToMaterial;
170 int *primitivesPerMesh;
171 int meshIdx, surfIdx, primOffset;
172 int hasSurfaces, primCount;
173 int numVerts, numIndexes;
174
175 /* patch tessellation cache */
176 mesh_t **patchMeshes;
177 int numPatchMeshes, patchMeshIdx;
178 mesh_t *mesh;
179
180 cgltf_size bufferSize, bufferOffset;
181 cgltf_size posOffset, normOffset, uvOffset, idxOffset;
182 unsigned char *bufferData;
183 float *posPtr, *normPtr, *uvPtr;
184 unsigned int *idxPtr;
185
186 int bvBase, acBase;
187 float posMin[ 3 ], posMax[ 3 ];
188 float gltfCoord[ 3 ];
189
190 cgltf_buffer *gltfBuffers;
191 cgltf_buffer_view *bufferViews;
192 cgltf_accessor *gltfAccessors;
193 cgltf_material *gltfMaterials;
194 cgltf_mesh *gltfMeshes;
195 cgltf_node *gltfNodes;
196 cgltf_node **nodePointers;
197 cgltf_scene *gltfScenes;
198 cgltf_primitive *allPrimitives;
199 cgltf_attribute *allAttributes;
200 cgltf_image *gltfImages;
201 cgltf_texture *gltfTextures;
202 cgltf_sampler *gltfSamplers;
203
204 /* texture embedding */
205 int numImages;
206 unsigned char **pngDataArray;
207 cgltf_size *pngSizeArray;
208 cgltf_size totalImageSize;
209 int numBufferViews;
210 int *blendTypes;
211
212 cgltf_data data;
213 cgltf_options options;
214 cgltf_result result;
215
216
217 /* note it */
218 Sys_Printf( "--- Convert BSP to GLTF ---\n" );
219
220 /* create output filename */
221 strcpy( name, bspName );
222 StripExtension( name );
223 strcat( name, ".glb" );
224 Sys_Printf( "writing %s\n", name );
225 ExtractFileBase( bspName, base );
226
227
228 /* first pass: count surfaces, vertices, indices, meshes, tessellate patches */
229 totalSurfaces = 0;
230 totalVertices = 0;
231 totalIndices = 0;
232 numMeshes = 0;
233 numPatchMeshes = 0;
234
235 /* count patch surfaces first to allocate cache */
236 for ( i = 0; i < numEntities; i++ )
237 {
238 e = &entities[ i ];
239 if ( i == 0 ) {
240 modelNum = 0;
241 }
242 else
243 {
244 key = ValueForKey( e, "model" );
245 if ( key[ 0 ] != '*' ) {
246 continue;
247 }
248 modelNum = atoi( key + 1 );
249 }
250 model = &bspModels[ modelNum ];
251 for ( j = 0; j < model->numBSPSurfaces; j++ )
252 {
253 s = j + model->firstBSPSurface;
254 ds = &bspDrawSurfaces[ s ];
255 if ( ds->surfaceType == MST_PATCH ) {
256 numPatchMeshes++;
257 }
258 }
259 }
260 patchMeshes = safe_malloc0( sizeof( mesh_t * ) * ( numPatchMeshes > 0 ? numPatchMeshes : 1 ) );
261 patchMeshIdx = 0;
262
263 for ( i = 0; i < numEntities; i++ )
264 {
265 e = &entities[ i ];
266 if ( i == 0 ) {
267 modelNum = 0;
268 }
269 else
270 {
271 key = ValueForKey( e, "model" );
272 if ( key[ 0 ] != '*' ) {
273 continue;
274 }
275 modelNum = atoi( key + 1 );
276 }
277 model = &bspModels[ modelNum ];
278
279 hasSurfaces = 0;
280 for ( j = 0; j < model->numBSPSurfaces; j++ )
281 {
282 s = j + model->firstBSPSurface;
283 ds = &bspDrawSurfaces[ s ];
284 if ( !IsSurfaceExportable( ds->surfaceType ) ) {
285 continue;
286 }
287
288 if ( ds->surfaceType == MST_PATCH ) {
289 mesh = TessellatePatch( ds );
290 patchMeshes[ patchMeshIdx++ ] = mesh;
291 numVerts = mesh->width * mesh->height;
292 numIndexes = ( mesh->width - 1 ) * ( mesh->height - 1 ) * 6;
293 }
294 else {
295 numVerts = ds->numVerts;
296 numIndexes = ds->numIndexes;
297 }
298
299 totalSurfaces++;
300 totalVertices += numVerts;
301 totalIndices += numIndexes;
302 hasSurfaces = 1;
303 }
304 if ( hasSurfaces ) {
305 numMeshes++;
306 }
307 }
308
309 if ( totalSurfaces == 0 ) {
310 Sys_Printf( "No surfaces to export\n" );
311 return 0;
312 }
313
314
315 /* count unique materials (shader indices actually used) */
316 shaderToMaterial = safe_malloc0( sizeof( int ) * numBSPShaders );
317 numMaterials = 0;
318 for ( i = 0; i < numBSPShaders; i++ )
319 {
320 shaderToMaterial[ i ] = -1;
321 }
322
323 for ( i = 0; i < numEntities; i++ )
324 {
325 e = &entities[ i ];
326 if ( i == 0 ) {
327 modelNum = 0;
328 }
329 else
330 {
331 key = ValueForKey( e, "model" );
332 if ( key[ 0 ] != '*' ) {
333 continue;
334 }
335 modelNum = atoi( key + 1 );
336 }
337 model = &bspModels[ modelNum ];
338 for ( j = 0; j < model->numBSPSurfaces; j++ )
339 {
340 s = j + model->firstBSPSurface;
341 ds = &bspDrawSurfaces[ s ];
342 if ( !IsSurfaceExportable( ds->surfaceType ) ) {
343 continue;
344 }
345 if ( shaderToMaterial[ ds->shaderNum ] == -1 ) {
346 shaderToMaterial[ ds->shaderNum ] = numMaterials++;
347 }
348 }
349 }
350
351
352 /* count primitives per mesh */
353 primitivesPerMesh = safe_malloc0( sizeof( int ) * numMeshes );
354 meshIdx = 0;
355
356
357 /* determine blend type for each material from shader properties */
358 blendTypes = safe_malloc0( sizeof( int ) * numMaterials );
359 for ( i = 0; i < numBSPShaders; i++ )
360 {
361 if ( shaderToMaterial[ i ] >= 0 ) {
362 shaderInfo_t *si;
363 k = shaderToMaterial[ i ];
364 si = ShaderInfoForShader( bspShaders[ i ].shader );
365 blendTypes[ k ] = GLTF_BLEND_OPAQUE;
366
367 if ( si ) {
368 if ( si->implicitMap == IM_MASKED ) {
369 blendTypes[ k ] = GLTF_BLEND_MASK;
370 }
371 else if ( si->implicitMap == IM_BLEND ) {
372 blendTypes[ k ] = GLTF_BLEND_ALPHA;
373 }
374 else if ( si->shaderText ) {
375 if ( stristr( si->shaderText, "alphaFunc" ) ) {
376 blendTypes[ k ] = GLTF_BLEND_MASK;
377 }
378 else if ( stristr( si->shaderText, "GL_SRC_ALPHA" ) ||
379 stristr( si->shaderText, "blendfunc blend" ) ) {
380 blendTypes[ k ] = GLTF_BLEND_ALPHA;
381 }
382 else if ( stristr( si->shaderText, "blendfunc add" ) ||
383 stristr( si->shaderText, "GL_ONE GL_ONE" ) ||
384 stristr( si->shaderText, "GL_ONE GL_ONE_MINUS_SRC_COLOR" ) ) {
385 blendTypes[ k ] = GLTF_BLEND_ADDITIVE;
386 }
387 }
388 }
389 }
390 }
391
392
393 /* load and encode textures as PNG for embedding */
394 pngDataArray = safe_malloc0( sizeof( unsigned char * ) * numMaterials );
395 pngSizeArray = safe_malloc0( sizeof( cgltf_size ) * numMaterials );
396 numImages = 0;
397 totalImageSize = 0;
398 for ( i = 0; i < numBSPShaders; i++ )
399 {
400 if ( shaderToMaterial[ i ] >= 0 ) {
401 image_t *img;
402 unsigned char *pngData;
403 cgltf_size pngSize;
404
405 k = shaderToMaterial[ i ];
406 img = ImageLoad( bspShaders[ i ].shader );
407 if ( img && img->pixels && img->width > 0 && img->height > 0 ) {
408 /* for additive blends, synthesize alpha from pixel brightness */
409 if ( blendTypes[ k ] == GLTF_BLEND_ADDITIVE ) {
410 int px;
411 int numPixels = img->width * img->height;
412 for ( px = 0; px < numPixels; px++ ) {
413 unsigned char r = img->pixels[ px * 4 + 0 ];
414 unsigned char g = img->pixels[ px * 4 + 1 ];
415 unsigned char b = img->pixels[ px * 4 + 2 ];
416 unsigned char a = r;
417 if ( g > a ) a = g;
418 if ( b > a ) a = b;
419 img->pixels[ px * 4 + 3 ] = a;
420 }
421 }
422 pngData = EncodePNG( img->pixels, img->width, img->height, &pngSize );
423 if ( pngData ) {
424 pngDataArray[ k ] = pngData;
425 pngSizeArray[ k ] = pngSize;
426 totalImageSize += pngSize;
427 numImages++;
428 Sys_FPrintf( SYS_VRB, " Encoded texture: %s (%dx%d, %d bytes PNG)\n",
429 bspShaders[ i ].shader, img->width, img->height, (int)pngSize );
430 }
431 else {
432 Sys_FPrintf( SYS_VRB, " Failed to encode texture: %s\n", bspShaders[ i ].shader );
433 }
434 }
435 else {
436 Sys_FPrintf( SYS_VRB, " Texture not found: %s\n", bspShaders[ i ].shader );
437 }
438 }
439 }
440 Sys_Printf( "Embedded %d of %d textures\n", numImages, numMaterials );
441
442 for ( i = 0; i < numEntities; i++ )
443 {
444 e = &entities[ i ];
445 if ( i == 0 ) {
446 modelNum = 0;
447 }
448 else
449 {
450 key = ValueForKey( e, "model" );
451 if ( key[ 0 ] != '*' ) {
452 continue;
453 }
454 modelNum = atoi( key + 1 );
455 }
456 model = &bspModels[ modelNum ];
457
458 primCount = 0;
459 for ( j = 0; j < model->numBSPSurfaces; j++ )
460 {
461 s = j + model->firstBSPSurface;
462 ds = &bspDrawSurfaces[ s ];
463 if ( !IsSurfaceExportable( ds->surfaceType ) ) {
464 continue;
465 }
466 primCount++;
467 }
468 if ( primCount > 0 ) {
469 primitivesPerMesh[ meshIdx++ ] = primCount;
470 }
471 }
472
473
474 /* allocate binary buffer */
475 /* per vertex: 3 floats (pos) + 3 floats (normal) + 2 floats (uv) = 32 bytes */
476 /* per index: 1 uint32 = 4 bytes */
477 /* plus embedded PNG image data */
478 bufferSize = (cgltf_size)totalVertices * 32 + (cgltf_size)totalIndices * 4 + totalImageSize;
479 bufferData = safe_malloc0( bufferSize );
480
481
482 /* allocate cgltf structures */
483 /* buffer views: 4 per surface (pos/norm/uv/idx) + 1 per embedded image */
484 numBufferViews = totalSurfaces * 4 + numImages;
485 gltfBuffers = safe_malloc0( sizeof( cgltf_buffer ) );
486 bufferViews = safe_malloc0( sizeof( cgltf_buffer_view ) * numBufferViews );
487 gltfAccessors = safe_malloc0( sizeof( cgltf_accessor ) * totalSurfaces * 4 );
488 gltfMaterials = safe_malloc0( sizeof( cgltf_material ) * numMaterials );
489 gltfMeshes = safe_malloc0( sizeof( cgltf_mesh ) * numMeshes );
490 gltfNodes = safe_malloc0( sizeof( cgltf_node ) * numMeshes );
491 nodePointers = safe_malloc0( sizeof( cgltf_node * ) * numMeshes );
492 gltfScenes = safe_malloc0( sizeof( cgltf_scene ) );
493 allPrimitives = safe_malloc0( sizeof( cgltf_primitive ) * totalSurfaces );
494 allAttributes = safe_malloc0( sizeof( cgltf_attribute ) * totalSurfaces * 3 );
495 gltfImages = safe_malloc0( sizeof( cgltf_image ) * ( numImages > 0 ? numImages : 1 ) );
496 gltfTextures = safe_malloc0( sizeof( cgltf_texture ) * ( numImages > 0 ? numImages : 1 ) );
497 gltfSamplers = safe_malloc0( sizeof( cgltf_sampler ) );
498
499
500 /* set up buffer */
501 gltfBuffers[ 0 ].size = bufferSize;
502
503
504 /* set up sampler (shared by all textures) */
505 gltfSamplers[ 0 ].mag_filter = cgltf_filter_type_linear;
506 gltfSamplers[ 0 ].min_filter = cgltf_filter_type_linear_mipmap_linear;
507 gltfSamplers[ 0 ].wrap_s = cgltf_wrap_mode_repeat;
508 gltfSamplers[ 0 ].wrap_t = cgltf_wrap_mode_repeat;
509
510
511 /* set up materials with embedded textures */
512 {
513 int imgIdx = 0;
514 int imgBvBase = totalSurfaces * 4;
515 cgltf_size imgBufferOffset = (cgltf_size)totalVertices * 32 + (cgltf_size)totalIndices * 4;
516
517 for ( i = 0; i < numBSPShaders; i++ )
518 {
519 if ( shaderToMaterial[ i ] >= 0 ) {
520 shaderInfo_t *si;
521
522 k = shaderToMaterial[ i ];
523 si = ShaderInfoForShader( bspShaders[ i ].shader );
524
525 gltfMaterials[ k ].name = bspShaders[ i ].shader;
526 gltfMaterials[ k ].has_pbr_metallic_roughness = 1;
527 gltfMaterials[ k ].pbr_metallic_roughness.base_color_factor[ 0 ] = 1.0f;
528 gltfMaterials[ k ].pbr_metallic_roughness.base_color_factor[ 1 ] = 1.0f;
529 gltfMaterials[ k ].pbr_metallic_roughness.base_color_factor[ 2 ] = 1.0f;
530 gltfMaterials[ k ].pbr_metallic_roughness.base_color_factor[ 3 ] = 1.0f;
531 gltfMaterials[ k ].pbr_metallic_roughness.metallic_factor = 0.0f;
532 gltfMaterials[ k ].pbr_metallic_roughness.roughness_factor = 1.0f;
533 gltfMaterials[ k ].alpha_cutoff = 0.5f;
534
535 /* set alpha mode from pre-computed blend type */
536 switch ( blendTypes[ k ] ) {
537 case GLTF_BLEND_MASK:
538 gltfMaterials[ k ].alpha_mode = cgltf_alpha_mode_mask;
539 break;
540 case GLTF_BLEND_ALPHA:
541 case GLTF_BLEND_ADDITIVE:
542 gltfMaterials[ k ].alpha_mode = cgltf_alpha_mode_blend;
543 break;
544 default:
545 gltfMaterials[ k ].alpha_mode = cgltf_alpha_mode_opaque;
546 break;
547 }
548
549 /* map shader properties to glTF material */
550 if ( si ) {
551 /* double-sided from cull none/disable/twosided */
552 if ( si->twoSided ) {
553 gltfMaterials[ k ].double_sided = 1;
554 }
555
556 /* emissive: surfaces with light value emit light */
557 if ( si->value > 0 ) {
558 gltfMaterials[ k ].emissive_factor[ 0 ] = si->color[ 0 ];
559 gltfMaterials[ k ].emissive_factor[ 1 ] = si->color[ 1 ];
560 gltfMaterials[ k ].emissive_factor[ 2 ] = si->color[ 2 ];
561 }
562 }
563
564 /* if we have a PNG for this material, embed it */
565 if ( pngDataArray[ k ] ) {
566 /* copy PNG data into the binary buffer */
567 memcpy( bufferData + imgBufferOffset, pngDataArray[ k ], pngSizeArray[ k ] );
568
569 /* set up buffer view for this image */
570 bufferViews[ imgBvBase + imgIdx ].buffer = &gltfBuffers[ 0 ];
571 bufferViews[ imgBvBase + imgIdx ].offset = imgBufferOffset;
572 bufferViews[ imgBvBase + imgIdx ].size = pngSizeArray[ k ];
573
574 /* set up image */
575 gltfImages[ imgIdx ].name = bspShaders[ i ].shader;
576 gltfImages[ imgIdx ].buffer_view = &bufferViews[ imgBvBase + imgIdx ];
577 gltfImages[ imgIdx ].mime_type = "image/png";
578
579 /* set up texture */
580 gltfTextures[ imgIdx ].name = bspShaders[ i ].shader;
581 gltfTextures[ imgIdx ].image = &gltfImages[ imgIdx ];
582 gltfTextures[ imgIdx ].sampler = &gltfSamplers[ 0 ];
583
584 /* wire texture into material */
585 gltfMaterials[ k ].pbr_metallic_roughness.base_color_texture.texture = &gltfTextures[ imgIdx ];
586 gltfMaterials[ k ].pbr_metallic_roughness.base_color_texture.scale = 1.0f;
587
588 imgBufferOffset += pngSizeArray[ k ];
589 imgIdx++;
590 }
591 }
592 }
593 }
594
595
596 /* set up mesh primitive structure */
597 primOffset = 0;
598 for ( meshIdx = 0; meshIdx < numMeshes; meshIdx++ )
599 {
600 gltfMeshes[ meshIdx ].primitives = &allPrimitives[ primOffset ];
601 gltfMeshes[ meshIdx ].primitives_count = primitivesPerMesh[ meshIdx ];
602 for ( j = 0; j < primitivesPerMesh[ meshIdx ]; j++ )
603 {
604 surfIdx = primOffset + j;
605 allPrimitives[ surfIdx ].type = cgltf_primitive_type_triangles;
606 allPrimitives[ surfIdx ].attributes = &allAttributes[ surfIdx * 3 ];
607 allPrimitives[ surfIdx ].attributes_count = 3;
608 }
609 primOffset += primitivesPerMesh[ meshIdx ];
610 }
611
612
613 /* set up nodes */
614 for ( meshIdx = 0; meshIdx < numMeshes; meshIdx++ )
615 {
616 gltfNodes[ meshIdx ].mesh = &gltfMeshes[ meshIdx ];
617 nodePointers[ meshIdx ] = &gltfNodes[ meshIdx ];
618 }
619
620
621 /* set up scene */
622 gltfScenes[ 0 ].nodes = nodePointers;
623 gltfScenes[ 0 ].nodes_count = numMeshes;
624
625
626 /* second pass: fill binary buffer and set up buffer views, accessors, primitives */
627 bufferOffset = 0;
628 surfIdx = 0;
629 meshIdx = 0;
630 patchMeshIdx = 0;
631
632 for ( i = 0; i < numEntities; i++ )
633 {
634 e = &entities[ i ];
635 if ( i == 0 ) {
636 modelNum = 0;
637 }
638 else
639 {
640 key = ValueForKey( e, "model" );
641 if ( key[ 0 ] != '*' ) {
642 continue;
643 }
644 modelNum = atoi( key + 1 );
645 }
646 model = &bspModels[ modelNum ];
647
648 /* get entity origin */
649 key = ValueForKey( e, "origin" );
650 if ( key[ 0 ] == '\0' ) {
651 VectorClear( origin );
652 }
653 else
654 {
655 GetVectorForKey( e, "origin", origin );
656 }
657
658 hasSurfaces = 0;
659 for ( j = 0; j < model->numBSPSurfaces; j++ )
660 {
661 s = j + model->firstBSPSurface;
662 ds = &bspDrawSurfaces[ s ];
663 if ( !IsSurfaceExportable( ds->surfaceType ) ) {
664 continue;
665 }
666
667 /* determine vertex/index counts for this surface */
668 if ( ds->surfaceType == MST_PATCH ) {
669 mesh = patchMeshes[ patchMeshIdx++ ];
670 numVerts = mesh->width * mesh->height;
671 numIndexes = ( mesh->width - 1 ) * ( mesh->height - 1 ) * 6;
672 }
673 else {
674 mesh = NULL;
675 numVerts = ds->numVerts;
676 numIndexes = ds->numIndexes;
677 }
678
679 bvBase = surfIdx * 4;
680 acBase = surfIdx * 4;
681
682 /* write positions and compute bounds */
683 posMin[ 0 ] = posMin[ 1 ] = posMin[ 2 ] = FLT_MAX;
684 posMax[ 0 ] = posMax[ 1 ] = posMax[ 2 ] = -FLT_MAX;
685
686 posOffset = bufferOffset;
687 posPtr = (float *)( bufferData + bufferOffset );
688 for ( v = 0; v < numVerts; v++ )
689 {
690 vec3_t pos;
691 if ( mesh ) {
692 dv = &mesh->verts[ v ];
693 }
694 else {
695 dv = &bspDrawVerts[ ds->firstVert + v ];
696 }
697 VectorAdd( dv->xyz, origin, pos );
698 /* Quake Z-up to glTF Y-up */
699 gltfCoord[ 0 ] = pos[ 0 ];
700 gltfCoord[ 1 ] = pos[ 2 ];
701 gltfCoord[ 2 ] = -pos[ 1 ];
702 posPtr[ v * 3 + 0 ] = gltfCoord[ 0 ];
703 posPtr[ v * 3 + 1 ] = gltfCoord[ 1 ];
704 posPtr[ v * 3 + 2 ] = gltfCoord[ 2 ];
705 for ( k = 0; k < 3; k++ )
706 {
707 if ( gltfCoord[ k ] < posMin[ k ] ) {
708 posMin[ k ] = gltfCoord[ k ];
709 }
710 if ( gltfCoord[ k ] > posMax[ k ] ) {
711 posMax[ k ] = gltfCoord[ k ];
712 }
713 }
714 }
715 bufferOffset += (cgltf_size)numVerts * 12;
716
717 /* write normals */
718 normOffset = bufferOffset;
719 normPtr = (float *)( bufferData + bufferOffset );
720 for ( v = 0; v < numVerts; v++ )
721 {
722 if ( mesh ) {
723 dv = &mesh->verts[ v ];
724 }
725 else {
726 dv = &bspDrawVerts[ ds->firstVert + v ];
727 }
728 /* Quake Z-up to glTF Y-up */
729 normPtr[ v * 3 + 0 ] = dv->normal[ 0 ];
730 normPtr[ v * 3 + 1 ] = dv->normal[ 2 ];
731 normPtr[ v * 3 + 2 ] = -dv->normal[ 1 ];
732 }
733 bufferOffset += (cgltf_size)numVerts * 12;
734
735 /* write texcoords */
736 uvOffset = bufferOffset;
737 uvPtr = (float *)( bufferData + bufferOffset );
738 for ( v = 0; v < numVerts; v++ )
739 {
740 if ( mesh ) {
741 dv = &mesh->verts[ v ];
742 }
743 else {
744 dv = &bspDrawVerts[ ds->firstVert + v ];
745 }
746 uvPtr[ v * 2 + 0 ] = dv->st[ 0 ];
747 uvPtr[ v * 2 + 1 ] = dv->st[ 1 ];
748 }
749 bufferOffset += (cgltf_size)numVerts * 8;
750
751 /* write indices (reverse winding: Q3 BSP uses CW front faces,
752 glTF expects CCW front faces) */
753 idxOffset = bufferOffset;
754 idxPtr = (unsigned int *)( bufferData + bufferOffset );
755 if ( mesh ) {
756 /* generate triangle indices from tessellated grid */
757 v = 0;
758 for ( y = 0; y < mesh->height - 1; y++ )
759 {
760 for ( x = 0; x < mesh->width - 1; x++ )
761 {
762 int r = ( x + y ) & 1;
763 int pw0 = x + y * mesh->width;
764 int pw1 = x + ( y + 1 ) * mesh->width;
765 int pw2 = ( x + 1 ) + ( y + 1 ) * mesh->width;
766 int pw3 = ( x + 1 ) + y * mesh->width;
767
768 if ( r ) {
769 idxPtr[ v++ ] = (unsigned int)pw0;
770 idxPtr[ v++ ] = (unsigned int)pw2;
771 idxPtr[ v++ ] = (unsigned int)pw1;
772 idxPtr[ v++ ] = (unsigned int)pw0;
773 idxPtr[ v++ ] = (unsigned int)pw3;
774 idxPtr[ v++ ] = (unsigned int)pw2;
775 }
776 else {
777 idxPtr[ v++ ] = (unsigned int)pw0;
778 idxPtr[ v++ ] = (unsigned int)pw3;
779 idxPtr[ v++ ] = (unsigned int)pw1;
780 idxPtr[ v++ ] = (unsigned int)pw3;
781 idxPtr[ v++ ] = (unsigned int)pw2;
782 idxPtr[ v++ ] = (unsigned int)pw1;
783 }
784 }
785 }
786 }
787 else {
788 for ( v = 0; v < numIndexes; v += 3 )
789 {
790 idxPtr[ v + 0 ] = (unsigned int)bspDrawIndexes[ ds->firstIndex + v + 0 ];
791 idxPtr[ v + 1 ] = (unsigned int)bspDrawIndexes[ ds->firstIndex + v + 2 ];
792 idxPtr[ v + 2 ] = (unsigned int)bspDrawIndexes[ ds->firstIndex + v + 1 ];
793 }
794 }
795 bufferOffset += (cgltf_size)numIndexes * 4;
796
797
798 /* set up buffer views */
799 bufferViews[ bvBase + 0 ].buffer = &gltfBuffers[ 0 ];
800 bufferViews[ bvBase + 0 ].offset = posOffset;
801 bufferViews[ bvBase + 0 ].size = (cgltf_size)numVerts * 12;
802 bufferViews[ bvBase + 0 ].type = cgltf_buffer_view_type_vertices;
803
804 bufferViews[ bvBase + 1 ].buffer = &gltfBuffers[ 0 ];
805 bufferViews[ bvBase + 1 ].offset = normOffset;
806 bufferViews[ bvBase + 1 ].size = (cgltf_size)numVerts * 12;
807 bufferViews[ bvBase + 1 ].type = cgltf_buffer_view_type_vertices;
808
809 bufferViews[ bvBase + 2 ].buffer = &gltfBuffers[ 0 ];
810 bufferViews[ bvBase + 2 ].offset = uvOffset;
811 bufferViews[ bvBase + 2 ].size = (cgltf_size)numVerts * 8;
812 bufferViews[ bvBase + 2 ].type = cgltf_buffer_view_type_vertices;
813
814 bufferViews[ bvBase + 3 ].buffer = &gltfBuffers[ 0 ];
815 bufferViews[ bvBase + 3 ].offset = idxOffset;
816 bufferViews[ bvBase + 3 ].size = (cgltf_size)numIndexes * 4;
817 bufferViews[ bvBase + 3 ].type = cgltf_buffer_view_type_indices;
818
819
820 /* set up accessors */
821 gltfAccessors[ acBase + 0 ].buffer_view = &bufferViews[ bvBase + 0 ];
822 gltfAccessors[ acBase + 0 ].component_type = cgltf_component_type_r_32f;
823 gltfAccessors[ acBase + 0 ].type = cgltf_type_vec3;
824 gltfAccessors[ acBase + 0 ].count = numVerts;
825 gltfAccessors[ acBase + 0 ].has_min = 1;
826 gltfAccessors[ acBase + 0 ].has_max = 1;
827 for ( k = 0; k < 3; k++ )
828 {
829 gltfAccessors[ acBase + 0 ].min[ k ] = posMin[ k ];
830 gltfAccessors[ acBase + 0 ].max[ k ] = posMax[ k ];
831 }
832
833 gltfAccessors[ acBase + 1 ].buffer_view = &bufferViews[ bvBase + 1 ];
834 gltfAccessors[ acBase + 1 ].component_type = cgltf_component_type_r_32f;
835 gltfAccessors[ acBase + 1 ].type = cgltf_type_vec3;
836 gltfAccessors[ acBase + 1 ].count = numVerts;
837
838 gltfAccessors[ acBase + 2 ].buffer_view = &bufferViews[ bvBase + 2 ];
839 gltfAccessors[ acBase + 2 ].component_type = cgltf_component_type_r_32f;
840 gltfAccessors[ acBase + 2 ].type = cgltf_type_vec2;
841 gltfAccessors[ acBase + 2 ].count = numVerts;
842
843 gltfAccessors[ acBase + 3 ].buffer_view = &bufferViews[ bvBase + 3 ];
844 gltfAccessors[ acBase + 3 ].component_type = cgltf_component_type_r_32u;
845 gltfAccessors[ acBase + 3 ].type = cgltf_type_scalar;
846 gltfAccessors[ acBase + 3 ].count = numIndexes;
847
848
849 /* set up primitive */
850 allPrimitives[ surfIdx ].indices = &gltfAccessors[ acBase + 3 ];
851 allPrimitives[ surfIdx ].material = &gltfMaterials[ shaderToMaterial[ ds->shaderNum ] ];
852
853 /* position attribute */
854 allAttributes[ surfIdx * 3 + 0 ].name = "POSITION";
855 allAttributes[ surfIdx * 3 + 0 ].type = cgltf_attribute_type_position;
856 allAttributes[ surfIdx * 3 + 0 ].data = &gltfAccessors[ acBase + 0 ];
857
858 /* normal attribute */
859 allAttributes[ surfIdx * 3 + 1 ].name = "NORMAL";
860 allAttributes[ surfIdx * 3 + 1 ].type = cgltf_attribute_type_normal;
861 allAttributes[ surfIdx * 3 + 1 ].data = &gltfAccessors[ acBase + 1 ];
862
863 /* texcoord attribute */
864 allAttributes[ surfIdx * 3 + 2 ].name = "TEXCOORD_0";
865 allAttributes[ surfIdx * 3 + 2 ].type = cgltf_attribute_type_texcoord;
866 allAttributes[ surfIdx * 3 + 2 ].data = &gltfAccessors[ acBase + 2 ];
867
868 surfIdx++;
869 hasSurfaces = 1;
870 }
871
872 if ( hasSurfaces ) {
873 meshIdx++;
874 }
875 }
876
877
878 /* build cgltf_data */
879 memset( &data, 0, sizeof( data ) );
880 data.asset.version = "2.0";
881 data.asset.generator = "Q3Map2 -convert -format gltf";
882
883 data.buffers = gltfBuffers;
884 data.buffers_count = 1;
885 data.buffer_views = bufferViews;
886 data.buffer_views_count = numBufferViews;
887 data.accessors = gltfAccessors;
888 data.accessors_count = totalSurfaces * 4;
889 data.materials = gltfMaterials;
890 data.materials_count = numMaterials;
891 data.meshes = gltfMeshes;
892 data.meshes_count = numMeshes;
893 data.nodes = gltfNodes;
894 data.nodes_count = numMeshes;
895 data.scenes = gltfScenes;
896 data.scenes_count = 1;
897 data.scene = gltfScenes;
898
899 data.images = gltfImages;
900 data.images_count = numImages;
901 data.textures = gltfTextures;
902 data.textures_count = numImages;
903 data.samplers = gltfSamplers;
904 data.samplers_count = numImages > 0 ? 1 : 0;
905
906 data.bin = bufferData;
907 data.bin_size = bufferSize;
908
909 /* write GLB */
910 memset( &options, 0, sizeof( options ) );
911 options.type = cgltf_file_type_glb;
912
913 result = cgltf_write_file( &options, name, &data );
914 if ( result != cgltf_result_success ) {
915 Sys_FPrintf( SYS_WRN, "WARNING: Failed to write %s (error %d)\n", name, (int)result );
916 }
917
918 /* free allocations */
919 for ( i = 0; i < numPatchMeshes; i++ )
920 {
921 FreeMesh( patchMeshes[ i ] );
922 }
923 free( patchMeshes );
924 free( bufferData );
925 free( gltfBuffers );
926 free( bufferViews );
927 free( gltfAccessors );
928 free( gltfMaterials );
929 free( gltfMeshes );
930 free( gltfNodes );
931 free( nodePointers );
932 free( gltfScenes );
933 free( allPrimitives );
934 free( allAttributes );
935 free( shaderToMaterial );
936 free( blendTypes );
937 free( primitivesPerMesh );
938 for ( i = 0; i < numMaterials; i++ )
939 {
940 free( pngDataArray[ i ] );
941 }
942 free( pngDataArray );
943 free( pngSizeArray );
944 free( gltfImages );
945 free( gltfTextures );
946 free( gltfSamplers );
947
948 /* return to sender */
949 return 0;
950 }