Debian Codegraph @

src/rmodels.c

raw symbols SCIP
1 /**********************************************************************************************
2 *
3 * rmodels - Basic functions to draw 3d shapes and load and draw 3d models
4 *
5 * CONFIGURATION:
6 * #define SUPPORT_MODULE_RMODELS 1
7 * rmodels module is included in the build
8 *
9 * #define SUPPORT_FILEFORMAT_OBJ 1
10 * #define SUPPORT_FILEFORMAT_MTL 1
11 * #define SUPPORT_FILEFORMAT_IQM 1
12 * #define SUPPORT_FILEFORMAT_GLTF 1
13 * #define SUPPORT_FILEFORMAT_GLTF_WRITE 0
14 * #define SUPPORT_FILEFORMAT_VOX 1
15 * #define SUPPORT_FILEFORMAT_M3D 1
16 * Selected desired fileformats to be supported for model data loading
17 *
18 * #define SUPPORT_MESH_GENERATION 1
19 * Support procedural mesh generation functions, uses external par_shapes.h library
20 * NOTE: Some generated meshes DO NOT include generated texture coordinates
21 *
22 *
23 * LICENSE: zlib/libpng
24 *
25 * Copyright (c) 2013-2026 Ramon Santamaria (@raysan5)
26 *
27 * This software is provided "as-is", without any express or implied warranty. In no event
28 * will the authors be held liable for any damages arising from the use of this software.
29 *
30 * Permission is granted to anyone to use this software for any purpose, including commercial
31 * applications, and to alter it and redistribute it freely, subject to the following restrictions:
32 *
33 * 1. The origin of this software must not be misrepresented; you must not claim that you
34 * wrote the original software. If you use this software in a product, an acknowledgment
35 * in the product documentation would be appreciated but is not required.
36 *
37 * 2. Altered source versions must be plainly marked as such, and must not be misrepresented
38 * as being the original software.
39 *
40 * 3. This notice may not be removed or altered from any source distribution.
41 *
42 **********************************************************************************************/
43
44 #include "raylib.h" // Declares module functions
45
46 #include "config.h" // Defines module configuration flags
47
48 #if SUPPORT_MODULE_RMODELS
49
50 #include "rlgl.h" // OpenGL abstraction layer to OpenGL 1.1, 2.1, 3.3+ or ES2
51 #include "raymath.h" // Required for: Vector3, Quaternion and Matrix functionality
52
53 #include <stdio.h> // Required for: sprintf()
54 #include <stdlib.h> // Required for: malloc(), calloc(), free()
55 #include <string.h> // Required for: memcmp(), strlen(), strncpy()
56 #include <math.h> // Required for: sinf(), cosf(), sqrtf(), fabsf()
57
58 #if SUPPORT_FILEFORMAT_OBJ || SUPPORT_FILEFORMAT_MTL
59 #define TINYOBJ_MALLOC RL_MALLOC
60 #define TINYOBJ_CALLOC RL_CALLOC
61 #define TINYOBJ_REALLOC RL_REALLOC
62 #define TINYOBJ_FREE RL_FREE
63
64 #define TINYOBJ_LOADER_C_IMPLEMENTATION
65 #include "external/tinyobj_loader_c.h" // OBJ/MTL file formats loading
66 #endif
67
68 #if SUPPORT_FILEFORMAT_GLTF
69 #define CGLTF_MALLOC RL_MALLOC
70 #define CGLTF_FREE RL_FREE
71
72 #define CGLTF_IMPLEMENTATION
73 #include "external/cgltf.h" // glTF file format loading
74 #endif
75 #if SUPPORT_FILEFORMAT_GLTF_WRITE
76 // NOTE: No need for custom allocators, memory buffer provided
77 #define CGLTF_WRITE_IMPLEMENTATION
78 #include "external/cgltf_write.h" // glTF file format writing
79 #endif
80
81 #if SUPPORT_FILEFORMAT_VOX
82 #define VOX_MALLOC RL_MALLOC
83 #define VOX_CALLOC RL_CALLOC
84 #define VOX_REALLOC RL_REALLOC
85 #define VOX_FREE RL_FREE
86
87 #define VOX_LOADER_IMPLEMENTATION
88 #include "external/vox_loader.h" // VOX file format loading (MagikaVoxel)
89 #endif
90
91 #if SUPPORT_FILEFORMAT_M3D
92 #define M3D_MALLOC RL_MALLOC
93 #define M3D_REALLOC RL_REALLOC
94 #define M3D_FREE RL_FREE
95
96 #define M3D_IMPLEMENTATION
97 #include "external/m3d.h" // Model3D file format loading
98 #endif
99
100 #if SUPPORT_MESH_GENERATION
101 #define PAR_MALLOC(T, N) ((T *)RL_MALLOC(N*sizeof(T)))
102 #define PAR_CALLOC(T, N) ((T *)RL_CALLOC(N*sizeof(T), 1))
103 #define PAR_REALLOC(T, BUF, N) ((T *)RL_REALLOC(BUF, sizeof(T)*(N)))
104 #define PAR_FREE RL_FREE
105
106 #if defined(_MSC_VER) // Disable some MSVC warning
107 #pragma warning(push)
108 #pragma warning(disable : 4244)
109 #pragma warning(disable : 4305)
110 #endif
111
112 #define PAR_SHAPES_IMPLEMENTATION
113 #include "external/par_shapes.h" // Shapes 3d parametric generation
114
115 #if defined(_MSC_VER)
116 #pragma warning(pop) // Disable MSVC warning suppression
117 #endif
118 #endif
119
120 #if defined(_WIN32)
121 #include <direct.h> // Required for: _chdir() [Used in LoadOBJ()]
122 #define CHDIR _chdir
123 #else
124 #include <unistd.h> // Required for: chdir() (POSIX) [Used in LoadOBJ()]
125 #define CHDIR chdir
126 #endif
127
128 //----------------------------------------------------------------------------------
129 // Defines and Macros
130 //----------------------------------------------------------------------------------
131 #ifndef MAX_MATERIAL_MAPS
132 #define MAX_MATERIAL_MAPS 12 // Maximum number of maps supported
133 #endif
134 #ifndef MAX_MESH_VERTEX_BUFFERS
135 #if SUPPORT_GPU_SKINNING
136 // NOTE: Two additional vertex buffers required to store bone indices and bone weights
137 // WARNING: Some GPUs could not support more than 8 VBOs
138 #define MAX_MESH_VERTEX_BUFFERS 9 // Maximum vertex buffers (VBO) per mesh
139 #else
140 #define MAX_MESH_VERTEX_BUFFERS 7 // Maximum vertex buffers (VBO) per mesh
141 #endif
142 #endif
143 #ifndef MAX_FILEPATH_LENGTH
144 #define MAX_FILEPATH_LENGTH 4096 // Maximum length for filepaths (Linux PATH_MAX default value)
145 #endif
146
147 //----------------------------------------------------------------------------------
148 // Types and Structures Definition
149 //----------------------------------------------------------------------------------
150 // ...
151
152 //----------------------------------------------------------------------------------
153 // Global Variables Definition
154 //----------------------------------------------------------------------------------
155 // ...
156
157 //----------------------------------------------------------------------------------
158 // Module Internal Functions Declaration
159 //----------------------------------------------------------------------------------
160 #if SUPPORT_FILEFORMAT_OBJ
161 static Model LoadOBJ(const char *fileName); // Load OBJ mesh data
162 #endif
163 #if SUPPORT_FILEFORMAT_IQM
164 static Model LoadIQM(const char *fileName); // Load IQM mesh data
165 static ModelAnimation *LoadModelAnimationsIQM(const char *fileName, int *animCount); // Load IQM animation data
166 #endif
167 #if SUPPORT_FILEFORMAT_GLTF
168 static Model LoadGLTF(const char *fileName); // Load GLTF mesh data
169 static ModelAnimation *LoadModelAnimationsGLTF(const char *fileName, int *animCount); // Load GLTF animation data
170 #endif
171 #if SUPPORT_FILEFORMAT_VOX
172 static Model LoadVOX(const char *filename); // Load VOX mesh data
173 #endif
174 #if SUPPORT_FILEFORMAT_M3D
175 static Model LoadM3D(const char *filename); // Load M3D mesh data
176 static ModelAnimation *LoadModelAnimationsM3D(const char *fileName, int *animCount); // Load M3D animation data
177 #endif
178 #if SUPPORT_FILEFORMAT_OBJ || SUPPORT_FILEFORMAT_MTL
179 static void ProcessMaterialsOBJ(Material *rayMaterials, tinyobj_material_t *materials, int materialCount); // Process obj materials
180 #endif
181
182 // Update model vertex data (positions and normals)
183 static void UpdateModelAnimationVertexBuffers(Model model);
184
185 //----------------------------------------------------------------------------------
186 // Module Functions Definition
187 //----------------------------------------------------------------------------------
188 // Draw a line in 3D world space
189 void DrawLine3D(Vector3 startPos, Vector3 endPos, Color color)
190 {
191 rlBegin(RL_LINES);
192 rlColor4ub(color.r, color.g, color.b, color.a);
193 rlVertex3f(startPos.x, startPos.y, startPos.z);
194 rlVertex3f(endPos.x, endPos.y, endPos.z);
195 rlEnd();
196 }
197
198 // Draw a point in 3D space, actually a small line
199 // WARNING: OpenGL ES 2.0 does not support point mode drawing
200 void DrawPoint3D(Vector3 position, Color color)
201 {
202 rlPushMatrix();
203 rlTranslatef(position.x, position.y, position.z);
204 rlBegin(RL_LINES);
205 rlColor4ub(color.r, color.g, color.b, color.a);
206 rlVertex3f(0.0f, 0.0f, 0.0f);
207 rlVertex3f(0.0f, 0.0f, 0.1f);
208 rlEnd();
209 rlPopMatrix();
210 }
211
212 // Draw a circle in 3D world space
213 void DrawCircle3D(Vector3 center, float radius, Vector3 rotationAxis, float rotationAngle, Color color)
214 {
215 rlPushMatrix();
216 rlTranslatef(center.x, center.y, center.z);
217 rlRotatef(rotationAngle, rotationAxis.x, rotationAxis.y, rotationAxis.z);
218
219 rlBegin(RL_LINES);
220 for (int i = 0; i < 360; i += 10)
221 {
222 rlColor4ub(color.r, color.g, color.b, color.a);
223
224 rlVertex3f(sinf(DEG2RAD*i)*radius, cosf(DEG2RAD*i)*radius, 0.0f);
225 rlVertex3f(sinf(DEG2RAD*(i + 10))*radius, cosf(DEG2RAD*(i + 10))*radius, 0.0f);
226 }
227 rlEnd();
228 rlPopMatrix();
229 }
230
231 // Draw a color-filled triangle (vertex in counter-clockwise order!)
232 void DrawTriangle3D(Vector3 v1, Vector3 v2, Vector3 v3, Color color)
233 {
234 rlBegin(RL_TRIANGLES);
235 rlColor4ub(color.r, color.g, color.b, color.a);
236 rlVertex3f(v1.x, v1.y, v1.z);
237 rlVertex3f(v2.x, v2.y, v2.z);
238 rlVertex3f(v3.x, v3.y, v3.z);
239 rlEnd();
240 }
241
242 // Draw a triangle strip defined by points
243 void DrawTriangleStrip3D(const Vector3 *points, int pointCount, Color color)
244 {
245 if (pointCount < 3) return; // Security check
246
247 rlBegin(RL_TRIANGLES);
248 rlColor4ub(color.r, color.g, color.b, color.a);
249
250 for (int i = 2; i < pointCount; i++)
251 {
252 if ((i%2) == 0)
253 {
254 rlVertex3f(points[i].x, points[i].y, points[i].z);
255 rlVertex3f(points[i - 2].x, points[i - 2].y, points[i - 2].z);
256 rlVertex3f(points[i - 1].x, points[i - 1].y, points[i - 1].z);
257 }
258 else
259 {
260 rlVertex3f(points[i].x, points[i].y, points[i].z);
261 rlVertex3f(points[i - 1].x, points[i - 1].y, points[i - 1].z);
262 rlVertex3f(points[i - 2].x, points[i - 2].y, points[i - 2].z);
263 }
264 }
265 rlEnd();
266 }
267
268 // Draw cube
269 // NOTE: Cube position is the center position
270 void DrawCube(Vector3 position, float width, float height, float length, Color color)
271 {
272 float x = 0.0f;
273 float y = 0.0f;
274 float z = 0.0f;
275
276 rlPushMatrix();
277 // NOTE: Transformation is applied in inverse order (scale -> rotate -> translate)
278 rlTranslatef(position.x, position.y, position.z);
279 //rlRotatef(45, 0, 1, 0);
280 //rlScalef(1.0f, 1.0f, 1.0f); // NOTE: Vertices are directly scaled on definition
281
282 rlBegin(RL_TRIANGLES);
283 rlColor4ub(color.r, color.g, color.b, color.a);
284
285 // Front face
286 rlNormal3f(0.0f, 0.0f, 1.0f);
287 rlVertex3f(x - width/2, y - height/2, z + length/2); // Bottom Left
288 rlVertex3f(x + width/2, y - height/2, z + length/2); // Bottom Right
289 rlVertex3f(x - width/2, y + height/2, z + length/2); // Top Left
290
291 rlVertex3f(x + width/2, y + height/2, z + length/2); // Top Right
292 rlVertex3f(x - width/2, y + height/2, z + length/2); // Top Left
293 rlVertex3f(x + width/2, y - height/2, z + length/2); // Bottom Right
294
295 // Back face
296 rlNormal3f(0.0f, 0.0f, -1.0f);
297 rlVertex3f(x - width/2, y - height/2, z - length/2); // Bottom Left
298 rlVertex3f(x - width/2, y + height/2, z - length/2); // Top Left
299 rlVertex3f(x + width/2, y - height/2, z - length/2); // Bottom Right
300
301 rlVertex3f(x + width/2, y + height/2, z - length/2); // Top Right
302 rlVertex3f(x + width/2, y - height/2, z - length/2); // Bottom Right
303 rlVertex3f(x - width/2, y + height/2, z - length/2); // Top Left
304
305 // Top face
306 rlNormal3f(0.0f, 1.0f, 0.0f);
307 rlVertex3f(x - width/2, y + height/2, z - length/2); // Top Left
308 rlVertex3f(x - width/2, y + height/2, z + length/2); // Bottom Left
309 rlVertex3f(x + width/2, y + height/2, z + length/2); // Bottom Right
310
311 rlVertex3f(x + width/2, y + height/2, z - length/2); // Top Right
312 rlVertex3f(x - width/2, y + height/2, z - length/2); // Top Left
313 rlVertex3f(x + width/2, y + height/2, z + length/2); // Bottom Right
314
315 // Bottom face
316 rlNormal3f(0.0f, -1.0f, 0.0f);
317 rlVertex3f(x - width/2, y - height/2, z - length/2); // Top Left
318 rlVertex3f(x + width/2, y - height/2, z + length/2); // Bottom Right
319 rlVertex3f(x - width/2, y - height/2, z + length/2); // Bottom Left
320
321 rlVertex3f(x + width/2, y - height/2, z - length/2); // Top Right
322 rlVertex3f(x + width/2, y - height/2, z + length/2); // Bottom Right
323 rlVertex3f(x - width/2, y - height/2, z - length/2); // Top Left
324
325 // Right face
326 rlNormal3f(1.0f, 0.0f, 0.0f);
327 rlVertex3f(x + width/2, y - height/2, z - length/2); // Bottom Right
328 rlVertex3f(x + width/2, y + height/2, z - length/2); // Top Right
329 rlVertex3f(x + width/2, y + height/2, z + length/2); // Top Left
330
331 rlVertex3f(x + width/2, y - height/2, z + length/2); // Bottom Left
332 rlVertex3f(x + width/2, y - height/2, z - length/2); // Bottom Right
333 rlVertex3f(x + width/2, y + height/2, z + length/2); // Top Left
334
335 // Left face
336 rlNormal3f(-1.0f, 0.0f, 0.0f);
337 rlVertex3f(x - width/2, y - height/2, z - length/2); // Bottom Right
338 rlVertex3f(x - width/2, y + height/2, z + length/2); // Top Left
339 rlVertex3f(x - width/2, y + height/2, z - length/2); // Top Right
340
341 rlVertex3f(x - width/2, y - height/2, z + length/2); // Bottom Left
342 rlVertex3f(x - width/2, y + height/2, z + length/2); // Top Left
343 rlVertex3f(x - width/2, y - height/2, z - length/2); // Bottom Right
344 rlEnd();
345 rlPopMatrix();
346 }
347
348 // Draw cube (Vector version)
349 void DrawCubeV(Vector3 position, Vector3 size, Color color)
350 {
351 DrawCube(position, size.x, size.y, size.z, color);
352 }
353
354 // Draw cube wires
355 void DrawCubeWires(Vector3 position, float width, float height, float length, Color color)
356 {
357 float x = 0.0f;
358 float y = 0.0f;
359 float z = 0.0f;
360
361 rlPushMatrix();
362 rlTranslatef(position.x, position.y, position.z);
363
364 rlBegin(RL_LINES);
365 rlColor4ub(color.r, color.g, color.b, color.a);
366
367 // Front face
368 //------------------------------------------------------------------
369 // Bottom line
370 rlVertex3f(x - width/2, y - height/2, z + length/2); // Bottom left
371 rlVertex3f(x + width/2, y - height/2, z + length/2); // Bottom right
372
373 // Left line
374 rlVertex3f(x + width/2, y - height/2, z + length/2); // Bottom right
375 rlVertex3f(x + width/2, y + height/2, z + length/2); // Top right
376
377 // Top line
378 rlVertex3f(x + width/2, y + height/2, z + length/2); // Top right
379 rlVertex3f(x - width/2, y + height/2, z + length/2); // Top left
380
381 // Right line
382 rlVertex3f(x - width/2, y + height/2, z + length/2); // Top left
383 rlVertex3f(x - width/2, y - height/2, z + length/2); // Bottom left
384
385 // Back face
386 //------------------------------------------------------------------
387 // Bottom line
388 rlVertex3f(x - width/2, y - height/2, z - length/2); // Bottom left
389 rlVertex3f(x + width/2, y - height/2, z - length/2); // Bottom right
390
391 // Left line
392 rlVertex3f(x + width/2, y - height/2, z - length/2); // Bottom right
393 rlVertex3f(x + width/2, y + height/2, z - length/2); // Top right
394
395 // Top line
396 rlVertex3f(x + width/2, y + height/2, z - length/2); // Top right
397 rlVertex3f(x - width/2, y + height/2, z - length/2); // Top left
398
399 // Right line
400 rlVertex3f(x - width/2, y + height/2, z - length/2); // Top left
401 rlVertex3f(x - width/2, y - height/2, z - length/2); // Bottom left
402
403 // Top face
404 //------------------------------------------------------------------
405 // Left line
406 rlVertex3f(x - width/2, y + height/2, z + length/2); // Top left front
407 rlVertex3f(x - width/2, y + height/2, z - length/2); // Top left back
408
409 // Right line
410 rlVertex3f(x + width/2, y + height/2, z + length/2); // Top right front
411 rlVertex3f(x + width/2, y + height/2, z - length/2); // Top right back
412
413 // Bottom face
414 //------------------------------------------------------------------
415 // Left line
416 rlVertex3f(x - width/2, y - height/2, z + length/2); // Top left front
417 rlVertex3f(x - width/2, y - height/2, z - length/2); // Top left back
418
419 // Right line
420 rlVertex3f(x + width/2, y - height/2, z + length/2); // Top right front
421 rlVertex3f(x + width/2, y - height/2, z - length/2); // Top right back
422 rlEnd();
423 rlPopMatrix();
424 }
425
426 // Draw cube wires (vector version)
427 void DrawCubeWiresV(Vector3 position, Vector3 size, Color color)
428 {
429 DrawCubeWires(position, size.x, size.y, size.z, color);
430 }
431
432 // Draw sphere
433 void DrawSphere(Vector3 centerPos, float radius, Color color)
434 {
435 DrawSphereEx(centerPos, radius, 16, 16, color);
436 }
437
438 // Draw sphere with extended parameters
439 void DrawSphereEx(Vector3 centerPos, float radius, int rings, int slices, Color color)
440 {
441 #if 0
442 // Basic implementation, do not use it!
443 // For a sphere with 16 rings and 16 slices it requires 8640 cos()/sin() function calls!
444 // New optimized version below only requires 4 cos()/sin() calls
445
446 rlPushMatrix();
447 // NOTE: Transformation is applied in inverse order (scale -> translate)
448 rlTranslatef(centerPos.x, centerPos.y, centerPos.z);
449 rlScalef(radius, radius, radius);
450
451 rlBegin(RL_TRIANGLES);
452 rlColor4ub(color.r, color.g, color.b, color.a);
453
454 for (int i = 0; i < (rings + 2); i++)
455 {
456 for (int j = 0; j < slices; j++)
457 {
458 rlVertex3f(cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*i))*sinf(DEG2RAD*(360.0f*j/slices)),
459 sinf(DEG2RAD*(270 + (180.0f/(rings + 1))*i)),
460 cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*i))*cosf(DEG2RAD*(360.0f*j/slices)));
461 rlVertex3f(cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1)))*sinf(DEG2RAD*(360.0f*(j + 1)/slices)),
462 sinf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1))),
463 cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1)))*cosf(DEG2RAD*(360.0f*(j + 1)/slices)));
464 rlVertex3f(cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1)))*sinf(DEG2RAD*(360.0f*j/slices)),
465 sinf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1))),
466 cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1)))*cosf(DEG2RAD*(360.0f*j/slices)));
467
468 rlVertex3f(cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*i))*sinf(DEG2RAD*(360.0f*j/slices)),
469 sinf(DEG2RAD*(270 + (180.0f/(rings + 1))*i)),
470 cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*i))*cosf(DEG2RAD*(360.0f*j/slices)));
471 rlVertex3f(cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i)))*sinf(DEG2RAD*(360.0f*(j + 1)/slices)),
472 sinf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i))),
473 cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i)))*cosf(DEG2RAD*(360.0f*(j + 1)/slices)));
474 rlVertex3f(cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1)))*sinf(DEG2RAD*(360.0f*(j + 1)/slices)),
475 sinf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1))),
476 cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1)))*cosf(DEG2RAD*(360.0f*(j + 1)/slices)));
477 }
478 }
479 rlEnd();
480 rlPopMatrix();
481 #endif
482
483 rlPushMatrix();
484 // NOTE: Transformation is applied in inverse order (scale -> translate)
485 rlTranslatef(centerPos.x, centerPos.y, centerPos.z);
486 rlScalef(radius, radius, radius);
487
488 rlBegin(RL_TRIANGLES);
489 rlColor4ub(color.r, color.g, color.b, color.a);
490
491 float ringangle = DEG2RAD*(180.0f/(rings + 1)); // Angle between latitudinal parallels
492 float sliceangle = DEG2RAD*(360.0f/slices); // Angle between longitudinal meridians
493
494 float cosring = cosf(ringangle);
495 float sinring = sinf(ringangle);
496 float cosslice = cosf(sliceangle);
497 float sinslice = sinf(sliceangle);
498
499 Vector3 vertices[4] = { 0 }; // Required to store face vertices
500 vertices[2] = (Vector3){ 0, 1, 0 };
501 vertices[3] = (Vector3){ sinring, cosring, 0 };
502
503 for (int i = 0; i < rings + 1; i++)
504 {
505 for (int j = 0; j < slices; j++)
506 {
507 vertices[0] = vertices[2]; // Rotate around y axis to set up vertices for next face
508 vertices[1] = vertices[3];
509 vertices[2] = (Vector3){ cosslice*vertices[2].x - sinslice*vertices[2].z, vertices[2].y, sinslice*vertices[2].x + cosslice*vertices[2].z }; // Rotation matrix around y axis
510 vertices[3] = (Vector3){ cosslice*vertices[3].x - sinslice*vertices[3].z, vertices[3].y, sinslice*vertices[3].x + cosslice*vertices[3].z };
511
512 rlNormal3f(vertices[0].x, vertices[0].y, vertices[0].z);
513 rlVertex3f(vertices[0].x, vertices[0].y, vertices[0].z);
514 rlNormal3f(vertices[3].x, vertices[3].y, vertices[3].z);
515 rlVertex3f(vertices[3].x, vertices[3].y, vertices[3].z);
516 rlNormal3f(vertices[1].x, vertices[1].y, vertices[1].z);
517 rlVertex3f(vertices[1].x, vertices[1].y, vertices[1].z);
518
519 rlNormal3f(vertices[0].x, vertices[0].y, vertices[0].z);
520 rlVertex3f(vertices[0].x, vertices[0].y, vertices[0].z);
521 rlNormal3f(vertices[2].x, vertices[2].y, vertices[2].z);
522 rlVertex3f(vertices[2].x, vertices[2].y, vertices[2].z);
523 rlNormal3f(vertices[3].x, vertices[3].y, vertices[3].z);
524 rlVertex3f(vertices[3].x, vertices[3].y, vertices[3].z);
525 }
526
527 vertices[2] = vertices[3]; // Rotate around z axis to set up starting vertices for next ring
528 vertices[3] = (Vector3){ cosring*vertices[3].x + sinring*vertices[3].y, -sinring*vertices[3].x + cosring*vertices[3].y, vertices[3].z }; // Rotation matrix around z axis
529 }
530 rlEnd();
531 rlPopMatrix();
532 }
533
534 // Draw sphere wires
535 void DrawSphereWires(Vector3 centerPos, float radius, int rings, int slices, Color color)
536 {
537 rlPushMatrix();
538 // NOTE: Transformation is applied in inverse order (scale -> translate)
539 rlTranslatef(centerPos.x, centerPos.y, centerPos.z);
540 rlScalef(radius, radius, radius);
541
542 rlBegin(RL_LINES);
543 rlColor4ub(color.r, color.g, color.b, color.a);
544
545 for (int i = 0; i < (rings + 2); i++)
546 {
547 for (int j = 0; j < slices; j++)
548 {
549 rlVertex3f(cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*i))*sinf(DEG2RAD*(360.0f*j/slices)),
550 sinf(DEG2RAD*(270 + (180.0f/(rings + 1))*i)),
551 cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*i))*cosf(DEG2RAD*(360.0f*j/slices)));
552 rlVertex3f(cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1)))*sinf(DEG2RAD*(360.0f*(j + 1)/slices)),
553 sinf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1))),
554 cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1)))*cosf(DEG2RAD*(360.0f*(j + 1)/slices)));
555
556 rlVertex3f(cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1)))*sinf(DEG2RAD*(360.0f*(j + 1)/slices)),
557 sinf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1))),
558 cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1)))*cosf(DEG2RAD*(360.0f*(j + 1)/slices)));
559 rlVertex3f(cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1)))*sinf(DEG2RAD*(360.0f*j/slices)),
560 sinf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1))),
561 cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1)))*cosf(DEG2RAD*(360.0f*j/slices)));
562
563 rlVertex3f(cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1)))*sinf(DEG2RAD*(360.0f*j/slices)),
564 sinf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1))),
565 cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*(i + 1)))*cosf(DEG2RAD*(360.0f*j/slices)));
566 rlVertex3f(cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*i))*sinf(DEG2RAD*(360.0f*j/slices)),
567 sinf(DEG2RAD*(270 + (180.0f/(rings + 1))*i)),
568 cosf(DEG2RAD*(270 + (180.0f/(rings + 1))*i))*cosf(DEG2RAD*(360.0f*j/slices)));
569 }
570 }
571 rlEnd();
572 rlPopMatrix();
573 }
574
575 // Draw a cylinder
576 // NOTE: It could be also used for pyramid and cone
577 void DrawCylinder(Vector3 position, float radiusTop, float radiusBottom, float height, int sides, Color color)
578 {
579 if (sides < 3) sides = 3;
580
581 const float angleStep = 360.0f/sides;
582
583 rlPushMatrix();
584 rlTranslatef(position.x, position.y, position.z);
585
586 rlBegin(RL_TRIANGLES);
587 rlColor4ub(color.r, color.g, color.b, color.a);
588
589 if (radiusTop > 0)
590 {
591 // Draw Body -------------------------------------------------------------------------------------
592 for (int i = 0; i < sides; i++)
593 {
594 rlVertex3f(sinf(DEG2RAD*i*angleStep)*radiusBottom, 0, cosf(DEG2RAD*i*angleStep)*radiusBottom); //Bottom Left
595 rlVertex3f(sinf(DEG2RAD*(i+1)*angleStep)*radiusBottom, 0, cosf(DEG2RAD*(i+1)*angleStep)*radiusBottom); //Bottom Right
596 rlVertex3f(sinf(DEG2RAD*(i+1)*angleStep)*radiusTop, height, cosf(DEG2RAD*(i+1)*angleStep)*radiusTop); //Top Right
597
598 rlVertex3f(sinf(DEG2RAD*i*angleStep)*radiusTop, height, cosf(DEG2RAD*i*angleStep)*radiusTop); //Top Left
599 rlVertex3f(sinf(DEG2RAD*i*angleStep)*radiusBottom, 0, cosf(DEG2RAD*i*angleStep)*radiusBottom); //Bottom Left
600 rlVertex3f(sinf(DEG2RAD*(i+1)*angleStep)*radiusTop, height, cosf(DEG2RAD*(i+1)*angleStep)*radiusTop); //Top Right
601 }
602
603 // Draw Cap --------------------------------------------------------------------------------------
604 for (int i = 0; i < sides; i++)
605 {
606 rlVertex3f(0, height, 0);
607 rlVertex3f(sinf(DEG2RAD*i*angleStep)*radiusTop, height, cosf(DEG2RAD*i*angleStep)*radiusTop);
608 rlVertex3f(sinf(DEG2RAD*(i+1)*angleStep)*radiusTop, height, cosf(DEG2RAD*(i+1)*angleStep)*radiusTop);
609 }
610 }
611 else
612 {
613 // Draw Cone -------------------------------------------------------------------------------------
614 for (int i = 0; i < sides; i++)
615 {
616 rlVertex3f(0, height, 0);
617 rlVertex3f(sinf(DEG2RAD*i*angleStep)*radiusBottom, 0, cosf(DEG2RAD*i*angleStep)*radiusBottom);
618 rlVertex3f(sinf(DEG2RAD*(i+1)*angleStep)*radiusBottom, 0, cosf(DEG2RAD*(i+1)*angleStep)*radiusBottom);
619 }
620 }
621
622 // Draw Base -----------------------------------------------------------------------------------------
623 for (int i = 0; i < sides; i++)
624 {
625 rlVertex3f(0, 0, 0);
626 rlVertex3f(sinf(DEG2RAD*(i+1)*angleStep)*radiusBottom, 0, cosf(DEG2RAD*(i+1)*angleStep)*radiusBottom);
627 rlVertex3f(sinf(DEG2RAD*i*angleStep)*radiusBottom, 0, cosf(DEG2RAD*i*angleStep)*radiusBottom);
628 }
629
630 rlEnd();
631 rlPopMatrix();
632 }
633
634 // Draw a cylinder with base at startPos and top at endPos
635 // NOTE: It could be also used for pyramid and cone
636 void DrawCylinderEx(Vector3 startPos, Vector3 endPos, float startRadius, float endRadius, int sides, Color color)
637 {
638 if (sides < 3) sides = 3;
639
640 Vector3 direction = { endPos.x - startPos.x, endPos.y - startPos.y, endPos.z - startPos.z };
641 if ((direction.x == 0) && (direction.y == 0) && (direction.z == 0)) return; // Security check
642
643 // Construct a basis of the base and the top face:
644 Vector3 b1 = Vector3Normalize(Vector3Perpendicular(direction));
645 Vector3 b2 = Vector3Normalize(Vector3CrossProduct(b1, direction));
646
647 float baseAngle = (2.0f*PI)/sides;
648
649 rlBegin(RL_TRIANGLES);
650 rlColor4ub(color.r, color.g, color.b, color.a);
651
652 for (int i = 0; i < sides; i++)
653 {
654 // Compute the four vertices
655 float s1 = sinf(baseAngle*(i + 0))*startRadius;
656 float c1 = cosf(baseAngle*(i + 0))*startRadius;
657 Vector3 w1 = { startPos.x + s1*b1.x + c1*b2.x, startPos.y + s1*b1.y + c1*b2.y, startPos.z + s1*b1.z + c1*b2.z };
658 float s2 = sinf(baseAngle*(i + 1))*startRadius;
659 float c2 = cosf(baseAngle*(i + 1))*startRadius;
660 Vector3 w2 = { startPos.x + s2*b1.x + c2*b2.x, startPos.y + s2*b1.y + c2*b2.y, startPos.z + s2*b1.z + c2*b2.z };
661 float s3 = sinf(baseAngle*(i + 0))*endRadius;
662 float c3 = cosf(baseAngle*(i + 0))*endRadius;
663 Vector3 w3 = { endPos.x + s3*b1.x + c3*b2.x, endPos.y + s3*b1.y + c3*b2.y, endPos.z + s3*b1.z + c3*b2.z };
664 float s4 = sinf(baseAngle*(i + 1))*endRadius;
665 float c4 = cosf(baseAngle*(i + 1))*endRadius;
666 Vector3 w4 = { endPos.x + s4*b1.x + c4*b2.x, endPos.y + s4*b1.y + c4*b2.y, endPos.z + s4*b1.z + c4*b2.z };
667
668 if (startRadius > 0)
669 {
670 rlVertex3f(startPos.x, startPos.y, startPos.z); // |
671 rlVertex3f(w2.x, w2.y, w2.z); // T0
672 rlVertex3f(w1.x, w1.y, w1.z); // |
673 }
674 // w2 x.-----------x startPos
675 rlVertex3f(w1.x, w1.y, w1.z); // | |\'. T0 /
676 rlVertex3f(w2.x, w2.y, w2.z); // T1 | \ '. /
677 rlVertex3f(w3.x, w3.y, w3.z); // | |T \ '. /
678 // | 2 \ T 'x w1
679 rlVertex3f(w2.x, w2.y, w2.z); // | w4 x.---\-1-|---x endPos
680 rlVertex3f(w4.x, w4.y, w4.z); // T2 '. \ |T3/
681 rlVertex3f(w3.x, w3.y, w3.z); // | '. \ | /
682 // '.\|/
683 if (endRadius > 0) // 'x w3
684 {
685 rlVertex3f(endPos.x, endPos.y, endPos.z); // |
686 rlVertex3f(w3.x, w3.y, w3.z); // T3
687 rlVertex3f(w4.x, w4.y, w4.z); // |
688 } //
689 }
690 rlEnd();
691 }
692
693 // Draw a wired cylinder
694 // NOTE: It could be also used for pyramid and cone
695 void DrawCylinderWires(Vector3 position, float radiusTop, float radiusBottom, float height, int sides, Color color)
696 {
697 if (sides < 3) sides = 3;
698
699 const float angleStep = 360.0f/sides;
700
701 rlPushMatrix();
702 rlTranslatef(position.x, position.y, position.z);
703
704 rlBegin(RL_LINES);
705 rlColor4ub(color.r, color.g, color.b, color.a);
706
707 for (int i = 0; i < sides; i++)
708 {
709 rlVertex3f(sinf(DEG2RAD*i*angleStep)*radiusBottom, 0, cosf(DEG2RAD*i*angleStep)*radiusBottom);
710 rlVertex3f(sinf(DEG2RAD*(i+1)*angleStep)*radiusBottom, 0, cosf(DEG2RAD*(i+1)*angleStep)*radiusBottom);
711
712 rlVertex3f(sinf(DEG2RAD*(i+1)*angleStep)*radiusBottom, 0, cosf(DEG2RAD*(i+1)*angleStep)*radiusBottom);
713 rlVertex3f(sinf(DEG2RAD*(i+1)*angleStep)*radiusTop, height, cosf(DEG2RAD*(i+1)*angleStep)*radiusTop);
714
715 rlVertex3f(sinf(DEG2RAD*(i+1)*angleStep)*radiusTop, height, cosf(DEG2RAD*(i+1)*angleStep)*radiusTop);
716 rlVertex3f(sinf(DEG2RAD*i*angleStep)*radiusTop, height, cosf(DEG2RAD*i*angleStep)*radiusTop);
717
718 rlVertex3f(sinf(DEG2RAD*i*angleStep)*radiusTop, height, cosf(DEG2RAD*i*angleStep)*radiusTop);
719 rlVertex3f(sinf(DEG2RAD*i*angleStep)*radiusBottom, 0, cosf(DEG2RAD*i*angleStep)*radiusBottom);
720 }
721 rlEnd();
722 rlPopMatrix();
723 }
724
725 // Draw a wired cylinder with base at startPos and top at endPos
726 // NOTE: It could be also used for pyramid and cone
727 void DrawCylinderWiresEx(Vector3 startPos, Vector3 endPos, float startRadius, float endRadius, int sides, Color color)
728 {
729 if (sides < 3) sides = 3;
730
731 Vector3 direction = { endPos.x - startPos.x, endPos.y - startPos.y, endPos.z - startPos.z };
732 if ((direction.x == 0) && (direction.y == 0) && (direction.z == 0)) return; // Security check
733
734 // Construct a basis of the base and the top face:
735 Vector3 b1 = Vector3Normalize(Vector3Perpendicular(direction));
736 Vector3 b2 = Vector3Normalize(Vector3CrossProduct(b1, direction));
737
738 float baseAngle = (2.0f*PI)/sides;
739
740 rlBegin(RL_LINES);
741 rlColor4ub(color.r, color.g, color.b, color.a);
742
743 for (int i = 0; i < sides; i++)
744 {
745 // Compute the four vertices
746 float s1 = sinf(baseAngle*(i + 0))*startRadius;
747 float c1 = cosf(baseAngle*(i + 0))*startRadius;
748 Vector3 w1 = { startPos.x + s1*b1.x + c1*b2.x, startPos.y + s1*b1.y + c1*b2.y, startPos.z + s1*b1.z + c1*b2.z };
749 float s2 = sinf(baseAngle*(i + 1))*startRadius;
750 float c2 = cosf(baseAngle*(i + 1))*startRadius;
751 Vector3 w2 = { startPos.x + s2*b1.x + c2*b2.x, startPos.y + s2*b1.y + c2*b2.y, startPos.z + s2*b1.z + c2*b2.z };
752 float s3 = sinf(baseAngle*(i + 0))*endRadius;
753 float c3 = cosf(baseAngle*(i + 0))*endRadius;
754 Vector3 w3 = { endPos.x + s3*b1.x + c3*b2.x, endPos.y + s3*b1.y + c3*b2.y, endPos.z + s3*b1.z + c3*b2.z };
755 float s4 = sinf(baseAngle*(i + 1))*endRadius;
756 float c4 = cosf(baseAngle*(i + 1))*endRadius;
757 Vector3 w4 = { endPos.x + s4*b1.x + c4*b2.x, endPos.y + s4*b1.y + c4*b2.y, endPos.z + s4*b1.z + c4*b2.z };
758
759 rlVertex3f(w1.x, w1.y, w1.z);
760 rlVertex3f(w2.x, w2.y, w2.z);
761
762 rlVertex3f(w1.x, w1.y, w1.z);
763 rlVertex3f(w3.x, w3.y, w3.z);
764
765 rlVertex3f(w3.x, w3.y, w3.z);
766 rlVertex3f(w4.x, w4.y, w4.z);
767 }
768 rlEnd();
769 }
770
771 // Draw a capsule with the center of its sphere caps at startPos and endPos
772 void DrawCapsule(Vector3 startPos, Vector3 endPos, float radius, int slices, int rings, Color color)
773 {
774 if (slices < 3) slices = 3;
775
776 Vector3 direction = { endPos.x - startPos.x, endPos.y - startPos.y, endPos.z - startPos.z };
777
778 // draw a sphere if start and end points are the same
779 bool sphereCase = (direction.x == 0) && (direction.y == 0) && (direction.z == 0);
780 if (sphereCase) direction = (Vector3){0.0f, 1.0f, 0.0f};
781
782 // Construct a basis of the base and the caps:
783 Vector3 b0 = Vector3Normalize(direction);
784 Vector3 b1 = Vector3Normalize(Vector3Perpendicular(direction));
785 Vector3 b2 = Vector3Normalize(Vector3CrossProduct(b1, direction));
786 Vector3 capCenter = endPos;
787
788 float baseSliceAngle = (2.0f*PI)/slices;
789 float baseRingAngle = PI*0.5f/rings;
790
791 rlBegin(RL_TRIANGLES);
792 rlColor4ub(color.r, color.g, color.b, color.a);
793
794 // render both caps
795 for (int c = 0; c < 2; c++)
796 {
797 for (int i = 0; i < rings; i++)
798 {
799 for (int j = 0; j < slices; j++)
800 {
801 // Building up the rings from capCenter in the direction of the 'direction' vector computed earlier
802
803 // Compute the four vertices
804 float ringSin1 = sinf(baseSliceAngle*(j + 0))*cosf(baseRingAngle*( i + 0 ));
805 float ringCos1 = cosf(baseSliceAngle*(j + 0))*cosf(baseRingAngle*( i + 0 ));
806 Vector3 w1 = (Vector3){
807 capCenter.x + (sinf(baseRingAngle*( i + 0 ))*b0.x + ringSin1*b1.x + ringCos1*b2.x)*radius,
808 capCenter.y + (sinf(baseRingAngle*( i + 0 ))*b0.y + ringSin1*b1.y + ringCos1*b2.y)*radius,
809 capCenter.z + (sinf(baseRingAngle*( i + 0 ))*b0.z + ringSin1*b1.z + ringCos1*b2.z)*radius
810 };
811 float ringSin2 = sinf(baseSliceAngle*(j + 1))*cosf(baseRingAngle*( i + 0 ));
812 float ringCos2 = cosf(baseSliceAngle*(j + 1))*cosf(baseRingAngle*( i + 0 ));
813 Vector3 w2 = (Vector3){
814 capCenter.x + (sinf(baseRingAngle*( i + 0 ))*b0.x + ringSin2*b1.x + ringCos2*b2.x)*radius,
815 capCenter.y + (sinf(baseRingAngle*( i + 0 ))*b0.y + ringSin2*b1.y + ringCos2*b2.y)*radius,
816 capCenter.z + (sinf(baseRingAngle*( i + 0 ))*b0.z + ringSin2*b1.z + ringCos2*b2.z)*radius
817 };
818
819 float ringSin3 = sinf(baseSliceAngle*(j + 0))*cosf(baseRingAngle*( i + 1 ));
820 float ringCos3 = cosf(baseSliceAngle*(j + 0))*cosf(baseRingAngle*( i + 1 ));
821 Vector3 w3 = (Vector3){
822 capCenter.x + (sinf(baseRingAngle*( i + 1 ))*b0.x + ringSin3*b1.x + ringCos3*b2.x)*radius,
823 capCenter.y + (sinf(baseRingAngle*( i + 1 ))*b0.y + ringSin3*b1.y + ringCos3*b2.y)*radius,
824 capCenter.z + (sinf(baseRingAngle*( i + 1 ))*b0.z + ringSin3*b1.z + ringCos3*b2.z)*radius
825 };
826 float ringSin4 = sinf(baseSliceAngle*(j + 1))*cosf(baseRingAngle*( i + 1 ));
827 float ringCos4 = cosf(baseSliceAngle*(j + 1))*cosf(baseRingAngle*( i + 1 ));
828 Vector3 w4 = (Vector3){
829 capCenter.x + (sinf(baseRingAngle*( i + 1 ))*b0.x + ringSin4*b1.x + ringCos4*b2.x)*radius,
830 capCenter.y + (sinf(baseRingAngle*( i + 1 ))*b0.y + ringSin4*b1.y + ringCos4*b2.y)*radius,
831 capCenter.z + (sinf(baseRingAngle*( i + 1 ))*b0.z + ringSin4*b1.z + ringCos4*b2.z)*radius
832 };
833
834 // Make sure cap triangle normals are facing outwards
835 if (c == 0)
836 {
837 rlVertex3f(w1.x, w1.y, w1.z);
838 rlVertex3f(w2.x, w2.y, w2.z);
839 rlVertex3f(w3.x, w3.y, w3.z);
840
841 rlVertex3f(w2.x, w2.y, w2.z);
842 rlVertex3f(w4.x, w4.y, w4.z);
843 rlVertex3f(w3.x, w3.y, w3.z);
844 }
845 else
846 {
847 rlVertex3f(w1.x, w1.y, w1.z);
848 rlVertex3f(w3.x, w3.y, w3.z);
849 rlVertex3f(w2.x, w2.y, w2.z);
850
851 rlVertex3f(w2.x, w2.y, w2.z);
852 rlVertex3f(w3.x, w3.y, w3.z);
853 rlVertex3f(w4.x, w4.y, w4.z);
854 }
855 }
856 }
857 capCenter = startPos;
858 b0 = Vector3Scale(b0, -1.0f);
859 }
860 // render middle
861 if (!sphereCase)
862 {
863 for (int j = 0; j < slices; j++)
864 {
865 // compute the four vertices
866 float ringSin1 = sinf(baseSliceAngle*(j + 0))*radius;
867 float ringCos1 = cosf(baseSliceAngle*(j + 0))*radius;
868 Vector3 w1 = {
869 startPos.x + ringSin1*b1.x + ringCos1*b2.x,
870 startPos.y + ringSin1*b1.y + ringCos1*b2.y,
871 startPos.z + ringSin1*b1.z + ringCos1*b2.z
872 };
873 float ringSin2 = sinf(baseSliceAngle*(j + 1))*radius;
874 float ringCos2 = cosf(baseSliceAngle*(j + 1))*radius;
875 Vector3 w2 = {
876 startPos.x + ringSin2*b1.x + ringCos2*b2.x,
877 startPos.y + ringSin2*b1.y + ringCos2*b2.y,
878 startPos.z + ringSin2*b1.z + ringCos2*b2.z
879 };
880
881 float ringSin3 = sinf(baseSliceAngle*(j + 0))*radius;
882 float ringCos3 = cosf(baseSliceAngle*(j + 0))*radius;
883 Vector3 w3 = {
884 endPos.x + ringSin3*b1.x + ringCos3*b2.x,
885 endPos.y + ringSin3*b1.y + ringCos3*b2.y,
886 endPos.z + ringSin3*b1.z + ringCos3*b2.z
887 };
888 float ringSin4 = sinf(baseSliceAngle*(j + 1))*radius;
889 float ringCos4 = cosf(baseSliceAngle*(j + 1))*radius;
890 Vector3 w4 = {
891 endPos.x + ringSin4*b1.x + ringCos4*b2.x,
892 endPos.y + ringSin4*b1.y + ringCos4*b2.y,
893 endPos.z + ringSin4*b1.z + ringCos4*b2.z
894 };
895 // w2 x.-----------x startPos
896 rlVertex3f(w1.x, w1.y, w1.z); // | |\'. T0 /
897 rlVertex3f(w2.x, w2.y, w2.z); // T1 | \ '. /
898 rlVertex3f(w3.x, w3.y, w3.z); // | |T \ '. /
899 // | 2 \ T 'x w1
900 rlVertex3f(w2.x, w2.y, w2.z); // | w4 x.---\-1-|---x endPos
901 rlVertex3f(w4.x, w4.y, w4.z); // T2 '. \ |T3/
902 rlVertex3f(w3.x, w3.y, w3.z); // | '. \ | /
903 // '.\|/
904 // 'x w3
905 }
906 }
907 rlEnd();
908 }
909
910 // Draw capsule wires with the center of its sphere caps at startPos and endPos
911 void DrawCapsuleWires(Vector3 startPos, Vector3 endPos, float radius, int slices, int rings, Color color)
912 {
913 if (slices < 3) slices = 3;
914
915 Vector3 direction = { endPos.x - startPos.x, endPos.y - startPos.y, endPos.z - startPos.z };
916
917 // draw a sphere if start and end points are the same
918 bool sphereCase = (direction.x == 0) && (direction.y == 0) && (direction.z == 0);
919 if (sphereCase) direction = (Vector3){0.0f, 1.0f, 0.0f};
920
921 // Construct a basis of the base and the caps:
922 Vector3 b0 = Vector3Normalize(direction);
923 Vector3 b1 = Vector3Normalize(Vector3Perpendicular(direction));
924 Vector3 b2 = Vector3Normalize(Vector3CrossProduct(b1, direction));
925 Vector3 capCenter = endPos;
926
927 float baseSliceAngle = (2.0f*PI)/slices;
928 float baseRingAngle = PI*0.5f/rings;
929
930 rlBegin(RL_LINES);
931 rlColor4ub(color.r, color.g, color.b, color.a);
932
933 // render both caps
934 for (int c = 0; c < 2; c++)
935 {
936 for (int i = 0; i < rings; i++)
937 {
938 for (int j = 0; j < slices; j++)
939 {
940 // Building up the rings from capCenter in the direction of the 'direction' vector computed earlier
941
942 // Compute the four vertices
943 float ringSin1 = sinf(baseSliceAngle*(j + 0))*cosf(baseRingAngle*( i + 0 ));
944 float ringCos1 = cosf(baseSliceAngle*(j + 0))*cosf(baseRingAngle*( i + 0 ));
945 Vector3 w1 = (Vector3){
946 capCenter.x + (sinf(baseRingAngle*( i + 0 ))*b0.x + ringSin1*b1.x + ringCos1*b2.x)*radius,
947 capCenter.y + (sinf(baseRingAngle*( i + 0 ))*b0.y + ringSin1*b1.y + ringCos1*b2.y)*radius,
948 capCenter.z + (sinf(baseRingAngle*( i + 0 ))*b0.z + ringSin1*b1.z + ringCos1*b2.z)*radius
949 };
950 float ringSin2 = sinf(baseSliceAngle*(j + 1))*cosf(baseRingAngle*( i + 0 ));
951 float ringCos2 = cosf(baseSliceAngle*(j + 1))*cosf(baseRingAngle*( i + 0 ));
952 Vector3 w2 = (Vector3){
953 capCenter.x + (sinf(baseRingAngle*( i + 0 ))*b0.x + ringSin2*b1.x + ringCos2*b2.x)*radius,
954 capCenter.y + (sinf(baseRingAngle*( i + 0 ))*b0.y + ringSin2*b1.y + ringCos2*b2.y)*radius,
955 capCenter.z + (sinf(baseRingAngle*( i + 0 ))*b0.z + ringSin2*b1.z + ringCos2*b2.z)*radius
956 };
957
958 float ringSin3 = sinf(baseSliceAngle*(j + 0))*cosf(baseRingAngle*( i + 1 ));
959 float ringCos3 = cosf(baseSliceAngle*(j + 0))*cosf(baseRingAngle*( i + 1 ));
960 Vector3 w3 = (Vector3){
961 capCenter.x + (sinf(baseRingAngle*( i + 1 ))*b0.x + ringSin3*b1.x + ringCos3*b2.x)*radius,
962 capCenter.y + (sinf(baseRingAngle*( i + 1 ))*b0.y + ringSin3*b1.y + ringCos3*b2.y)*radius,
963 capCenter.z + (sinf(baseRingAngle*( i + 1 ))*b0.z + ringSin3*b1.z + ringCos3*b2.z)*radius
964 };
965 float ringSin4 = sinf(baseSliceAngle*(j + 1))*cosf(baseRingAngle*( i + 1 ));
966 float ringCos4 = cosf(baseSliceAngle*(j + 1))*cosf(baseRingAngle*( i + 1 ));
967 Vector3 w4 = (Vector3){
968 capCenter.x + (sinf(baseRingAngle*( i + 1 ))*b0.x + ringSin4*b1.x + ringCos4*b2.x)*radius,
969 capCenter.y + (sinf(baseRingAngle*( i + 1 ))*b0.y + ringSin4*b1.y + ringCos4*b2.y)*radius,
970 capCenter.z + (sinf(baseRingAngle*( i + 1 ))*b0.z + ringSin4*b1.z + ringCos4*b2.z)*radius
971 };
972
973 rlVertex3f(w1.x, w1.y, w1.z);
974 rlVertex3f(w2.x, w2.y, w2.z);
975
976 rlVertex3f(w2.x, w2.y, w2.z);
977 rlVertex3f(w3.x, w3.y, w3.z);
978
979 rlVertex3f(w1.x, w1.y, w1.z);
980 rlVertex3f(w3.x, w3.y, w3.z);
981
982 rlVertex3f(w2.x, w2.y, w2.z);
983 rlVertex3f(w4.x, w4.y, w4.z);
984
985 rlVertex3f(w3.x, w3.y, w3.z);
986 rlVertex3f(w4.x, w4.y, w4.z);
987 }
988 }
989 capCenter = startPos;
990 b0 = Vector3Scale(b0, -1.0f);
991 }
992 // render middle
993 if (!sphereCase)
994 {
995 for (int j = 0; j < slices; j++)
996 {
997 // compute the four vertices
998 float ringSin1 = sinf(baseSliceAngle*(j + 0))*radius;
999 float ringCos1 = cosf(baseSliceAngle*(j + 0))*radius;
1000 Vector3 w1 = {
1001 startPos.x + ringSin1*b1.x + ringCos1*b2.x,
1002 startPos.y + ringSin1*b1.y + ringCos1*b2.y,
1003 startPos.z + ringSin1*b1.z + ringCos1*b2.z
1004 };
1005 float ringSin2 = sinf(baseSliceAngle*(j + 1))*radius;
1006 float ringCos2 = cosf(baseSliceAngle*(j + 1))*radius;
1007 Vector3 w2 = {
1008 startPos.x + ringSin2*b1.x + ringCos2*b2.x,
1009 startPos.y + ringSin2*b1.y + ringCos2*b2.y,
1010 startPos.z + ringSin2*b1.z + ringCos2*b2.z
1011 };
1012
1013 float ringSin3 = sinf(baseSliceAngle*(j + 0))*radius;
1014 float ringCos3 = cosf(baseSliceAngle*(j + 0))*radius;
1015 Vector3 w3 = {
1016 endPos.x + ringSin3*b1.x + ringCos3*b2.x,
1017 endPos.y + ringSin3*b1.y + ringCos3*b2.y,
1018 endPos.z + ringSin3*b1.z + ringCos3*b2.z
1019 };
1020 float ringSin4 = sinf(baseSliceAngle*(j + 1))*radius;
1021 float ringCos4 = cosf(baseSliceAngle*(j + 1))*radius;
1022 Vector3 w4 = {
1023 endPos.x + ringSin4*b1.x + ringCos4*b2.x,
1024 endPos.y + ringSin4*b1.y + ringCos4*b2.y,
1025 endPos.z + ringSin4*b1.z + ringCos4*b2.z
1026 };
1027
1028 rlVertex3f(w1.x, w1.y, w1.z);
1029 rlVertex3f(w3.x, w3.y, w3.z);
1030
1031 rlVertex3f(w2.x, w2.y, w2.z);
1032 rlVertex3f(w4.x, w4.y, w4.z);
1033
1034 rlVertex3f(w2.x, w2.y, w2.z);
1035 rlVertex3f(w3.x, w3.y, w3.z);
1036 }
1037 }
1038 rlEnd();
1039 }
1040
1041 // Draw a plane
1042 void DrawPlane(Vector3 centerPos, Vector2 size, Color color)
1043 {
1044 // NOTE: Plane is always created on XZ ground
1045 rlPushMatrix();
1046 rlTranslatef(centerPos.x, centerPos.y, centerPos.z);
1047 rlScalef(size.x, 1.0f, size.y);
1048
1049 rlBegin(RL_QUADS);
1050 rlColor4ub(color.r, color.g, color.b, color.a);
1051 rlNormal3f(0.0f, 1.0f, 0.0f);
1052
1053 rlVertex3f(-0.5f, 0.0f, -0.5f);
1054 rlVertex3f(-0.5f, 0.0f, 0.5f);
1055 rlVertex3f(0.5f, 0.0f, 0.5f);
1056 rlVertex3f(0.5f, 0.0f, -0.5f);
1057 rlEnd();
1058 rlPopMatrix();
1059 }
1060
1061 // Draw a ray line
1062 void DrawRay(Ray ray, Color color)
1063 {
1064 float scale = 10000;
1065
1066 rlBegin(RL_LINES);
1067 rlColor4ub(color.r, color.g, color.b, color.a);
1068 rlColor4ub(color.r, color.g, color.b, color.a);
1069
1070 rlVertex3f(ray.position.x, ray.position.y, ray.position.z);
1071 rlVertex3f(ray.position.x + ray.direction.x*scale, ray.position.y + ray.direction.y*scale, ray.position.z + ray.direction.z*scale);
1072 rlEnd();
1073 }
1074
1075 // Draw a grid centered at (0, 0, 0)
1076 void DrawGrid(int slices, float spacing)
1077 {
1078 int halfSlices = slices/2;
1079
1080 rlBegin(RL_LINES);
1081 for (int i = -halfSlices; i <= halfSlices; i++)
1082 {
1083 if (i == 0)
1084 {
1085 rlColor3f(0.5f, 0.5f, 0.5f);
1086 }
1087 else
1088 {
1089 rlColor3f(0.75f, 0.75f, 0.75f);
1090 }
1091
1092 rlVertex3f((float)i*spacing, 0.0f, (float)-halfSlices*spacing);
1093 rlVertex3f((float)i*spacing, 0.0f, (float)halfSlices*spacing);
1094
1095 rlVertex3f((float)-halfSlices*spacing, 0.0f, (float)i*spacing);
1096 rlVertex3f((float)halfSlices*spacing, 0.0f, (float)i*spacing);
1097 }
1098 rlEnd();
1099 }
1100
1101 // Load model from files (mesh and material)
1102 Model LoadModel(const char *fileName)
1103 {
1104 Model model = { 0 };
1105
1106 #if SUPPORT_FILEFORMAT_OBJ
1107 if (IsFileExtension(fileName, ".obj")) model = LoadOBJ(fileName);
1108 #endif
1109 #if SUPPORT_FILEFORMAT_IQM
1110 if (IsFileExtension(fileName, ".iqm")) model = LoadIQM(fileName);
1111 #endif
1112 #if SUPPORT_FILEFORMAT_GLTF
1113 if (IsFileExtension(fileName, ".gltf") || IsFileExtension(fileName, ".glb")) model = LoadGLTF(fileName);
1114 #endif
1115 #if SUPPORT_FILEFORMAT_VOX
1116 if (IsFileExtension(fileName, ".vox")) model = LoadVOX(fileName);
1117 #endif
1118 #if SUPPORT_FILEFORMAT_M3D
1119 if (IsFileExtension(fileName, ".m3d")) model = LoadM3D(fileName);
1120 #endif
1121
1122 // Make sure model transform is set to identity matrix!
1123 model.transform = MatrixIdentity();
1124
1125 if ((model.meshCount != 0) && (model.meshes != NULL))
1126 {
1127 // Upload vertex data to GPU (static meshes)
1128 for (int i = 0; i < model.meshCount; i++) UploadMesh(&model.meshes[i], false);
1129 }
1130 else TRACELOG(LOG_WARNING, "MESH: [%s] Failed to load model mesh(es) data", fileName);
1131
1132 if (model.materialCount == 0)
1133 {
1134 TRACELOG(LOG_WARNING, "MATERIAL: [%s] Failed to load model material data, default to white material", fileName);
1135
1136 model.materialCount = 1;
1137 model.materials = (Material *)RL_CALLOC(model.materialCount, sizeof(Material));
1138 model.materials[0] = LoadMaterialDefault();
1139
1140 if (model.meshMaterial == NULL) model.meshMaterial = (int *)RL_CALLOC(model.meshCount, sizeof(int));
1141 }
1142
1143 return model;
1144 }
1145
1146 // Load model from generated mesh
1147 // WARNING: A shallow copy of mesh is generated, passed by value,
1148 // as long as struct contains pointers to data and some values, get a copy
1149 // of mesh pointing to same data as original version... be careful!
1150 Model LoadModelFromMesh(Mesh mesh)
1151 {
1152 Model model = { 0 };
1153
1154 model.transform = MatrixIdentity();
1155
1156 model.meshCount = 1;
1157 model.meshes = (Mesh *)RL_CALLOC(model.meshCount, sizeof(Mesh));
1158 model.meshes[0] = mesh;
1159
1160 model.materialCount = 1;
1161 model.materials = (Material *)RL_CALLOC(model.materialCount, sizeof(Material));
1162 model.materials[0] = LoadMaterialDefault();
1163
1164 model.meshMaterial = (int *)RL_CALLOC(model.meshCount, sizeof(int));
1165 model.meshMaterial[0] = 0; // First material index
1166
1167 return model;
1168 }
1169
1170 // Check if a model is valid (loaded in GPU, VAO/VBOs)
1171 bool IsModelValid(Model model)
1172 {
1173 bool result = false;
1174
1175 if ((model.meshes != NULL) && // Validate model contains some mesh
1176 (model.materials != NULL) && // Validate model contains some material (at least default one)
1177 (model.meshMaterial != NULL) && // Validate mesh-material linkage
1178 (model.meshCount > 0) && // Validate mesh count
1179 (model.materialCount > 0)) result = true; // Validate material count
1180
1181 // NOTE: Many elements could be validated from a model, including every model mesh VAO/VBOs
1182 // but some VBOs could not be used, it depends on Mesh vertex data
1183 for (int i = 0; i < model.meshCount; i++)
1184 {
1185 if ((model.meshes[i].vertices != NULL) && (model.meshes[i].vboId[0] == 0)) { result = false; break; } // Vertex position buffer not uploaded to GPU
1186 if ((model.meshes[i].texcoords != NULL) && (model.meshes[i].vboId[1] == 0)) { result = false; break; } // Vertex textcoords buffer not uploaded to GPU
1187 if ((model.meshes[i].normals != NULL) && (model.meshes[i].vboId[2] == 0)) { result = false; break; } // Vertex normals buffer not uploaded to GPU
1188 if ((model.meshes[i].colors != NULL) && (model.meshes[i].vboId[3] == 0)) { result = false; break; } // Vertex colors buffer not uploaded to GPU
1189 if ((model.meshes[i].tangents != NULL) && (model.meshes[i].vboId[4] == 0)) { result = false; break; } // Vertex tangents buffer not uploaded to GPU
1190 if ((model.meshes[i].texcoords2 != NULL) && (model.meshes[i].vboId[5] == 0)) { result = false; break; } // Vertex texcoords2 buffer not uploaded to GPU
1191 if ((model.meshes[i].indices != NULL) && (model.meshes[i].vboId[6] == 0)) { result = false; break; } // Vertex indices buffer not uploaded to GPU
1192 if ((model.meshes[i].boneIndices != NULL) && (model.meshes[i].vboId[7] == 0)) { result = false; break; } // Vertex boneIndices buffer not uploaded to GPU
1193 if ((model.meshes[i].boneWeights != NULL) && (model.meshes[i].vboId[8] == 0)) { result = false; break; } // Vertex boneWeights buffer not uploaded to GPU
1194
1195 // NOTE: Some OpenGL versions do not support VAO, so avoid below check
1196 //if (model.meshes[i].vaoId == 0) { result = false; break }
1197 }
1198
1199 return result;
1200 }
1201
1202 // Unload model (meshes/materials) from memory (RAM and/or VRAM)
1203 // NOTE: This function takes care of all model elements, for a detailed control
1204 // over them, use UnloadMesh() and UnloadMaterial()
1205 void UnloadModel(Model model)
1206 {
1207 // Unload meshes
1208 for (int i = 0; i < model.meshCount; i++) UnloadMesh(model.meshes[i]);
1209
1210 // Unload materials maps
1211 // NOTE: As the user could be sharing shaders and textures between models,
1212 // don't unload the material but free its maps,
1213 // the user is responsible for freeing models shaders and textures
1214 for (int i = 0; i < model.materialCount; i++) RL_FREE(model.materials[i].maps);
1215
1216 // Unload arrays
1217 RL_FREE(model.meshes);
1218 RL_FREE(model.materials);
1219 RL_FREE(model.meshMaterial);
1220
1221 // Unload animation data
1222 RL_FREE(model.skeleton.bones);
1223 RL_FREE(model.skeleton.bindPose);
1224
1225 TRACELOG(LOG_INFO, "MODEL: Unloaded model (and meshes) from RAM and VRAM");
1226 }
1227
1228 // Compute model bounding box limits (considers all meshes)
1229 BoundingBox GetModelBoundingBox(Model model)
1230 {
1231 BoundingBox bounds = { 0 };
1232
1233 if (model.meshCount > 0)
1234 {
1235 Vector3 temp = { 0 };
1236 bounds = GetMeshBoundingBox(model.meshes[0]);
1237
1238 for (int i = 1; i < model.meshCount; i++)
1239 {
1240 BoundingBox tempBounds = GetMeshBoundingBox(model.meshes[i]);
1241
1242 temp.x = (bounds.min.x < tempBounds.min.x)? bounds.min.x : tempBounds.min.x;
1243 temp.y = (bounds.min.y < tempBounds.min.y)? bounds.min.y : tempBounds.min.y;
1244 temp.z = (bounds.min.z < tempBounds.min.z)? bounds.min.z : tempBounds.min.z;
1245 bounds.min = temp;
1246
1247 temp.x = (bounds.max.x > tempBounds.max.x)? bounds.max.x : tempBounds.max.x;
1248 temp.y = (bounds.max.y > tempBounds.max.y)? bounds.max.y : tempBounds.max.y;
1249 temp.z = (bounds.max.z > tempBounds.max.z)? bounds.max.z : tempBounds.max.z;
1250 bounds.max = temp;
1251 }
1252 }
1253
1254 // Apply model.transform to bounding box
1255 // WARNING: Current BoundingBox structure design does not support rotation transformations,
1256 // in those cases is up to the user to calculate the proper box bounds (8 vertices transformed)
1257 bounds.min = Vector3Transform(bounds.min, model.transform);
1258 bounds.max = Vector3Transform(bounds.max, model.transform);
1259
1260 return bounds;
1261 }
1262
1263 // Upload vertex data into a VAO (if supported) and VBO
1264 void UploadMesh(Mesh *mesh, bool dynamic)
1265 {
1266 if (mesh->vaoId > 0)
1267 {
1268 // Check if mesh has already been loaded in GPU
1269 TRACELOG(LOG_WARNING, "VAO: [ID %i] Trying to re-load an already loaded mesh", mesh->vaoId);
1270 return;
1271 }
1272
1273 mesh->vboId = (unsigned int *)RL_CALLOC(MAX_MESH_VERTEX_BUFFERS, sizeof(unsigned int));
1274
1275 mesh->vaoId = 0; // Vertex Array Object
1276 mesh->vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION] = 0; // Vertex buffer: positions
1277 mesh->vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD] = 0; // Vertex buffer: texcoords
1278 mesh->vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL] = 0; // Vertex buffer: normals
1279 mesh->vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR] = 0; // Vertex buffer: colors
1280 mesh->vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT] = 0; // Vertex buffer: tangents
1281 mesh->vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2] = 0; // Vertex buffer: texcoords2
1282 mesh->vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_INDICES] = 0; // Vertex buffer: indices
1283 #if SUPPORT_GPU_SKINNING
1284 mesh->vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEINDICES] = 0; // Vertex buffer: boneIndices
1285 mesh->vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEWEIGHTS] = 0; // Vertex buffer: boneWeights
1286 #endif
1287
1288 #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)
1289 mesh->vaoId = rlLoadVertexArray();
1290
1291 rlEnableVertexArray(mesh->vaoId);
1292
1293 // NOTE: Vertex attributes must be uploaded considering default locations points and available vertex data
1294
1295 // Enable vertex attributes: position (shader-location = 0)
1296 void *vertices = (mesh->animVertices != NULL)? mesh->animVertices : mesh->vertices;
1297 mesh->vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION] = rlLoadVertexBuffer(vertices, mesh->vertexCount*3*sizeof(float), dynamic);
1298 rlSetVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION, 3, RL_FLOAT, 0, 0, 0);
1299 rlEnableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION);
1300
1301 // Enable vertex attributes: texcoords (shader-location = 1)
1302
1303 if (mesh->texcoords != NULL)
1304 {
1305 mesh->vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD] = rlLoadVertexBuffer(mesh->texcoords, mesh->vertexCount*2*sizeof(float), dynamic);
1306 rlSetVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD, 2, RL_FLOAT, 0, 0, 0);
1307 rlEnableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD);
1308 }
1309 else
1310 {
1311 float value[2] = { 0.0f, 0.0f };
1312 rlSetVertexAttributeDefault(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD, value, SHADER_ATTRIB_VEC2, 2);
1313 rlDisableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD);
1314 }
1315 // WARNING: When setting default vertex attribute values, the values for each generic vertex attribute
1316 // is part of current state, and it is maintained even if a different program object is used
1317
1318 if (mesh->normals != NULL)
1319 {
1320 // Enable vertex attributes: normals (shader-location = 2)
1321 void *normals = (mesh->animNormals != NULL)? mesh->animNormals : mesh->normals;
1322 mesh->vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL] = rlLoadVertexBuffer(normals, mesh->vertexCount*3*sizeof(float), dynamic);
1323 rlSetVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL, 3, RL_FLOAT, 0, 0, 0);
1324 rlEnableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL);
1325 }
1326 else
1327 {
1328 // Default vertex attribute: normal
1329 // WARNING: Default value provided to shader if location available
1330 float value[3] = { 0.0f, 0.0f, 1.0f };
1331 rlSetVertexAttributeDefault(RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL, value, SHADER_ATTRIB_VEC3, 3);
1332 rlDisableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL);
1333 }
1334
1335 if (mesh->colors != NULL)
1336 {
1337 // Enable vertex attribute: color (shader-location = 3)
1338 mesh->vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR] = rlLoadVertexBuffer(mesh->colors, mesh->vertexCount*4*sizeof(unsigned char), dynamic);
1339 rlSetVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR, 4, RL_UNSIGNED_BYTE, 1, 0, 0);
1340 rlEnableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR);
1341 }
1342 else
1343 {
1344 // Default vertex attribute: color
1345 // WARNING: Default value provided to shader if location available
1346 float value[4] = { 1.0f, 1.0f, 1.0f, 1.0f }; // WHITE
1347 rlSetVertexAttributeDefault(RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR, value, SHADER_ATTRIB_VEC4, 4);
1348 rlDisableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR);
1349 }
1350
1351 if (mesh->tangents != NULL)
1352 {
1353 // Enable vertex attribute: tangent (shader-location = 4)
1354 mesh->vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT] = rlLoadVertexBuffer(mesh->tangents, mesh->vertexCount*4*sizeof(float), dynamic);
1355 rlSetVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT, 4, RL_FLOAT, 0, 0, 0);
1356 rlEnableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT);
1357 }
1358 else
1359 {
1360 // Default vertex attribute: tangent
1361 // WARNING: Default value provided to shader if location available
1362 float value[4] = { 1.0f, 0.0f, 0.0f, 1.0f };
1363 rlSetVertexAttributeDefault(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT, value, SHADER_ATTRIB_VEC4, 4);
1364 rlDisableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT);
1365 }
1366
1367 if (mesh->texcoords2 != NULL)
1368 {
1369 // Enable vertex attribute: texcoord2 (shader-location = 5)
1370 mesh->vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2] = rlLoadVertexBuffer(mesh->texcoords2, mesh->vertexCount*2*sizeof(float), dynamic);
1371 rlSetVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2, 2, RL_FLOAT, 0, 0, 0);
1372 rlEnableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2);
1373 }
1374 else
1375 {
1376 // Default vertex attribute: texcoord2
1377 // WARNING: Default value provided to shader if location available
1378 float value[2] = { 0.0f, 0.0f };
1379 rlSetVertexAttributeDefault(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2, value, SHADER_ATTRIB_VEC2, 2);
1380 rlDisableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2);
1381 }
1382
1383 #if SUPPORT_GPU_SKINNING
1384 if (mesh->boneIndices != NULL)
1385 {
1386 // Enable vertex attribute: boneIndices (shader-location = 7)
1387 mesh->vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEINDICES] = rlLoadVertexBuffer(mesh->boneIndices, mesh->vertexCount*4*sizeof(unsigned char), dynamic);
1388 rlSetVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEINDICES, 4, RL_UNSIGNED_BYTE, 0, 0, 0);
1389 rlEnableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEINDICES);
1390 }
1391 else
1392 {
1393 // Default vertex attribute: boneIndices
1394 // WARNING: Default value provided to shader if location available
1395 float value[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
1396 rlSetVertexAttributeDefault(RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEINDICES, value, SHADER_ATTRIB_VEC4, 4);
1397 rlDisableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEINDICES);
1398 }
1399
1400 if (mesh->boneWeights != NULL)
1401 {
1402 // Enable vertex attribute: boneWeights (shader-location = 8)
1403 mesh->vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEWEIGHTS] = rlLoadVertexBuffer(mesh->boneWeights, mesh->vertexCount*4*sizeof(float), dynamic);
1404 rlSetVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEWEIGHTS, 4, RL_FLOAT, 0, 0, 0);
1405 rlEnableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEWEIGHTS);
1406 }
1407 else
1408 {
1409 // Default vertex attribute: boneWeights
1410 // WARNING: Default value provided to shader if location available
1411 float value[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
1412 rlSetVertexAttributeDefault(RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEWEIGHTS, value, SHADER_ATTRIB_VEC4, 2);
1413 rlDisableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEWEIGHTS);
1414 }
1415 #endif
1416
1417 if (mesh->indices != NULL)
1418 {
1419 mesh->vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_INDICES] = rlLoadVertexBufferElement(mesh->indices, mesh->triangleCount*3*sizeof(unsigned short), dynamic);
1420 }
1421
1422 if (mesh->vaoId > 0) TRACELOG(LOG_INFO, "VAO: [ID %i] Mesh uploaded successfully to VRAM (GPU)", mesh->vaoId);
1423 else TRACELOG(LOG_INFO, "VBO: Mesh uploaded successfully to VRAM (GPU)");
1424
1425 rlDisableVertexArray();
1426 #endif
1427 }
1428
1429 // Update mesh vertex data in GPU for a specific buffer index
1430 void UpdateMeshBuffer(Mesh mesh, int index, const void *data, int dataSize, int offset)
1431 {
1432 rlUpdateVertexBuffer(mesh.vboId[index], data, dataSize, offset);
1433 }
1434
1435 // Draw a 3d mesh with material and transform
1436 void DrawMesh(Mesh mesh, Material material, Matrix transform)
1437 {
1438 #if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_SOFTWARE)
1439 #define GL_VERTEX_ARRAY 0x8074
1440 #define GL_NORMAL_ARRAY 0x8075
1441 #define GL_COLOR_ARRAY 0x8076
1442 #define GL_TEXTURE_COORD_ARRAY 0x8078
1443
1444 if ((mesh.texcoords != NULL) && (material.maps[MATERIAL_MAP_DIFFUSE].texture.id > 0)) rlEnableTexture(material.maps[MATERIAL_MAP_DIFFUSE].texture.id);
1445
1446 if (mesh.animVertices != NULL) rlEnableStatePointer(GL_VERTEX_ARRAY, mesh.animVertices);
1447 else rlEnableStatePointer(GL_VERTEX_ARRAY, mesh.vertices);
1448
1449 if (mesh.texcoords) rlEnableStatePointer(GL_TEXTURE_COORD_ARRAY, mesh.texcoords);
1450
1451 if (mesh.animNormals != NULL) rlEnableStatePointer(GL_NORMAL_ARRAY, mesh.animNormals);
1452 else if (mesh.normals != NULL) rlEnableStatePointer(GL_NORMAL_ARRAY, mesh.normals);
1453
1454 if (mesh.colors != NULL) rlEnableStatePointer(GL_COLOR_ARRAY, mesh.colors);
1455
1456 rlPushMatrix();
1457 rlMultMatrixf(MatrixToFloat(transform));
1458 rlColor4ub(material.maps[MATERIAL_MAP_DIFFUSE].color.r,
1459 material.maps[MATERIAL_MAP_DIFFUSE].color.g,
1460 material.maps[MATERIAL_MAP_DIFFUSE].color.b,
1461 material.maps[MATERIAL_MAP_DIFFUSE].color.a);
1462
1463 if (mesh.indices != NULL) rlDrawVertexArrayElements(0, mesh.triangleCount*3, mesh.indices);
1464 else rlDrawVertexArray(0, mesh.vertexCount);
1465 rlPopMatrix();
1466
1467 rlDisableStatePointer(GL_VERTEX_ARRAY);
1468 rlDisableStatePointer(GL_TEXTURE_COORD_ARRAY);
1469 rlDisableStatePointer(GL_NORMAL_ARRAY);
1470 rlDisableStatePointer(GL_COLOR_ARRAY);
1471
1472 rlDisableTexture();
1473 #endif
1474
1475 #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)
1476 // Bind shader program
1477 rlEnableShader(material.shader.id);
1478
1479 if (material.shader.locs == NULL) return;
1480
1481 // Send required data to shader (matrices, values)
1482 //-----------------------------------------------------
1483 // Upload to shader material.colDiffuse
1484 if (material.shader.locs[SHADER_LOC_COLOR_DIFFUSE] != -1)
1485 {
1486 float values[4] = {
1487 (float)material.maps[MATERIAL_MAP_DIFFUSE].color.r/255.0f,
1488 (float)material.maps[MATERIAL_MAP_DIFFUSE].color.g/255.0f,
1489 (float)material.maps[MATERIAL_MAP_DIFFUSE].color.b/255.0f,
1490 (float)material.maps[MATERIAL_MAP_DIFFUSE].color.a/255.0f
1491 };
1492
1493 rlSetUniform(material.shader.locs[SHADER_LOC_COLOR_DIFFUSE], values, SHADER_UNIFORM_VEC4, 1);
1494 }
1495
1496 // Upload to shader material.colSpecular (if location available)
1497 if (material.shader.locs[SHADER_LOC_COLOR_SPECULAR] != -1)
1498 {
1499 float values[4] = {
1500 (float)material.maps[MATERIAL_MAP_SPECULAR].color.r/255.0f,
1501 (float)material.maps[MATERIAL_MAP_SPECULAR].color.g/255.0f,
1502 (float)material.maps[MATERIAL_MAP_SPECULAR].color.b/255.0f,
1503 (float)material.maps[MATERIAL_MAP_SPECULAR].color.a/255.0f
1504 };
1505
1506 rlSetUniform(material.shader.locs[SHADER_LOC_COLOR_SPECULAR], values, SHADER_UNIFORM_VEC4, 1);
1507 }
1508
1509 // Get a copy of current matrices to work with,
1510 // in case stereo render is required, and they need to be modified
1511 // NOTE: At this point the modelview matrix contains the view matrix (camera)
1512 // That's because BeginMode3D() sets it and there is no model-drawing function
1513 // that modifies it, all use rlPushMatrix() and rlPopMatrix()
1514 Matrix matModel = MatrixIdentity();
1515 Matrix matView = rlGetMatrixModelview();
1516 Matrix matModelView = MatrixIdentity();
1517 Matrix matProjection = rlGetMatrixProjection();
1518
1519 // Upload view and projection matrices (if locations available)
1520 if (material.shader.locs[SHADER_LOC_MATRIX_VIEW] != -1) rlSetUniformMatrix(material.shader.locs[SHADER_LOC_MATRIX_VIEW], matView);
1521 if (material.shader.locs[SHADER_LOC_MATRIX_PROJECTION] != -1) rlSetUniformMatrix(material.shader.locs[SHADER_LOC_MATRIX_PROJECTION], matProjection);
1522
1523 // Accumulate several model transformations:
1524 // transform: model transformation provided (includes DrawModel() params combined with model.transform)
1525 // rlGetMatrixTransform(): rlgl internal transform matrix due to push/pop matrix stack
1526 matModel = MatrixMultiply(transform, rlGetMatrixTransform());
1527
1528 // Model transformation matrix is sent to shader uniform location: SHADER_LOC_MATRIX_MODEL
1529 if (material.shader.locs[SHADER_LOC_MATRIX_MODEL] != -1) rlSetUniformMatrix(material.shader.locs[SHADER_LOC_MATRIX_MODEL], matModel);
1530
1531 // Get model-view matrix
1532 matModelView = MatrixMultiply(matModel, matView);
1533
1534 // Upload model normal matrix (if locations available)
1535 if (material.shader.locs[SHADER_LOC_MATRIX_NORMAL] != -1) rlSetUniformMatrix(material.shader.locs[SHADER_LOC_MATRIX_NORMAL], MatrixTranspose(MatrixInvert(matModel)));
1536 //-----------------------------------------------------
1537
1538 // Bind active texture maps (if available)
1539 for (int i = 0; i < MAX_MATERIAL_MAPS; i++)
1540 {
1541 if (material.maps[i].texture.id > 0)
1542 {
1543 // Select current shader texture slot
1544 rlActiveTextureSlot(i);
1545
1546 // Enable texture for active slot
1547 if ((i == MATERIAL_MAP_IRRADIANCE) ||
1548 (i == MATERIAL_MAP_PREFILTER) ||
1549 (i == MATERIAL_MAP_CUBEMAP)) rlEnableTextureCubemap(material.maps[i].texture.id);
1550 else rlEnableTexture(material.maps[i].texture.id);
1551
1552 rlSetUniform(material.shader.locs[SHADER_LOC_MAP_DIFFUSE + i], &i, SHADER_UNIFORM_INT, 1);
1553 }
1554 }
1555
1556 // Try binding vertex array objects (VAO) or use VBOs if not possible
1557 // WARNING: UploadMesh() enables all vertex attributes available in mesh and sets default attribute values
1558 // for shader expected vertex attributes that are not provided by the mesh (i.e. colors)
1559 // This could be a dangerous approach because different meshes with different shaders can enable/disable some attributes
1560 if (!rlEnableVertexArray(mesh.vaoId))
1561 {
1562 // Bind mesh VBO data: vertex position (shader-location = 0)
1563 rlEnableVertexBuffer(mesh.vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION]);
1564 rlSetVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_POSITION], 3, RL_FLOAT, 0, 0, 0);
1565 rlEnableVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_POSITION]);
1566
1567 // Bind mesh VBO data: vertex texcoords (shader-location = 1)
1568 rlEnableVertexBuffer(mesh.vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD]);
1569 rlSetVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_TEXCOORD01], 2, RL_FLOAT, 0, 0, 0);
1570 rlEnableVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_TEXCOORD01]);
1571
1572 if (material.shader.locs[SHADER_LOC_VERTEX_NORMAL] != -1)
1573 {
1574 // Bind mesh VBO data: vertex normals (shader-location = 2)
1575 rlEnableVertexBuffer(mesh.vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL]);
1576 rlSetVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_NORMAL], 3, RL_FLOAT, 0, 0, 0);
1577 rlEnableVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_NORMAL]);
1578 }
1579
1580 // Bind mesh VBO data: vertex colors (shader-location = 3, if available)
1581 if (material.shader.locs[SHADER_LOC_VERTEX_COLOR] != -1)
1582 {
1583 if (mesh.vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR] != 0)
1584 {
1585 rlEnableVertexBuffer(mesh.vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR]);
1586 rlSetVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_COLOR], 4, RL_UNSIGNED_BYTE, 1, 0, 0);
1587 rlEnableVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_COLOR]);
1588 }
1589 else
1590 {
1591 // Set default value for defined vertex attribute in shader but not provided by mesh
1592 // WARNING: It could result in GPU undefined behaviour
1593 float value[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
1594 rlSetVertexAttributeDefault(material.shader.locs[SHADER_LOC_VERTEX_COLOR], value, SHADER_ATTRIB_VEC4, 4);
1595 rlDisableVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_COLOR]);
1596 }
1597 }
1598
1599 // Bind mesh VBO data: vertex tangents (shader-location = 4, if available)
1600 if (material.shader.locs[SHADER_LOC_VERTEX_TANGENT] != -1)
1601 {
1602 rlEnableVertexBuffer(mesh.vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT]);
1603 rlSetVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_TANGENT], 4, RL_FLOAT, 0, 0, 0);
1604 rlEnableVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_TANGENT]);
1605 }
1606
1607 // Bind mesh VBO data: vertex texcoords2 (shader-location = 5, if available)
1608 if (material.shader.locs[SHADER_LOC_VERTEX_TEXCOORD02] != -1)
1609 {
1610 rlEnableVertexBuffer(mesh.vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2]);
1611 rlSetVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_TEXCOORD02], 2, RL_FLOAT, 0, 0, 0);
1612 rlEnableVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_TEXCOORD02]);
1613 }
1614
1615 #if SUPPORT_GPU_SKINNING
1616 // Bind mesh VBO data: vertex bone ids (shader-location = 6, if available)
1617 if (material.shader.locs[SHADER_LOC_VERTEX_BONEIDS] != -1)
1618 {
1619 rlEnableVertexBuffer(mesh.vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEINDICES]);
1620 rlSetVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_BONEIDS], 4, RL_UNSIGNED_BYTE, 0, 0, 0);
1621 rlEnableVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_BONEIDS]);
1622 }
1623
1624 // Bind mesh VBO data: vertex bone weights (shader-location = 7, if available)
1625 if (material.shader.locs[SHADER_LOC_VERTEX_BONEWEIGHTS] != -1)
1626 {
1627 rlEnableVertexBuffer(mesh.vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEWEIGHTS]);
1628 rlSetVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_BONEWEIGHTS], 4, RL_FLOAT, 0, 0, 0);
1629 rlEnableVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_BONEWEIGHTS]);
1630 }
1631 #endif
1632
1633 if (mesh.indices != NULL) rlEnableVertexBufferElement(mesh.vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_INDICES]);
1634 }
1635
1636 int eyeCount = 1;
1637 if (rlIsStereoRenderEnabled()) eyeCount = 2;
1638
1639 for (int eye = 0; eye < eyeCount; eye++)
1640 {
1641 // Calculate model-view-projection matrix (MVP)
1642 Matrix matModelViewProjection = MatrixIdentity();
1643 if (eyeCount == 1) matModelViewProjection = MatrixMultiply(matModelView, matProjection);
1644 else
1645 {
1646 // Setup current eye viewport (half screen width)
1647 rlViewport(eye*rlGetFramebufferWidth()/2, 0, rlGetFramebufferWidth()/2, rlGetFramebufferHeight());
1648 matModelViewProjection = MatrixMultiply(MatrixMultiply(matModelView, rlGetMatrixViewOffsetStereo(eye)), rlGetMatrixProjectionStereo(eye));
1649 }
1650
1651 // Send combined model-view-projection matrix to shader
1652 rlSetUniformMatrix(material.shader.locs[SHADER_LOC_MATRIX_MVP], matModelViewProjection);
1653
1654 // Draw mesh
1655 if (mesh.indices != NULL) rlDrawVertexArrayElements(0, mesh.triangleCount*3, 0);
1656 else rlDrawVertexArray(0, mesh.vertexCount);
1657 }
1658
1659 // Unbind all bound texture maps
1660 for (int i = 0; i < MAX_MATERIAL_MAPS; i++)
1661 {
1662 if (material.maps[i].texture.id > 0)
1663 {
1664 // Select current shader texture slot
1665 rlActiveTextureSlot(i);
1666
1667 // Disable texture for active slot
1668 if ((i == MATERIAL_MAP_IRRADIANCE) ||
1669 (i == MATERIAL_MAP_PREFILTER) ||
1670 (i == MATERIAL_MAP_CUBEMAP)) rlDisableTextureCubemap();
1671 else rlDisableTexture();
1672 }
1673 }
1674
1675 // Disable all possible vertex array objects (or VBOs)
1676 rlDisableVertexArray();
1677 rlDisableVertexBuffer();
1678 rlDisableVertexBufferElement();
1679
1680 // Disable shader program
1681 rlDisableShader();
1682
1683 // Restore rlgl internal modelview and projection matrices
1684 rlSetMatrixModelview(matView);
1685 rlSetMatrixProjection(matProjection);
1686 #endif
1687 }
1688
1689 // Draw multiple mesh instances with material and different transforms
1690 void DrawMeshInstanced(Mesh mesh, Material material, const Matrix *transforms, int instances)
1691 {
1692 #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)
1693 // Instancing required variables
1694 float16 *instanceTransform = NULL;
1695 unsigned int instancesVboId = 0;
1696
1697 // Bind shader program
1698 rlEnableShader(material.shader.id);
1699
1700 // Send required data to shader (matrices, values)
1701 //-----------------------------------------------------
1702 // Upload to shader material.colDiffuse
1703 if (material.shader.locs[SHADER_LOC_COLOR_DIFFUSE] != -1)
1704 {
1705 float values[4] = {
1706 (float)material.maps[MATERIAL_MAP_DIFFUSE].color.r/255.0f,
1707 (float)material.maps[MATERIAL_MAP_DIFFUSE].color.g/255.0f,
1708 (float)material.maps[MATERIAL_MAP_DIFFUSE].color.b/255.0f,
1709 (float)material.maps[MATERIAL_MAP_DIFFUSE].color.a/255.0f
1710 };
1711
1712 rlSetUniform(material.shader.locs[SHADER_LOC_COLOR_DIFFUSE], values, SHADER_UNIFORM_VEC4, 1);
1713 }
1714
1715 // Upload to shader material.colSpecular (if location available)
1716 if (material.shader.locs[SHADER_LOC_COLOR_SPECULAR] != -1)
1717 {
1718 float values[4] = {
1719 (float)material.maps[MATERIAL_MAP_SPECULAR].color.r/255.0f,
1720 (float)material.maps[MATERIAL_MAP_SPECULAR].color.g/255.0f,
1721 (float)material.maps[MATERIAL_MAP_SPECULAR].color.b/255.0f,
1722 (float)material.maps[MATERIAL_MAP_SPECULAR].color.a/255.0f
1723 };
1724
1725 rlSetUniform(material.shader.locs[SHADER_LOC_COLOR_SPECULAR], values, SHADER_UNIFORM_VEC4, 1);
1726 }
1727
1728 // Get a copy of current matrices to work with,
1729 // in case stereo render is required, and they need to be modified
1730 // NOTE: At this point the modelview matrix contains the view matrix (camera)
1731 // That's because BeginMode3D() sets it and there is no model-drawing function
1732 // that modifies it, all use rlPushMatrix() and rlPopMatrix()
1733 Matrix matModel = MatrixIdentity();
1734 Matrix matView = rlGetMatrixModelview();
1735 Matrix matModelView = MatrixIdentity();
1736 Matrix matProjection = rlGetMatrixProjection();
1737
1738 // Upload view and projection matrices (if locations available)
1739 if (material.shader.locs[SHADER_LOC_MATRIX_VIEW] != -1) rlSetUniformMatrix(material.shader.locs[SHADER_LOC_MATRIX_VIEW], matView);
1740 if (material.shader.locs[SHADER_LOC_MATRIX_PROJECTION] != -1) rlSetUniformMatrix(material.shader.locs[SHADER_LOC_MATRIX_PROJECTION], matProjection);
1741
1742 // Create instances buffer
1743 instanceTransform = (float16 *)RL_CALLOC(instances, sizeof(float16));
1744
1745 // Fill buffer with instances transformations as float16 arrays
1746 for (int i = 0; i < instances; i++) instanceTransform[i] = MatrixToFloatV(transforms[i]);
1747
1748 // Enable mesh VAO to attach new buffer
1749 rlEnableVertexArray(mesh.vaoId);
1750
1751 // This could alternatively use a static VBO and either glMapBuffer() or glBufferSubData()
1752 // It isn't clear which would be reliably faster in all cases and on all platforms,
1753 // anecdotally glMapBuffer() seems quite slow (syncs) while glBufferSubData() seems
1754 // no faster, since all the transform matrices are transferred anyway
1755 instancesVboId = rlLoadVertexBuffer(instanceTransform, instances*sizeof(float16), false);
1756
1757 // Instances transformation matrices are sent to shader attribute location: SHADER_LOC_VERTEX_INSTANCETRANSFORM
1758 if (material.shader.locs[SHADER_LOC_VERTEX_INSTANCETRANSFORM] != -1)
1759 {
1760 for (unsigned int i = 0; i < 4; i++)
1761 {
1762 rlEnableVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_INSTANCETRANSFORM] + i);
1763 rlSetVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_INSTANCETRANSFORM] + i, 4, RL_FLOAT, 0, sizeof(Matrix), i*sizeof(Vector4));
1764 rlSetVertexAttributeDivisor(material.shader.locs[SHADER_LOC_VERTEX_INSTANCETRANSFORM] + i, 1);
1765 }
1766 }
1767
1768 rlDisableVertexBuffer();
1769 rlDisableVertexArray();
1770
1771 // Accumulate internal matrix transform (push/pop) and view matrix
1772 // NOTE: In this case, model instance transformation must be computed in the shader
1773 matModelView = MatrixMultiply(rlGetMatrixTransform(), matView);
1774
1775 // Upload model normal matrix (if locations available)
1776 if (material.shader.locs[SHADER_LOC_MATRIX_NORMAL] != -1) rlSetUniformMatrix(material.shader.locs[SHADER_LOC_MATRIX_NORMAL], MatrixTranspose(MatrixInvert(matModel)));
1777 //-----------------------------------------------------
1778
1779 // Bind active texture maps (if available)
1780 for (int i = 0; i < MAX_MATERIAL_MAPS; i++)
1781 {
1782 if (material.maps[i].texture.id > 0)
1783 {
1784 // Select current shader texture slot
1785 rlActiveTextureSlot(i);
1786
1787 // Enable texture for active slot
1788 if ((i == MATERIAL_MAP_IRRADIANCE) ||
1789 (i == MATERIAL_MAP_PREFILTER) ||
1790 (i == MATERIAL_MAP_CUBEMAP)) rlEnableTextureCubemap(material.maps[i].texture.id);
1791 else rlEnableTexture(material.maps[i].texture.id);
1792
1793 rlSetUniform(material.shader.locs[SHADER_LOC_MAP_DIFFUSE + i], &i, SHADER_UNIFORM_INT, 1);
1794 }
1795 }
1796
1797 // Try binding vertex array objects (VAO)
1798 // or use VBOs if not possible
1799 if (!rlEnableVertexArray(mesh.vaoId))
1800 {
1801 // Bind mesh VBO data: vertex position (shader-location = 0)
1802 rlEnableVertexBuffer(mesh.vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION]);
1803 rlSetVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_POSITION], 3, RL_FLOAT, 0, 0, 0);
1804 rlEnableVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_POSITION]);
1805
1806 // Bind mesh VBO data: vertex texcoords (shader-location = 1)
1807 rlEnableVertexBuffer(mesh.vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD]);
1808 rlSetVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_TEXCOORD01], 2, RL_FLOAT, 0, 0, 0);
1809 rlEnableVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_TEXCOORD01]);
1810
1811 if (material.shader.locs[SHADER_LOC_VERTEX_NORMAL] != -1)
1812 {
1813 // Bind mesh VBO data: vertex normals (shader-location = 2)
1814 rlEnableVertexBuffer(mesh.vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL]);
1815 rlSetVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_NORMAL], 3, RL_FLOAT, 0, 0, 0);
1816 rlEnableVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_NORMAL]);
1817 }
1818
1819 // Bind mesh VBO data: vertex colors (shader-location = 3, if available)
1820 if (material.shader.locs[SHADER_LOC_VERTEX_COLOR] != -1)
1821 {
1822 if (mesh.vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR] != 0)
1823 {
1824 rlEnableVertexBuffer(mesh.vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR]);
1825 rlSetVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_COLOR], 4, RL_UNSIGNED_BYTE, 1, 0, 0);
1826 rlEnableVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_COLOR]);
1827 }
1828 else
1829 {
1830 // Set default value for unused attribute
1831 // NOTE: Required when using default shader and no VAO support
1832 float value[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
1833 rlSetVertexAttributeDefault(material.shader.locs[SHADER_LOC_VERTEX_COLOR], value, SHADER_ATTRIB_VEC4, 4);
1834 rlDisableVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_COLOR]);
1835 }
1836 }
1837
1838 // Bind mesh VBO data: vertex tangents (shader-location = 4, if available)
1839 if (material.shader.locs[SHADER_LOC_VERTEX_TANGENT] != -1)
1840 {
1841 rlEnableVertexBuffer(mesh.vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT]);
1842 rlSetVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_TANGENT], 4, RL_FLOAT, 0, 0, 0);
1843 rlEnableVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_TANGENT]);
1844 }
1845
1846 // Bind mesh VBO data: vertex texcoords2 (shader-location = 5, if available)
1847 if (material.shader.locs[SHADER_LOC_VERTEX_TEXCOORD02] != -1)
1848 {
1849 rlEnableVertexBuffer(mesh.vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2]);
1850 rlSetVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_TEXCOORD02], 2, RL_FLOAT, 0, 0, 0);
1851 rlEnableVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_TEXCOORD02]);
1852 }
1853
1854 #if SUPPORT_GPU_SKINNING
1855 // Bind mesh VBO data: vertex bone ids (shader-location = 6, if available)
1856 if (material.shader.locs[SHADER_LOC_VERTEX_BONEIDS] != -1)
1857 {
1858 rlEnableVertexBuffer(mesh.vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEINDICES]);
1859 rlSetVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_BONEIDS], 4, RL_UNSIGNED_BYTE, 0, 0, 0);
1860 rlEnableVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_BONEIDS]);
1861 }
1862
1863 // Bind mesh VBO data: vertex bone weights (shader-location = 7, if available)
1864 if (material.shader.locs[SHADER_LOC_VERTEX_BONEWEIGHTS] != -1)
1865 {
1866 rlEnableVertexBuffer(mesh.vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEWEIGHTS]);
1867 rlSetVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_BONEWEIGHTS], 4, RL_FLOAT, 0, 0, 0);
1868 rlEnableVertexAttribute(material.shader.locs[SHADER_LOC_VERTEX_BONEWEIGHTS]);
1869 }
1870 #endif
1871
1872 if (mesh.indices != NULL) rlEnableVertexBufferElement(mesh.vboId[RL_DEFAULT_SHADER_ATTRIB_LOCATION_INDICES]);
1873 }
1874
1875 int eyeCount = 1;
1876 if (rlIsStereoRenderEnabled()) eyeCount = 2;
1877
1878 for (int eye = 0; eye < eyeCount; eye++)
1879 {
1880 // Calculate model-view-projection matrix (MVP)
1881 Matrix matModelViewProjection = MatrixIdentity();
1882 if (eyeCount == 1) matModelViewProjection = MatrixMultiply(matModelView, matProjection);
1883 else
1884 {
1885 // Setup current eye viewport (half screen width)
1886 rlViewport(eye*rlGetFramebufferWidth()/2, 0, rlGetFramebufferWidth()/2, rlGetFramebufferHeight());
1887 matModelViewProjection = MatrixMultiply(MatrixMultiply(matModelView, rlGetMatrixViewOffsetStereo(eye)), rlGetMatrixProjectionStereo(eye));
1888 }
1889
1890 // Send combined model-view-projection matrix to shader
1891 rlSetUniformMatrix(material.shader.locs[SHADER_LOC_MATRIX_MVP], matModelViewProjection);
1892
1893 // Draw mesh instanced
1894 if (mesh.indices != NULL) rlDrawVertexArrayElementsInstanced(0, mesh.triangleCount*3, 0, instances);
1895 else rlDrawVertexArrayInstanced(0, mesh.vertexCount, instances);
1896 }
1897
1898 // Unbind all bound texture maps
1899 for (int i = 0; i < MAX_MATERIAL_MAPS; i++)
1900 {
1901 if (material.maps[i].texture.id > 0)
1902 {
1903 // Select current shader texture slot
1904 rlActiveTextureSlot(i);
1905
1906 // Disable texture for active slot
1907 if ((i == MATERIAL_MAP_IRRADIANCE) ||
1908 (i == MATERIAL_MAP_PREFILTER) ||
1909 (i == MATERIAL_MAP_CUBEMAP)) rlDisableTextureCubemap();
1910 else rlDisableTexture();
1911 }
1912 }
1913
1914 // Disable all possible vertex array objects (or VBOs)
1915 rlDisableVertexArray();
1916 rlDisableVertexBuffer();
1917 rlDisableVertexBufferElement();
1918
1919 // Disable shader program
1920 rlDisableShader();
1921
1922 // Remove instance transforms buffer
1923 rlUnloadVertexBuffer(instancesVboId);
1924 RL_FREE(instanceTransform);
1925 #endif
1926 }
1927
1928 // Unload mesh from memory (RAM and VRAM)
1929 void UnloadMesh(Mesh mesh)
1930 {
1931 // Unload rlgl mesh vboId data
1932 rlUnloadVertexArray(mesh.vaoId);
1933
1934 if (mesh.vboId != NULL) for (int i = 0; i < MAX_MESH_VERTEX_BUFFERS; i++) rlUnloadVertexBuffer(mesh.vboId[i]);
1935 RL_FREE(mesh.vboId);
1936
1937 // Unload mesh vertex buffers
1938 RL_FREE(mesh.vertices);
1939 RL_FREE(mesh.texcoords);
1940 RL_FREE(mesh.normals);
1941 RL_FREE(mesh.colors);
1942 RL_FREE(mesh.tangents);
1943 RL_FREE(mesh.texcoords2);
1944 RL_FREE(mesh.indices);
1945
1946 // Unload mesh skin animation data
1947 RL_FREE(mesh.boneWeights);
1948 RL_FREE(mesh.boneIndices);
1949
1950 // Unload mesh runtime CPU skinning data
1951 RL_FREE(mesh.animVertices);
1952 RL_FREE(mesh.animNormals);
1953 }
1954
1955 // Export mesh data to file
1956 bool ExportMesh(Mesh mesh, const char *fileName)
1957 {
1958 bool result = false;
1959
1960 if (IsFileExtension(fileName, ".obj"))
1961 {
1962 // Estimated data size, it should be enough...
1963 int vc = mesh.vertexCount;
1964 int dataSize = vc*(int)strlen("v -0000.000000f -0000.000000f -0000.000000f\n") +
1965 vc*(int)strlen("vt -0.000000f -0.000000f\n") +
1966 vc*(int)strlen("vn -0.0000f -0.0000f -0.0000f\n") +
1967 mesh.triangleCount*snprintf(NULL, 0, "f %i/%i/%i %i/%i/%i %i/%i/%i\n", vc, vc, vc, vc, vc, vc, vc, vc, vc);
1968
1969 // NOTE: Text data buffer size is estimated considering mesh data size
1970 char *txtData = (char *)RL_CALLOC(dataSize + 1000, sizeof(char));
1971
1972 int byteCount = 0;
1973 byteCount += sprintf(txtData + byteCount, "# //////////////////////////////////////////////////////////////////////////////////\n");
1974 byteCount += sprintf(txtData + byteCount, "# // //\n");
1975 byteCount += sprintf(txtData + byteCount, "# // rMeshOBJ exporter v1.0 - Mesh exported as triangle faces and not optimized //\n");
1976 byteCount += sprintf(txtData + byteCount, "# // //\n");
1977 byteCount += sprintf(txtData + byteCount, "# // more info and bugs-report: github.com/raysan5/raylib //\n");
1978 byteCount += sprintf(txtData + byteCount, "# // feedback and support: ray[at]raylib.com //\n");
1979 byteCount += sprintf(txtData + byteCount, "# // //\n");
1980 byteCount += sprintf(txtData + byteCount, "# // Copyright (c) 2018-2026 Ramon Santamaria (@raysan5) //\n");
1981 byteCount += sprintf(txtData + byteCount, "# // //\n");
1982 byteCount += sprintf(txtData + byteCount, "# //////////////////////////////////////////////////////////////////////////////////\n\n");
1983 byteCount += sprintf(txtData + byteCount, "# Vertex Count: %i\n", mesh.vertexCount);
1984 byteCount += sprintf(txtData + byteCount, "# Triangle Count: %i\n\n", mesh.triangleCount);
1985
1986 byteCount += sprintf(txtData + byteCount, "g mesh\n");
1987
1988 for (int i = 0, v = 0; i < mesh.vertexCount; i++, v += 3)
1989 {
1990 byteCount += sprintf(txtData + byteCount, "v %.6f %.6f %.6f\n", mesh.vertices[v], mesh.vertices[v + 1], mesh.vertices[v + 2]);
1991 }
1992
1993 for (int i = 0, v = 0; i < mesh.vertexCount; i++, v += 2)
1994 {
1995 byteCount += sprintf(txtData + byteCount, "vt %.6f %.6f\n", mesh.texcoords[v], mesh.texcoords[v + 1]);
1996 }
1997
1998 for (int i = 0, v = 0; i < mesh.vertexCount; i++, v += 3)
1999 {
2000 byteCount += sprintf(txtData + byteCount, "vn %.4f %.4f %.4f\n", mesh.normals[v], mesh.normals[v + 1], mesh.normals[v + 2]);
2001 }
2002
2003 if (mesh.indices != NULL)
2004 {
2005 for (int i = 0, v = 0; i < mesh.triangleCount; i++, v += 3)
2006 {
2007 byteCount += sprintf(txtData + byteCount, "f %i/%i/%i %i/%i/%i %i/%i/%i\n",
2008 mesh.indices[v] + 1, mesh.indices[v] + 1, mesh.indices[v] + 1,
2009 mesh.indices[v + 1] + 1, mesh.indices[v + 1] + 1, mesh.indices[v + 1] + 1,
2010 mesh.indices[v + 2] + 1, mesh.indices[v + 2] + 1, mesh.indices[v + 2] + 1);
2011 }
2012 }
2013 else
2014 {
2015 for (int i = 0, v = 1; i < mesh.triangleCount; i++, v += 3)
2016 {
2017 byteCount += sprintf(txtData + byteCount, "f %i/%i/%i %i/%i/%i %i/%i/%i\n", v, v, v, v + 1, v + 1, v + 1, v + 2, v + 2, v + 2);
2018 }
2019 }
2020
2021 // NOTE: Text data length exported is determined by '\0' (NULL) character
2022 result = SaveFileText(fileName, txtData);
2023
2024 RL_FREE(txtData);
2025 }
2026 else if (IsFileExtension(fileName, ".gltf")) // Or .glb
2027 {
2028 // TODO: Implement gltf/glb support
2029 /*
2030 cgltf_size expected = cgltf_write(options, NULL, 0, data);
2031 char *buffer = (char *)RL_CALLOC(expected, 0);
2032 cgltf_size actual = cgltf_write(options, buffer, expected, data);
2033
2034 // NOTE: cgltf_write() includes a NULL terminator that should be ommited in case of a .glb
2035 if (options->type == cgltf_file_type_glb) cgltf_write_glb(file, buffer, actual - 1, data->bin, data->bin_size);
2036 else SaveFileText(fileName, buffer); // Write a plain JSON file
2037 */
2038 }
2039 else if (IsFileExtension(fileName, ".raw"))
2040 {
2041 // TODO: Support additional file formats to export mesh vertex data
2042 }
2043
2044 return result;
2045 }
2046
2047 // Export mesh as code file (.h) defining multiple arrays of vertex attributes
2048 bool ExportMeshAsCode(Mesh mesh, const char *fileName)
2049 {
2050 bool result = false;
2051
2052 #ifndef TEXT_BYTES_PER_LINE
2053 #define TEXT_BYTES_PER_LINE 20
2054 #endif
2055
2056 // NOTE: Text data buffer size is fixed to 64MB
2057 char *txtData = (char *)RL_CALLOC(64*1024*1024, sizeof(char)); // 64 MB
2058
2059 int byteCount = 0;
2060 byteCount += sprintf(txtData + byteCount, "////////////////////////////////////////////////////////////////////////////////////////\n");
2061 byteCount += sprintf(txtData + byteCount, "// //\n");
2062 byteCount += sprintf(txtData + byteCount, "// MeshAsCode exporter v1.0 - Mesh vertex data exported as arrays //\n");
2063 byteCount += sprintf(txtData + byteCount, "// //\n");
2064 byteCount += sprintf(txtData + byteCount, "// more info and bugs-report: github.com/raysan5/raylib //\n");
2065 byteCount += sprintf(txtData + byteCount, "// feedback and support: ray[at]raylib.com //\n");
2066 byteCount += sprintf(txtData + byteCount, "// //\n");
2067 byteCount += sprintf(txtData + byteCount, "// Copyright (c) 2023 Ramon Santamaria (@raysan5) //\n");
2068 byteCount += sprintf(txtData + byteCount, "// //\n");
2069 byteCount += sprintf(txtData + byteCount, "////////////////////////////////////////////////////////////////////////////////////////\n\n");
2070
2071 // Get file name from path and convert variable name to uppercase
2072 char varFileName[256] = { 0 };
2073 strncpy(varFileName, GetFileNameWithoutExt(fileName), 256 - 1); // NOTE: Using function provided by [rcore] module
2074 for (int i = 0; varFileName[i] != '\0'; i++) if ((varFileName[i] >= 'a') && (varFileName[i] <= 'z')) { varFileName[i] = varFileName[i] - 32; }
2075
2076 // Add image information
2077 byteCount += sprintf(txtData + byteCount, "// Mesh basic information\n");
2078 byteCount += sprintf(txtData + byteCount, "#define %s_VERTEX_COUNT %i\n", varFileName, mesh.vertexCount);
2079 byteCount += sprintf(txtData + byteCount, "#define %s_TRIANGLE_COUNT %i\n\n", varFileName, mesh.triangleCount);
2080
2081 // Define vertex attributes data as separate arrays
2082 //-----------------------------------------------------------------------------------------
2083 if (mesh.vertices != NULL) // Vertex position (XYZ - 3 components per vertex - float)
2084 {
2085 byteCount += sprintf(txtData + byteCount, "static float %s_VERTEX_DATA[%i] = { ", varFileName, mesh.vertexCount*3);
2086 for (int i = 0; i < mesh.vertexCount*3 - 1; i++) byteCount += sprintf(txtData + byteCount, ((i%TEXT_BYTES_PER_LINE == 0)? "%.3ff,\n" : "%.3ff, "), mesh.vertices[i]);
2087 byteCount += sprintf(txtData + byteCount, "%.3ff };\n\n", mesh.vertices[mesh.vertexCount*3 - 1]);
2088 }
2089
2090 if (mesh.texcoords != NULL) // Vertex texture coordinates (UV - 2 components per vertex - float)
2091 {
2092 byteCount += sprintf(txtData + byteCount, "static float %s_TEXCOORD_DATA[%i] = { ", varFileName, mesh.vertexCount*2);
2093 for (int i = 0; i < mesh.vertexCount*2 - 1; i++) byteCount += sprintf(txtData + byteCount, ((i%TEXT_BYTES_PER_LINE == 0)? "%.3ff,\n" : "%.3ff, "), mesh.texcoords[i]);
2094 byteCount += sprintf(txtData + byteCount, "%.3ff };\n\n", mesh.texcoords[mesh.vertexCount*2 - 1]);
2095 }
2096
2097 if (mesh.texcoords2 != NULL) // Vertex texture coordinates (UV - 2 components per vertex - float)
2098 {
2099 byteCount += sprintf(txtData + byteCount, "static float %s_TEXCOORD2_DATA[%i] = { ", varFileName, mesh.vertexCount*2);
2100 for (int i = 0; i < mesh.vertexCount*2 - 1; i++) byteCount += sprintf(txtData + byteCount, ((i%TEXT_BYTES_PER_LINE == 0)? "%.3ff,\n" : "%.3ff, "), mesh.texcoords2[i]);
2101 byteCount += sprintf(txtData + byteCount, "%.3ff };\n\n", mesh.texcoords2[mesh.vertexCount*2 - 1]);
2102 }
2103
2104 if (mesh.normals != NULL) // Vertex normals (XYZ - 3 components per vertex - float)
2105 {
2106 byteCount += sprintf(txtData + byteCount, "static float %s_NORMAL_DATA[%i] = { ", varFileName, mesh.vertexCount*3);
2107 for (int i = 0; i < mesh.vertexCount*3 - 1; i++) byteCount += sprintf(txtData + byteCount, ((i%TEXT_BYTES_PER_LINE == 0)? "%.3ff,\n" : "%.3ff, "), mesh.normals[i]);
2108 byteCount += sprintf(txtData + byteCount, "%.3ff };\n\n", mesh.normals[mesh.vertexCount*3 - 1]);
2109 }
2110
2111 if (mesh.tangents != NULL) // Vertex tangents (XYZW - 4 components per vertex - float)
2112 {
2113 byteCount += sprintf(txtData + byteCount, "static float %s_TANGENT_DATA[%i] = { ", varFileName, mesh.vertexCount*4);
2114 for (int i = 0; i < mesh.vertexCount*4 - 1; i++) byteCount += sprintf(txtData + byteCount, ((i%TEXT_BYTES_PER_LINE == 0)? "%.3ff,\n" : "%.3ff, "), mesh.tangents[i]);
2115 byteCount += sprintf(txtData + byteCount, "%.3ff };\n\n", mesh.tangents[mesh.vertexCount*4 - 1]);
2116 }
2117
2118 if (mesh.colors != NULL) // Vertex colors (RGBA - 4 components per vertex - unsigned char)
2119 {
2120 byteCount += sprintf(txtData + byteCount, "static unsigned char %s_COLOR_DATA[%i] = { ", varFileName, mesh.vertexCount*4);
2121 for (int i = 0; i < mesh.vertexCount*4 - 1; i++) byteCount += sprintf(txtData + byteCount, ((i%TEXT_BYTES_PER_LINE == 0)? "0x%x,\n" : "0x%x, "), mesh.colors[i]);
2122 byteCount += sprintf(txtData + byteCount, "0x%x };\n\n", mesh.colors[mesh.vertexCount*4 - 1]);
2123 }
2124
2125 if (mesh.indices != NULL) // Vertex indices (3 index per triangle - unsigned short)
2126 {
2127 byteCount += sprintf(txtData + byteCount, "static unsigned short %s_INDEX_DATA[%i] = { ", varFileName, mesh.triangleCount*3);
2128 for (int i = 0; i < mesh.triangleCount*3 - 1; i++) byteCount += sprintf(txtData + byteCount, ((i%TEXT_BYTES_PER_LINE == 0)? "%i,\n" : "%i, "), mesh.indices[i]);
2129 byteCount += sprintf(txtData + byteCount, "%i };\n", mesh.indices[mesh.triangleCount*3 - 1]);
2130 }
2131 //-----------------------------------------------------------------------------------------
2132
2133 // NOTE: Text data size exported is determined by '\0' (NULL) character
2134 result = SaveFileText(fileName, txtData);
2135
2136 RL_FREE(txtData);
2137
2138 //if (result != 0) TRACELOG(LOG_INFO, "FILEIO: [%s] Image as code exported successfully", fileName);
2139 //else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to export image as code", fileName);
2140
2141 return result;
2142 }
2143
2144 #if SUPPORT_FILEFORMAT_OBJ || SUPPORT_FILEFORMAT_MTL
2145 // Process obj materials
2146 static void ProcessMaterialsOBJ(Material *materials, tinyobj_material_t *mats, int materialCount)
2147 {
2148 // Init model mats
2149 for (int m = 0; m < materialCount; m++)
2150 {
2151 // Init material to default
2152 // NOTE: Uses default shader, which only supports MATERIAL_MAP_DIFFUSE
2153 materials[m] = LoadMaterialDefault();
2154
2155 if (mats == NULL) continue;
2156
2157 // Get default texture, in case no texture is defined
2158 // NOTE: rlgl default texture is a 1x1 pixel UNCOMPRESSED_R8G8B8A8
2159 materials[m].maps[MATERIAL_MAP_DIFFUSE].texture = (Texture2D){ rlGetTextureIdDefault(), 1, 1, 1, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 };
2160
2161 if (mats[m].diffuse_texname != NULL) materials[m].maps[MATERIAL_MAP_DIFFUSE].texture = LoadTexture(mats[m].diffuse_texname); //char *diffuse_texname; // map_Kd
2162 else materials[m].maps[MATERIAL_MAP_DIFFUSE].color = (Color){ (unsigned char)(mats[m].diffuse[0]*255.0f), (unsigned char)(mats[m].diffuse[1]*255.0f), (unsigned char)(mats[m].diffuse[2]*255.0f), 255 }; //float diffuse[3];
2163 materials[m].maps[MATERIAL_MAP_DIFFUSE].value = 0.0f;
2164
2165 if (mats[m].specular_texname != NULL) materials[m].maps[MATERIAL_MAP_SPECULAR].texture = LoadTexture(mats[m].specular_texname); //char *specular_texname; // map_Ks
2166 materials[m].maps[MATERIAL_MAP_SPECULAR].color = (Color){ (unsigned char)(mats[m].specular[0]*255.0f), (unsigned char)(mats[m].specular[1]*255.0f), (unsigned char)(mats[m].specular[2]*255.0f), 255 }; //float specular[3];
2167 materials[m].maps[MATERIAL_MAP_SPECULAR].value = 0.0f;
2168
2169 if (mats[m].bump_texname != NULL) materials[m].maps[MATERIAL_MAP_NORMAL].texture = LoadTexture(mats[m].bump_texname); //char *bump_texname; // map_bump, bump
2170 materials[m].maps[MATERIAL_MAP_NORMAL].color = WHITE;
2171 materials[m].maps[MATERIAL_MAP_NORMAL].value = mats[m].shininess;
2172
2173 materials[m].maps[MATERIAL_MAP_EMISSION].color = (Color){ (unsigned char)(mats[m].emission[0]*255.0f), (unsigned char)(mats[m].emission[1]*255.0f), (unsigned char)(mats[m].emission[2]*255.0f), 255 }; //float emission[3];
2174
2175 if (mats[m].displacement_texname != NULL) materials[m].maps[MATERIAL_MAP_HEIGHT].texture = LoadTexture(mats[m].displacement_texname); //char *displacement_texname; // disp
2176 }
2177 }
2178 #endif
2179
2180 // Load materials from model file
2181 Material *LoadMaterials(const char *fileName, int *materialCount)
2182 {
2183 Material *materials = NULL;
2184 unsigned int count = 0;
2185
2186 // TODO: Support IQM and GLTF for materials parsing
2187
2188 #if SUPPORT_FILEFORMAT_MTL
2189 if (IsFileExtension(fileName, ".mtl"))
2190 {
2191 tinyobj_material_t *mats = NULL;
2192
2193 int result = tinyobj_parse_mtl_file(&mats, &count, fileName);
2194 if (result != TINYOBJ_SUCCESS) TRACELOG(LOG_WARNING, "MATERIAL: [%s] Failed to parse materials file", fileName);
2195
2196 materials = (Material *)RL_CALLOC(count, sizeof(Material));
2197 ProcessMaterialsOBJ(materials, mats, count);
2198
2199 tinyobj_materials_free(mats, count);
2200 }
2201 #else
2202 TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to load material file", fileName);
2203 #endif
2204
2205 *materialCount = count;
2206 return materials;
2207 }
2208
2209 // Load default material (Supports: DIFFUSE, SPECULAR, NORMAL maps)
2210 Material LoadMaterialDefault(void)
2211 {
2212 Material material = { 0 };
2213 material.maps = (MaterialMap *)RL_CALLOC(MAX_MATERIAL_MAPS, sizeof(MaterialMap));
2214
2215 // Using rlgl default shader
2216 material.shader.id = rlGetShaderIdDefault();
2217 material.shader.locs = rlGetShaderLocsDefault();
2218
2219 // Using rlgl default texture (1x1 pixel, UNCOMPRESSED_R8G8B8A8, 1 mipmap)
2220 material.maps[MATERIAL_MAP_DIFFUSE].texture = (Texture2D){ rlGetTextureIdDefault(), 1, 1, 1, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 };
2221 //material.maps[MATERIAL_MAP_NORMAL].texture; // NOTE: By default, not set
2222 //material.maps[MATERIAL_MAP_SPECULAR].texture; // NOTE: By default, not set
2223
2224 material.maps[MATERIAL_MAP_DIFFUSE].color = WHITE; // Diffuse color
2225 material.maps[MATERIAL_MAP_SPECULAR].color = WHITE; // Specular color
2226
2227 return material;
2228 }
2229
2230 // Check if a material is valid (map textures loaded in GPU)
2231 bool IsMaterialValid(Material material)
2232 {
2233 bool result = false;
2234
2235 if ((material.maps != NULL) && // Validate material contain some map
2236 (material.shader.id > 0)) result = true; // Validate material shader is valid
2237
2238 // NOTE: Checking if available maps contain loaded textures does not determine if
2239 // a material is valid, there can be maps without a texture assigned, only properties
2240
2241 return result;
2242 }
2243
2244 // Unload material from memory
2245 void UnloadMaterial(Material material)
2246 {
2247 // Unload material shader (avoid unloading default shader, managed by raylib)
2248 if (material.shader.id != rlGetShaderIdDefault()) UnloadShader(material.shader);
2249
2250 // Unload loaded texture maps (avoid unloading default texture, managed by raylib)
2251 if (material.maps != NULL)
2252 {
2253 for (int i = 0; i < MAX_MATERIAL_MAPS; i++)
2254 {
2255 if (material.maps[i].texture.id != rlGetTextureIdDefault()) rlUnloadTexture(material.maps[i].texture.id);
2256 }
2257 }
2258
2259 RL_FREE(material.maps);
2260 }
2261
2262 // Set texture for a material map type (MATERIAL_MAP_DIFFUSE, MATERIAL_MAP_SPECULAR...)
2263 // NOTE: Previous texture should be manually unloaded
2264 void SetMaterialTexture(Material *material, int mapType, Texture2D texture)
2265 {
2266 material->maps[mapType].texture = texture;
2267 }
2268
2269 // Set the material for a mesh
2270 void SetModelMeshMaterial(Model *model, int meshId, int materialId)
2271 {
2272 if (meshId >= model->meshCount) TRACELOG(LOG_WARNING, "MESH: Id greater than mesh count");
2273 else if (materialId >= model->materialCount) TRACELOG(LOG_WARNING, "MATERIAL: Id greater than material count");
2274 else model->meshMaterial[meshId] = materialId;
2275 }
2276
2277 // Load model animations from file
2278 ModelAnimation *LoadModelAnimations(const char *fileName, int *animCount)
2279 {
2280 ModelAnimation *animations = NULL;
2281
2282 #if SUPPORT_FILEFORMAT_IQM
2283 if (IsFileExtension(fileName, ".iqm")) animations = LoadModelAnimationsIQM(fileName, animCount);
2284 #endif
2285 #if SUPPORT_FILEFORMAT_M3D
2286 if (IsFileExtension(fileName, ".m3d")) animations = LoadModelAnimationsM3D(fileName, animCount);
2287 #endif
2288 #if SUPPORT_FILEFORMAT_GLTF
2289 if (IsFileExtension(fileName, ".gltf;.glb")) animations = LoadModelAnimationsGLTF(fileName, animCount);
2290 #endif
2291
2292 return animations;
2293 }
2294
2295 // Update model animation data (vertex buffers / bone matrices) for a specific pose
2296 // NOTE 1: Request frame could be fractional, using a lerp interpolation between two frames
2297 // NOTE 2: Updated vertex animation data is uploaded to GPU in case of CPU skinning,
2298 // for GPU skinning, bone matrices are uploaded to shader on DrawModelEx()
2299 void UpdateModelAnimation(Model model, ModelAnimation anim, float frame)
2300 {
2301 if (model.boneMatrices == NULL) return;
2302
2303 //UpdateModelAnimationEx(model, anim, frame, anim, frame, 0.0f);
2304
2305 // Update model animated bones transform matrices for a given frame
2306 if ((anim.keyframeCount > 0) && (model.skeleton.bones != NULL) && (anim.keyframePoses != NULL))
2307 {
2308 // Get frame and blending from frame factor required
2309 int currentFrame = (int)frame;
2310 int nextFrame = currentFrame + 1;
2311 float blend = frame - currentFrame;
2312 blend = Clamp(blend, 0.0f, 1.0f);
2313 if (currentFrame >= anim.keyframeCount) currentFrame = currentFrame%anim.keyframeCount;
2314 if (nextFrame >= anim.keyframeCount) nextFrame = nextFrame%anim.keyframeCount;
2315
2316 Matrix bindPoseMatrix = { 0 };
2317 Matrix currentPoseMatrix = { 0 };
2318
2319 // Update all bones and bone matrices of model
2320 for (int boneIndex = 0; boneIndex < model.skeleton.boneCount; boneIndex++)
2321 {
2322 // Compute interpolated pose between current and next frame
2323 // NOTE: Storing animation frame data in model.currentPose
2324 model.currentPose[boneIndex].translation = Vector3Lerp(
2325 anim.keyframePoses[currentFrame][boneIndex].translation,
2326 anim.keyframePoses[nextFrame][boneIndex].translation, blend);
2327 model.currentPose[boneIndex].rotation = QuaternionSlerp(
2328 anim.keyframePoses[currentFrame][boneIndex].rotation,
2329 anim.keyframePoses[nextFrame][boneIndex].rotation, blend);
2330 model.currentPose[boneIndex].scale = Vector3Lerp(
2331 anim.keyframePoses[currentFrame][boneIndex].scale,
2332 anim.keyframePoses[nextFrame][boneIndex].scale, blend);
2333
2334 // Compute runtime bone matrix from model current pose
2335 //-----------------------------------------------------------------------------------
2336 Transform *bindPoseTransform = &model.skeleton.bindPose[boneIndex];
2337 bindPoseMatrix = MatrixMultiply(
2338 MatrixMultiply(MatrixScale(bindPoseTransform->scale.x, bindPoseTransform->scale.y, bindPoseTransform->scale.z),
2339 QuaternionToMatrix(bindPoseTransform->rotation)),
2340 MatrixTranslate(bindPoseTransform->translation.x, bindPoseTransform->translation.y, bindPoseTransform->translation.z));
2341
2342 Transform *currentPoseTransform = &model.currentPose[boneIndex];
2343 currentPoseMatrix = MatrixMultiply(
2344 MatrixMultiply(MatrixScale(currentPoseTransform->scale.x, currentPoseTransform->scale.y, currentPoseTransform->scale.z),
2345 QuaternionToMatrix(currentPoseTransform->rotation)),
2346 MatrixTranslate(currentPoseTransform->translation.x, currentPoseTransform->translation.y, currentPoseTransform->translation.z));
2347
2348 model.boneMatrices[boneIndex] = MatrixMultiply(MatrixInvert(bindPoseMatrix), currentPoseMatrix);
2349 //-----------------------------------------------------------------------------------
2350 }
2351
2352 // CPU skinning, updates CPU buffers and uploads them to GPU
2353 // NOTE: On GPU skinning not supported, use CPU skinning
2354 UpdateModelAnimationVertexBuffers(model);
2355 }
2356 }
2357
2358 // Update model animation data (vertex buffers / bone matrices) for a specific pose,
2359 // defined by two different animations at specific frames blended together
2360 // NOTE 1: Request frames could be fractional, using a lerp interpolation between two frames
2361 // NOTE 2: Updated vertex animation data is uploaded to GPU in case of CPU skinning,
2362 // for GPU skinning, bone matrices are uploaded to shader on DrawModelEx()
2363 void UpdateModelAnimationEx(Model model, ModelAnimation animA, float frameA, ModelAnimation animB, float frameB, float blend)
2364 {
2365 if (model.boneMatrices == NULL) return;
2366
2367 if ((animA.keyframeCount > 0) && (animA.keyframePoses != NULL) &&
2368 (animB.keyframeCount > 0) && (animB.keyframePoses != NULL) &&
2369 (blend >= 0.0f) && (blend <= 1.0f))
2370 {
2371 // Inter-frame interpolation values for first animation
2372 int currentFrameA = (int)frameA%animA.keyframeCount;
2373 int nextFrameA = currentFrameA + 1;
2374 float blendA = frameA - currentFrameA;
2375 blendA = Clamp(blendA, 0.0f, 1.0f);
2376 if (currentFrameA >= animA.keyframeCount) currentFrameA = currentFrameA%animA.keyframeCount;
2377 if (nextFrameA >= animA.keyframeCount) nextFrameA = nextFrameA%animA.keyframeCount;
2378
2379 // Inter-frame interpolation values for second animation
2380 int currentFrameB = (int)frameB%animB.keyframeCount;
2381 int nextFrameB = currentFrameB + 1;
2382 float blendB = frameB - currentFrameB;
2383 blendB = Clamp(blendB, 0.0f, 1.0f);
2384 if (currentFrameB >= animB.keyframeCount) currentFrameB = currentFrameB%animB.keyframeCount;
2385 if (nextFrameB >= animB.keyframeCount) nextFrameB = nextFrameB%animB.keyframeCount;
2386
2387 Matrix bindPoseMatrix = { 0 };
2388 Matrix currentPoseMatrix = { 0 };
2389
2390 for (int boneIndex = 0; boneIndex < model.skeleton.boneCount; boneIndex++)
2391 {
2392 // Get frame-interpolation for first animation
2393 Vector3 frameATranslation = Vector3Lerp(
2394 animA.keyframePoses[currentFrameA][boneIndex].translation,
2395 animA.keyframePoses[nextFrameA][boneIndex].translation, blendA);
2396 Quaternion frameARotation = QuaternionSlerp(
2397 animA.keyframePoses[currentFrameA][boneIndex].rotation,
2398 animA.keyframePoses[nextFrameA][boneIndex].rotation, blendA);
2399 Vector3 frameAScale = Vector3Lerp(
2400 animA.keyframePoses[currentFrameA][boneIndex].scale,
2401 animA.keyframePoses[nextFrameA][boneIndex].scale, blendA);
2402
2403 // Get frame-interpolation for second animation
2404 Vector3 frameBTranslation = Vector3Lerp(
2405 animB.keyframePoses[currentFrameB][boneIndex].translation,
2406 animB.keyframePoses[nextFrameB][boneIndex].translation, blendB);
2407 Quaternion frameBRotation = QuaternionSlerp(
2408 animB.keyframePoses[currentFrameB][boneIndex].rotation,
2409 animB.keyframePoses[nextFrameB][boneIndex].rotation, blendB);
2410 Vector3 frameBScale = Vector3Lerp(
2411 animB.keyframePoses[currentFrameB][boneIndex].scale,
2412 animB.keyframePoses[nextFrameB][boneIndex].scale, blendB);
2413
2414 // Compute interpolated pose between both animations frames
2415 // NOTE: Storing animation frame data in model.currentPose
2416 model.currentPose[boneIndex].translation = Vector3Lerp(frameATranslation, frameBTranslation, blend);
2417 model.currentPose[boneIndex].rotation = QuaternionSlerp(frameARotation, frameBRotation, blend);
2418 model.currentPose[boneIndex].scale = Vector3Lerp(frameAScale, frameBScale, blend);
2419
2420 // Compute runtime bone matrix from model current pose
2421 //-----------------------------------------------------------------------------------
2422 Transform *bindPoseTransform = &model.skeleton.bindPose[boneIndex];
2423 bindPoseMatrix = MatrixMultiply(
2424 MatrixMultiply(MatrixScale(bindPoseTransform->scale.x, bindPoseTransform->scale.y, bindPoseTransform->scale.z),
2425 QuaternionToMatrix(bindPoseTransform->rotation)),
2426 MatrixTranslate(bindPoseTransform->translation.x, bindPoseTransform->translation.y, bindPoseTransform->translation.z));
2427
2428 Transform *currentPoseTransform = &model.currentPose[boneIndex];
2429 currentPoseMatrix = MatrixMultiply(
2430 MatrixMultiply(MatrixScale(currentPoseTransform->scale.x, currentPoseTransform->scale.y, currentPoseTransform->scale.z),
2431 QuaternionToMatrix(currentPoseTransform->rotation)),
2432 MatrixTranslate(currentPoseTransform->translation.x, currentPoseTransform->translation.y, currentPoseTransform->translation.z));
2433
2434 model.boneMatrices[boneIndex] = MatrixMultiply(MatrixInvert(bindPoseMatrix), currentPoseMatrix);
2435 //-----------------------------------------------------------------------------------
2436
2437 /*
2438 Vector3 outATranslation = animA.keyframePoses[currentFrameA][boneIndex].translation;
2439 Quaternion outARotation = animA.keyframePoses[currentFrameA][boneIndex].rotation;
2440 Vector3 outAScale = animA.keyframePoses[currentFrameA][boneIndex].scale;
2441
2442 Vector3 outBTranslation = animB.keyframePoses[currentFrameB][boneIndex].translation;
2443 Quaternion outBRotation = animB.keyframePoses[currentFrameB][boneIndex].rotation;
2444 Vector3 outBScale = animB.keyframePoses[currentFrameB][boneIndex].scale;
2445
2446 // Invert bind pose transformation
2447 Vector3 invBindTranslation = Vector3RotateByQuaternion(
2448 Vector3Negate(model.skeleton.bindPose[boneIndex].translation),
2449 QuaternionInvert(model.skeleton.bindPose[boneIndex].rotation));
2450 Quaternion invBindRotation = QuaternionInvert(model.skeleton.bindPose[boneIndex].rotation);
2451 Vector3 invBindScale = Vector3Divide((Vector3){ 1.0f, 1.0f, 1.0f }, model.skeleton.bindPose[boneIndex].scale);
2452
2453 Vector3 boneTranslation = Vector3Add(Vector3RotateByQuaternion(
2454 Vector3Multiply(model.currentPose[boneIndex].scale, invBindTranslation),
2455 model.currentPose[boneIndex].rotation),
2456 model.currentPose[boneIndex].translation);
2457 Quaternion boneRotation = QuaternionMultiply(model.currentPose[boneIndex].rotation, invBindRotation);
2458 Vector3 boneScale = Vector3Multiply(model.currentPose[boneIndex].scale, invBindScale);
2459
2460 model.boneMatrices[boneIndex] = MatrixMultiply(
2461 MatrixMultiply(QuaternionToMatrix(boneRotation),
2462 MatrixTranslate(boneTranslation.x, boneTranslation.y, boneTranslation.z)),
2463 MatrixScale(boneScale.x, boneScale.y, boneScale.z));
2464 */
2465 }
2466
2467 // CPU skinning, updates CPU buffers and uploads them to GPU (if available)
2468 // NOTE: Fallback in case GPU skinning is not supported or enabled
2469 UpdateModelAnimationVertexBuffers(model);
2470 }
2471 }
2472
2473 // Update model vertex animation buffers (positions and normals)
2474 // NOTE: Required for CPU skinning, uploads animated vertex buffers to GPU
2475 static void UpdateModelAnimationVertexBuffers(Model model)
2476 {
2477 for (int m = 0; m < model.meshCount; m++)
2478 {
2479 Mesh mesh = model.meshes[m];
2480 Vector3 animVertex = { 0 };
2481 Vector3 animNormal = { 0 };
2482 const int vertexValuesCount = mesh.vertexCount*3;
2483
2484 int boneIndex = 0;
2485 int boneCounter = 0;
2486 float boneWeight = 0.0f;
2487 bool bufferUpdateRequired = false; // Flag to check when anim vertex information is updated
2488
2489 // Skip if missing bone data or missing anim buffers initialization
2490 if ((mesh.boneWeights == NULL) || (mesh.boneIndices == NULL) ||
2491 (mesh.animVertices == NULL) || (mesh.animNormals == NULL)) continue;
2492
2493 for (int vCounter = 0; vCounter < vertexValuesCount; vCounter += 3)
2494 {
2495 mesh.animVertices[vCounter] = 0;
2496 mesh.animVertices[vCounter + 1] = 0;
2497 mesh.animVertices[vCounter + 2] = 0;
2498 if (mesh.animNormals != NULL)
2499 {
2500 mesh.animNormals[vCounter] = 0;
2501 mesh.animNormals[vCounter + 1] = 0;
2502 mesh.animNormals[vCounter + 2] = 0;
2503 }
2504
2505 // Iterates over 4 bones per vertex
2506 for (int j = 0; j < 4; j++, boneCounter++)
2507 {
2508 boneWeight = mesh.boneWeights[boneCounter];
2509 boneIndex = mesh.boneIndices[boneCounter];
2510
2511 // Early stop when no transformation will be applied
2512 if (boneWeight == 0.0f) continue;
2513 animVertex = (Vector3){ mesh.vertices[vCounter], mesh.vertices[vCounter + 1], mesh.vertices[vCounter + 2] };
2514 animVertex = Vector3Transform(animVertex, model.boneMatrices[boneIndex]);
2515 mesh.animVertices[vCounter] += animVertex.x*boneWeight;
2516 mesh.animVertices[vCounter + 1] += animVertex.y*boneWeight;
2517 mesh.animVertices[vCounter + 2] += animVertex.z*boneWeight;
2518 bufferUpdateRequired = true;
2519
2520 // Normals processing
2521 // NOTE: Using meshes.baseNormals (default normal) to calculate meshes.normals (animated normals)
2522 if ((mesh.normals != NULL) && (mesh.animNormals != NULL ))
2523 {
2524 animNormal = (Vector3){ mesh.normals[vCounter], mesh.normals[vCounter + 1], mesh.normals[vCounter + 2] };
2525 animNormal = Vector3Transform(animNormal, MatrixTranspose(MatrixInvert(model.boneMatrices[boneIndex])));
2526 mesh.animNormals[vCounter] += animNormal.x*boneWeight;
2527 mesh.animNormals[vCounter + 1] += animNormal.y*boneWeight;
2528 mesh.animNormals[vCounter + 2] += animNormal.z*boneWeight;
2529 }
2530 }
2531 }
2532
2533 if (bufferUpdateRequired)
2534 {
2535 // Update GPU vertex buffers with updated data (position + normals)
2536 rlUpdateVertexBuffer(mesh.vboId[SHADER_LOC_VERTEX_POSITION], mesh.animVertices, mesh.vertexCount*3*sizeof(float), 0);
2537 if (mesh.normals != NULL) rlUpdateVertexBuffer(mesh.vboId[SHADER_LOC_VERTEX_NORMAL], mesh.animNormals, mesh.vertexCount*3*sizeof(float), 0);
2538 }
2539 }
2540 }
2541
2542 // Unload animation array data
2543 void UnloadModelAnimations(ModelAnimation *animations, int animCount)
2544 {
2545 for (int a = 0; a < animCount; a++)
2546 {
2547 for (int i = 0; i < animations[a].keyframeCount; i++)
2548 RL_FREE(animations[a].keyframePoses[i]);
2549
2550 RL_FREE(animations[a].keyframePoses);
2551 }
2552
2553 RL_FREE(animations);
2554 }
2555
2556 // Check model animation skeleton match
2557 // NOTE: Only number of bones and parent connections are checked
2558 bool IsModelAnimationValid(Model model, ModelAnimation anim)
2559 {
2560 int result = true;
2561
2562 if (model.skeleton.boneCount != anim.boneCount) result = false;
2563
2564 return result;
2565 }
2566
2567 #if SUPPORT_MESH_GENERATION
2568 // Generate polygonal mesh
2569 Mesh GenMeshPoly(int sides, float radius)
2570 {
2571 Mesh mesh = { 0 };
2572
2573 if (sides < 3) return mesh; // Security check
2574
2575 int vertexCount = sides*3;
2576
2577 // Vertices definition
2578 Vector3 *vertices = (Vector3 *)RL_MALLOC(vertexCount*sizeof(Vector3));
2579
2580 float d = 0.0f, dStep = 360.0f/sides;
2581 for (int v = 0; v < vertexCount - 2; v += 3)
2582 {
2583 vertices[v] = (Vector3){ 0.0f, 0.0f, 0.0f };
2584 vertices[v + 1] = (Vector3){ sinf(DEG2RAD*d)*radius, 0.0f, cosf(DEG2RAD*d)*radius };
2585 vertices[v + 2] = (Vector3){ sinf(DEG2RAD*(d+dStep))*radius, 0.0f, cosf(DEG2RAD*(d+dStep))*radius };
2586 d += dStep;
2587 }
2588
2589 // Normals definition
2590 Vector3 *normals = (Vector3 *)RL_MALLOC(vertexCount*sizeof(Vector3));
2591 for (int n = 0; n < vertexCount; n++) normals[n] = (Vector3){ 0.0f, 1.0f, 0.0f }; // Vector3.up;
2592
2593 // TexCoords definition
2594 Vector2 *texcoords = (Vector2 *)RL_MALLOC(vertexCount*sizeof(Vector2));
2595 for (int n = 0; n < vertexCount; n++) texcoords[n] = (Vector2){ 0.0f, 0.0f };
2596
2597 mesh.vertexCount = vertexCount;
2598 mesh.triangleCount = sides;
2599 mesh.vertices = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float));
2600 mesh.texcoords = (float *)RL_MALLOC(mesh.vertexCount*2*sizeof(float));
2601 mesh.normals = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float));
2602
2603 // Mesh vertices position array
2604 for (int i = 0; i < mesh.vertexCount; i++)
2605 {
2606 mesh.vertices[3*i] = vertices[i].x;
2607 mesh.vertices[3*i + 1] = vertices[i].y;
2608 mesh.vertices[3*i + 2] = vertices[i].z;
2609 }
2610
2611 // Mesh texcoords array
2612 for (int i = 0; i < mesh.vertexCount; i++)
2613 {
2614 mesh.texcoords[2*i] = texcoords[i].x;
2615 mesh.texcoords[2*i + 1] = texcoords[i].y;
2616 }
2617
2618 // Mesh normals array
2619 for (int i = 0; i < mesh.vertexCount; i++)
2620 {
2621 mesh.normals[3*i] = normals[i].x;
2622 mesh.normals[3*i + 1] = normals[i].y;
2623 mesh.normals[3*i + 2] = normals[i].z;
2624 }
2625
2626 RL_FREE(vertices);
2627 RL_FREE(normals);
2628 RL_FREE(texcoords);
2629
2630 // Upload vertex data to GPU (static mesh)
2631 // NOTE: mesh.vboId array is allocated inside UploadMesh()
2632 UploadMesh(&mesh, false);
2633
2634 return mesh;
2635 }
2636
2637 // Generate plane mesh (with subdivisions)
2638 Mesh GenMeshPlane(float width, float length, int resX, int resZ)
2639 {
2640 Mesh mesh = { 0 };
2641
2642 #define CUSTOM_MESH_GEN_PLANE
2643 #if defined(CUSTOM_MESH_GEN_PLANE)
2644 resX++;
2645 resZ++;
2646
2647 // Vertices definition
2648 int vertexCount = resX*resZ; // vertices get reused for the faces
2649
2650 Vector3 *vertices = (Vector3 *)RL_MALLOC(vertexCount*sizeof(Vector3));
2651 for (int z = 0; z < resZ; z++)
2652 {
2653 // [-length/2, length/2]
2654 float zPos = ((float)z/(resZ - 1) - 0.5f)*length;
2655 for (int x = 0; x < resX; x++)
2656 {
2657 // [-width/2, width/2]
2658 float xPos = ((float)x/(resX - 1) - 0.5f)*width;
2659 vertices[x + z*resX] = (Vector3){ xPos, 0.0f, zPos };
2660 }
2661 }
2662
2663 // Normals definition
2664 Vector3 *normals = (Vector3 *)RL_MALLOC(vertexCount*sizeof(Vector3));
2665 for (int n = 0; n < vertexCount; n++) normals[n] = (Vector3){ 0.0f, 1.0f, 0.0f }; // Vector3.up;
2666
2667 // TexCoords definition
2668 Vector2 *texcoords = (Vector2 *)RL_MALLOC(vertexCount*sizeof(Vector2));
2669 for (int v = 0; v < resZ; v++)
2670 {
2671 for (int u = 0; u < resX; u++)
2672 {
2673 texcoords[u + v*resX] = (Vector2){ (float)u/(resX - 1), (float)v/(resZ - 1) };
2674 }
2675 }
2676
2677 // Triangles definition (indices)
2678 int numFaces = (resX - 1)*(resZ - 1);
2679 int *triangles = (int *)RL_MALLOC(numFaces*6*sizeof(int));
2680 int t = 0;
2681 for (int face = 0; face < numFaces; face++)
2682 {
2683 // Retrieve lower left corner from face ind
2684 int i = face + face/(resX - 1);
2685
2686 triangles[t++] = i + resX;
2687 triangles[t++] = i + 1;
2688 triangles[t++] = i;
2689
2690 triangles[t++] = i + resX;
2691 triangles[t++] = i + resX + 1;
2692 triangles[t++] = i + 1;
2693 }
2694
2695 mesh.vertexCount = vertexCount;
2696 mesh.triangleCount = numFaces*2;
2697 mesh.vertices = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float));
2698 mesh.texcoords = (float *)RL_MALLOC(mesh.vertexCount*2*sizeof(float));
2699 mesh.normals = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float));
2700 mesh.indices = (unsigned short *)RL_MALLOC(mesh.triangleCount*3*sizeof(unsigned short));
2701
2702 // Mesh vertices position array
2703 for (int i = 0; i < mesh.vertexCount; i++)
2704 {
2705 mesh.vertices[3*i] = vertices[i].x;
2706 mesh.vertices[3*i + 1] = vertices[i].y;
2707 mesh.vertices[3*i + 2] = vertices[i].z;
2708 }
2709
2710 // Mesh texcoords array
2711 for (int i = 0; i < mesh.vertexCount; i++)
2712 {
2713 mesh.texcoords[2*i] = texcoords[i].x;
2714 mesh.texcoords[2*i + 1] = texcoords[i].y;
2715 }
2716
2717 // Mesh normals array
2718 for (int i = 0; i < mesh.vertexCount; i++)
2719 {
2720 mesh.normals[3*i] = normals[i].x;
2721 mesh.normals[3*i + 1] = normals[i].y;
2722 mesh.normals[3*i + 2] = normals[i].z;
2723 }
2724
2725 // Mesh indices array initialization
2726 for (int i = 0; i < mesh.triangleCount*3; i++) mesh.indices[i] = triangles[i];
2727
2728 RL_FREE(vertices);
2729 RL_FREE(normals);
2730 RL_FREE(texcoords);
2731 RL_FREE(triangles);
2732
2733 #else // Use par_shapes library to generate plane mesh
2734
2735 par_shapes_mesh *plane = par_shapes_create_plane(resX, resZ); // No normals/texcoords generated!!!
2736 par_shapes_scale(plane, width, length, 1.0f);
2737 par_shapes_rotate(plane, -PI/2.0f, (float[]){ 1, 0, 0 });
2738 par_shapes_translate(plane, -width/2, 0.0f, length/2);
2739
2740 mesh.vertices = (float *)RL_MALLOC(plane->ntriangles*3*3*sizeof(float));
2741 mesh.texcoords = (float *)RL_MALLOC(plane->ntriangles*3*2*sizeof(float));
2742 mesh.normals = (float *)RL_MALLOC(plane->ntriangles*3*3*sizeof(float));
2743
2744 mesh.vertexCount = plane->ntriangles*3;
2745 mesh.triangleCount = plane->ntriangles;
2746
2747 for (int k = 0; k < mesh.vertexCount; k++)
2748 {
2749 mesh.vertices[k*3] = plane->points[plane->triangles[k]*3];
2750 mesh.vertices[k*3 + 1] = plane->points[plane->triangles[k]*3 + 1];
2751 mesh.vertices[k*3 + 2] = plane->points[plane->triangles[k]*3 + 2];
2752
2753 mesh.normals[k*3] = plane->normals[plane->triangles[k]*3];
2754 mesh.normals[k*3 + 1] = plane->normals[plane->triangles[k]*3 + 1];
2755 mesh.normals[k*3 + 2] = plane->normals[plane->triangles[k]*3 + 2];
2756
2757 mesh.texcoords[k*2] = plane->tcoords[plane->triangles[k]*2];
2758 mesh.texcoords[k*2 + 1] = plane->tcoords[plane->triangles[k]*2 + 1];
2759 }
2760
2761 par_shapes_free_mesh(plane);
2762 #endif
2763
2764 // Upload vertex data to GPU (static mesh)
2765 UploadMesh(&mesh, false);
2766
2767 return mesh;
2768 }
2769
2770 // Generated cuboid mesh
2771 Mesh GenMeshCube(float width, float height, float length)
2772 {
2773 Mesh mesh = { 0 };
2774
2775 #define CUSTOM_MESH_GEN_CUBE
2776 #if defined(CUSTOM_MESH_GEN_CUBE)
2777 float vertices[] = {
2778 -width/2, -height/2, length/2,
2779 width/2, -height/2, length/2,
2780 width/2, height/2, length/2,
2781 -width/2, height/2, length/2,
2782 -width/2, -height/2, -length/2,
2783 -width/2, height/2, -length/2,
2784 width/2, height/2, -length/2,
2785 width/2, -height/2, -length/2,
2786 -width/2, height/2, -length/2,
2787 -width/2, height/2, length/2,
2788 width/2, height/2, length/2,
2789 width/2, height/2, -length/2,
2790 -width/2, -height/2, -length/2,
2791 width/2, -height/2, -length/2,
2792 width/2, -height/2, length/2,
2793 -width/2, -height/2, length/2,
2794 width/2, -height/2, -length/2,
2795 width/2, height/2, -length/2,
2796 width/2, height/2, length/2,
2797 width/2, -height/2, length/2,
2798 -width/2, -height/2, -length/2,
2799 -width/2, -height/2, length/2,
2800 -width/2, height/2, length/2,
2801 -width/2, height/2, -length/2
2802 };
2803
2804 float texcoords[] = {
2805 0.0f, 0.0f,
2806 1.0f, 0.0f,
2807 1.0f, 1.0f,
2808 0.0f, 1.0f,
2809 1.0f, 0.0f,
2810 1.0f, 1.0f,
2811 0.0f, 1.0f,
2812 0.0f, 0.0f,
2813 0.0f, 1.0f,
2814 0.0f, 0.0f,
2815 1.0f, 0.0f,
2816 1.0f, 1.0f,
2817 1.0f, 1.0f,
2818 0.0f, 1.0f,
2819 0.0f, 0.0f,
2820 1.0f, 0.0f,
2821 1.0f, 0.0f,
2822 1.0f, 1.0f,
2823 0.0f, 1.0f,
2824 0.0f, 0.0f,
2825 0.0f, 0.0f,
2826 1.0f, 0.0f,
2827 1.0f, 1.0f,
2828 0.0f, 1.0f
2829 };
2830
2831 float normals[] = {
2832 0.0f, 0.0f, 1.0f,
2833 0.0f, 0.0f, 1.0f,
2834 0.0f, 0.0f, 1.0f,
2835 0.0f, 0.0f, 1.0f,
2836 0.0f, 0.0f,-1.0f,
2837 0.0f, 0.0f,-1.0f,
2838 0.0f, 0.0f,-1.0f,
2839 0.0f, 0.0f,-1.0f,
2840 0.0f, 1.0f, 0.0f,
2841 0.0f, 1.0f, 0.0f,
2842 0.0f, 1.0f, 0.0f,
2843 0.0f, 1.0f, 0.0f,
2844 0.0f,-1.0f, 0.0f,
2845 0.0f,-1.0f, 0.0f,
2846 0.0f,-1.0f, 0.0f,
2847 0.0f,-1.0f, 0.0f,
2848 1.0f, 0.0f, 0.0f,
2849 1.0f, 0.0f, 0.0f,
2850 1.0f, 0.0f, 0.0f,
2851 1.0f, 0.0f, 0.0f,
2852 -1.0f, 0.0f, 0.0f,
2853 -1.0f, 0.0f, 0.0f,
2854 -1.0f, 0.0f, 0.0f,
2855 -1.0f, 0.0f, 0.0f
2856 };
2857
2858 mesh.vertices = (float *)RL_MALLOC(24*3*sizeof(float));
2859 memcpy(mesh.vertices, vertices, 24*3*sizeof(float));
2860
2861 mesh.texcoords = (float *)RL_MALLOC(24*2*sizeof(float));
2862 memcpy(mesh.texcoords, texcoords, 24*2*sizeof(float));
2863
2864 mesh.normals = (float *)RL_MALLOC(24*3*sizeof(float));
2865 memcpy(mesh.normals, normals, 24*3*sizeof(float));
2866
2867 mesh.indices = (unsigned short *)RL_MALLOC(36*sizeof(unsigned short));
2868
2869 int k = 0;
2870
2871 // Indices can be initialized right now
2872 for (int i = 0; i < 36; i += 6)
2873 {
2874 mesh.indices[i] = 4*k;
2875 mesh.indices[i + 1] = 4*k + 1;
2876 mesh.indices[i + 2] = 4*k + 2;
2877 mesh.indices[i + 3] = 4*k;
2878 mesh.indices[i + 4] = 4*k + 2;
2879 mesh.indices[i + 5] = 4*k + 3;
2880
2881 k++;
2882 }
2883
2884 mesh.vertexCount = 24;
2885 mesh.triangleCount = 12;
2886
2887 #else // Use par_shapes library to generate cube mesh
2888 /*
2889 // Platonic solids:
2890 par_shapes_mesh *par_shapes_create_tetrahedron(); // 4 sides polyhedron (pyramid)
2891 par_shapes_mesh *par_shapes_create_cube(); // 6 sides polyhedron (cube)
2892 par_shapes_mesh *par_shapes_create_octahedron(); // 8 sides polyhedron (diamond)
2893 par_shapes_mesh *par_shapes_create_dodecahedron(); // 12 sides polyhedron
2894 par_shapes_mesh *par_shapes_create_icosahedron(); // 20 sides polyhedron
2895 */
2896 // Platonic solid generation: cube (6 sides)
2897 // NOTE: No normals/texcoords generated by default
2898 par_shapes_mesh *cube = par_shapes_create_cube();
2899 cube->tcoords = PAR_MALLOC(float, 2*cube->npoints);
2900 for (int i = 0; i < 2*cube->npoints; i++) cube->tcoords[i] = 0.0f;
2901 par_shapes_scale(cube, width, height, length);
2902 par_shapes_translate(cube, -width/2, 0.0f, -length/2);
2903 par_shapes_compute_normals(cube);
2904
2905 mesh.vertices = (float *)RL_MALLOC(cube->ntriangles*3*3*sizeof(float));
2906 mesh.texcoords = (float *)RL_MALLOC(cube->ntriangles*3*2*sizeof(float));
2907 mesh.normals = (float *)RL_MALLOC(cube->ntriangles*3*3*sizeof(float));
2908
2909 mesh.vertexCount = cube->ntriangles*3;
2910 mesh.triangleCount = cube->ntriangles;
2911
2912 for (int k = 0; k < mesh.vertexCount; k++)
2913 {
2914 mesh.vertices[k*3] = cube->points[cube->triangles[k]*3];
2915 mesh.vertices[k*3 + 1] = cube->points[cube->triangles[k]*3 + 1];
2916 mesh.vertices[k*3 + 2] = cube->points[cube->triangles[k]*3 + 2];
2917
2918 mesh.normals[k*3] = cube->normals[cube->triangles[k]*3];
2919 mesh.normals[k*3 + 1] = cube->normals[cube->triangles[k]*3 + 1];
2920 mesh.normals[k*3 + 2] = cube->normals[cube->triangles[k]*3 + 2];
2921
2922 mesh.texcoords[k*2] = cube->tcoords[cube->triangles[k]*2];
2923 mesh.texcoords[k*2 + 1] = cube->tcoords[cube->triangles[k]*2 + 1];
2924 }
2925
2926 par_shapes_free_mesh(cube);
2927 #endif
2928
2929 // Upload vertex data to GPU (static mesh)
2930 UploadMesh(&mesh, false);
2931
2932 return mesh;
2933 }
2934
2935 // Generate sphere mesh (standard sphere)
2936 Mesh GenMeshSphere(float radius, int rings, int slices)
2937 {
2938 Mesh mesh = { 0 };
2939
2940 if ((rings >= 3) && (slices >= 3))
2941 {
2942 par_shapes_set_epsilon_degenerate_sphere(0.0);
2943 par_shapes_mesh *sphere = par_shapes_create_parametric_sphere(slices, rings);
2944 par_shapes_scale(sphere, radius, radius, radius);
2945 // NOTE: Soft normals are computed internally
2946
2947 mesh.vertices = (float *)RL_MALLOC(sphere->ntriangles*3*3*sizeof(float));
2948 mesh.texcoords = (float *)RL_MALLOC(sphere->ntriangles*3*2*sizeof(float));
2949 mesh.normals = (float *)RL_MALLOC(sphere->ntriangles*3*3*sizeof(float));
2950
2951 mesh.vertexCount = sphere->ntriangles*3;
2952 mesh.triangleCount = sphere->ntriangles;
2953
2954 for (int k = 0; k < mesh.vertexCount; k++)
2955 {
2956 mesh.vertices[k*3] = sphere->points[sphere->triangles[k]*3];
2957 mesh.vertices[k*3 + 1] = sphere->points[sphere->triangles[k]*3 + 1];
2958 mesh.vertices[k*3 + 2] = sphere->points[sphere->triangles[k]*3 + 2];
2959
2960 mesh.normals[k*3] = sphere->normals[sphere->triangles[k]*3];
2961 mesh.normals[k*3 + 1] = sphere->normals[sphere->triangles[k]*3 + 1];
2962 mesh.normals[k*3 + 2] = sphere->normals[sphere->triangles[k]*3 + 2];
2963
2964 mesh.texcoords[k*2] = sphere->tcoords[sphere->triangles[k]*2];
2965 mesh.texcoords[k*2 + 1] = sphere->tcoords[sphere->triangles[k]*2 + 1];
2966 }
2967
2968 par_shapes_free_mesh(sphere);
2969
2970 // Upload vertex data to GPU (static mesh)
2971 UploadMesh(&mesh, false);
2972 }
2973 else TRACELOG(LOG_WARNING, "MESH: Failed to generate mesh: sphere");
2974
2975 return mesh;
2976 }
2977
2978 // Generate hemisphere mesh (half sphere, no bottom cap)
2979 Mesh GenMeshHemiSphere(float radius, int rings, int slices)
2980 {
2981 Mesh mesh = { 0 };
2982
2983 if ((rings >= 3) && (slices >= 3))
2984 {
2985 if (radius < 0.0f) radius = 0.0f;
2986
2987 par_shapes_mesh *sphere = par_shapes_create_hemisphere(slices, rings);
2988 par_shapes_scale(sphere, radius, radius, radius);
2989 // NOTE: Soft normals are computed internally
2990
2991 mesh.vertices = (float *)RL_MALLOC(sphere->ntriangles*3*3*sizeof(float));
2992 mesh.texcoords = (float *)RL_MALLOC(sphere->ntriangles*3*2*sizeof(float));
2993 mesh.normals = (float *)RL_MALLOC(sphere->ntriangles*3*3*sizeof(float));
2994
2995 mesh.vertexCount = sphere->ntriangles*3;
2996 mesh.triangleCount = sphere->ntriangles;
2997
2998 for (int k = 0; k < mesh.vertexCount; k++)
2999 {
3000 mesh.vertices[k*3] = sphere->points[sphere->triangles[k]*3];
3001 mesh.vertices[k*3 + 1] = sphere->points[sphere->triangles[k]*3 + 1];
3002 mesh.vertices[k*3 + 2] = sphere->points[sphere->triangles[k]*3 + 2];
3003
3004 mesh.normals[k*3] = sphere->normals[sphere->triangles[k]*3];
3005 mesh.normals[k*3 + 1] = sphere->normals[sphere->triangles[k]*3 + 1];
3006 mesh.normals[k*3 + 2] = sphere->normals[sphere->triangles[k]*3 + 2];
3007
3008 mesh.texcoords[k*2] = sphere->tcoords[sphere->triangles[k]*2];
3009 mesh.texcoords[k*2 + 1] = sphere->tcoords[sphere->triangles[k]*2 + 1];
3010 }
3011
3012 par_shapes_free_mesh(sphere);
3013
3014 // Upload vertex data to GPU (static mesh)
3015 UploadMesh(&mesh, false);
3016 }
3017 else TRACELOG(LOG_WARNING, "MESH: Failed to generate mesh: hemisphere");
3018
3019 return mesh;
3020 }
3021
3022 // Generate cylinder mesh
3023 Mesh GenMeshCylinder(float radius, float height, int slices)
3024 {
3025 Mesh mesh = { 0 };
3026
3027 if (slices >= 3)
3028 {
3029 // Instance a cylinder that sits on the Z=0 plane using the given tessellation
3030 // levels across the UV domain. Think of "slices" like a number of pizza
3031 // slices, and "stacks" like a number of stacked rings
3032 // Height and radius are both 1.0, but they can easily be changed with par_shapes_scale
3033 par_shapes_mesh *cylinder = par_shapes_create_cylinder(slices, 8);
3034 par_shapes_scale(cylinder, radius, radius, height);
3035 par_shapes_rotate(cylinder, -PI/2.0f, (float[]){ 1, 0, 0 });
3036
3037 // Generate an orientable disk shape (top cap)
3038 par_shapes_mesh *capTop = par_shapes_create_disk(radius, slices, (float[]){ 0, 0, 0 }, (float[]){ 0, 0, 1 });
3039 capTop->tcoords = PAR_MALLOC(float, 2*capTop->npoints);
3040 for (int i = 0; i < 2*capTop->npoints; i++) capTop->tcoords[i] = 0.0f;
3041 par_shapes_rotate(capTop, -PI/2.0f, (float[]){ 1, 0, 0 });
3042 par_shapes_rotate(capTop, 90*DEG2RAD, (float[]){ 0, 1, 0 });
3043 par_shapes_translate(capTop, 0, height, 0);
3044
3045 // Generate an orientable disk shape (bottom cap)
3046 par_shapes_mesh *capBottom = par_shapes_create_disk(radius, slices, (float[]){ 0, 0, 0 }, (float[]){ 0, 0, -1 });
3047 capBottom->tcoords = PAR_MALLOC(float, 2*capBottom->npoints);
3048 for (int i = 0; i < 2*capBottom->npoints; i++) capBottom->tcoords[i] = 0.95f;
3049 par_shapes_rotate(capBottom, PI/2.0f, (float[]){ 1, 0, 0 });
3050 par_shapes_rotate(capBottom, -90*DEG2RAD, (float[]){ 0, 1, 0 });
3051
3052 par_shapes_merge_and_free(cylinder, capTop);
3053 par_shapes_merge_and_free(cylinder, capBottom);
3054
3055 mesh.vertices = (float *)RL_MALLOC(cylinder->ntriangles*3*3*sizeof(float));
3056 mesh.texcoords = (float *)RL_MALLOC(cylinder->ntriangles*3*2*sizeof(float));
3057 mesh.normals = (float *)RL_MALLOC(cylinder->ntriangles*3*3*sizeof(float));
3058
3059 mesh.vertexCount = cylinder->ntriangles*3;
3060 mesh.triangleCount = cylinder->ntriangles;
3061
3062 for (int k = 0; k < mesh.vertexCount; k++)
3063 {
3064 mesh.vertices[k*3] = cylinder->points[cylinder->triangles[k]*3];
3065 mesh.vertices[k*3 + 1] = cylinder->points[cylinder->triangles[k]*3 + 1];
3066 mesh.vertices[k*3 + 2] = cylinder->points[cylinder->triangles[k]*3 + 2];
3067
3068 mesh.normals[k*3] = cylinder->normals[cylinder->triangles[k]*3];
3069 mesh.normals[k*3 + 1] = cylinder->normals[cylinder->triangles[k]*3 + 1];
3070 mesh.normals[k*3 + 2] = cylinder->normals[cylinder->triangles[k]*3 + 2];
3071
3072 mesh.texcoords[k*2] = cylinder->tcoords[cylinder->triangles[k]*2];
3073 mesh.texcoords[k*2 + 1] = cylinder->tcoords[cylinder->triangles[k]*2 + 1];
3074 }
3075
3076 par_shapes_free_mesh(cylinder);
3077
3078 // Upload vertex data to GPU (static mesh)
3079 UploadMesh(&mesh, false);
3080 }
3081 else TRACELOG(LOG_WARNING, "MESH: Failed to generate mesh: cylinder");
3082
3083 return mesh;
3084 }
3085
3086 // Generate cone/pyramid mesh
3087 Mesh GenMeshCone(float radius, float height, int slices)
3088 {
3089 Mesh mesh = { 0 };
3090
3091 if (slices >= 3)
3092 {
3093 // Instance a cone that sits on the Z=0 plane using the given tessellation
3094 // levels across the UV domain. Think of "slices" like a number of pizza
3095 // slices, and "stacks" like a number of stacked rings
3096 // Height and radius are both 1.0, but they can easily be changed with par_shapes_scale
3097 par_shapes_mesh *cone = par_shapes_create_cone(slices, 8);
3098 par_shapes_scale(cone, radius, radius, height);
3099 par_shapes_rotate(cone, -PI/2.0f, (float[]){ 1, 0, 0 });
3100 par_shapes_rotate(cone, PI/2.0f, (float[]){ 0, 1, 0 });
3101
3102 // Generate an orientable disk shape (bottom cap)
3103 par_shapes_mesh *capBottom = par_shapes_create_disk(radius, slices, (float[]){ 0, 0, 0 }, (float[]){ 0, 0, -1 });
3104 capBottom->tcoords = PAR_MALLOC(float, 2*capBottom->npoints);
3105 for (int i = 0; i < 2*capBottom->npoints; i++) capBottom->tcoords[i] = 0.95f;
3106 par_shapes_rotate(capBottom, PI/2.0f, (float[]){ 1, 0, 0 });
3107
3108 par_shapes_merge_and_free(cone, capBottom);
3109
3110 mesh.vertices = (float *)RL_MALLOC(cone->ntriangles*3*3*sizeof(float));
3111 mesh.texcoords = (float *)RL_MALLOC(cone->ntriangles*3*2*sizeof(float));
3112 mesh.normals = (float *)RL_MALLOC(cone->ntriangles*3*3*sizeof(float));
3113
3114 mesh.vertexCount = cone->ntriangles*3;
3115 mesh.triangleCount = cone->ntriangles;
3116
3117 for (int k = 0; k < mesh.vertexCount; k++)
3118 {
3119 mesh.vertices[k*3] = cone->points[cone->triangles[k]*3];
3120 mesh.vertices[k*3 + 1] = cone->points[cone->triangles[k]*3 + 1];
3121 mesh.vertices[k*3 + 2] = cone->points[cone->triangles[k]*3 + 2];
3122
3123 mesh.normals[k*3] = cone->normals[cone->triangles[k]*3];
3124 mesh.normals[k*3 + 1] = cone->normals[cone->triangles[k]*3 + 1];
3125 mesh.normals[k*3 + 2] = cone->normals[cone->triangles[k]*3 + 2];
3126
3127 mesh.texcoords[k*2] = cone->tcoords[cone->triangles[k]*2];
3128 mesh.texcoords[k*2 + 1] = cone->tcoords[cone->triangles[k]*2 + 1];
3129 }
3130
3131 par_shapes_free_mesh(cone);
3132
3133 // Upload vertex data to GPU (static mesh)
3134 UploadMesh(&mesh, false);
3135 }
3136 else TRACELOG(LOG_WARNING, "MESH: Failed to generate mesh: cone");
3137
3138 return mesh;
3139 }
3140
3141 // Generate torus mesh
3142 Mesh GenMeshTorus(float radius, float size, int radSeg, int sides)
3143 {
3144 Mesh mesh = { 0 };
3145
3146 if ((sides >= 3) && (radSeg >= 3))
3147 {
3148 if (radius > 1.0f) radius = 1.0f;
3149 else if (radius < 0.1f) radius = 0.1f;
3150
3151 // Create a donut that sits on the Z=0 plane with the specified inner radius
3152 // The outer radius can be controlled with par_shapes_scale
3153 par_shapes_mesh *torus = par_shapes_create_torus(radSeg, sides, radius);
3154 par_shapes_scale(torus, size/2, size/2, size/2);
3155
3156 mesh.vertices = (float *)RL_MALLOC(torus->ntriangles*3*3*sizeof(float));
3157 mesh.texcoords = (float *)RL_MALLOC(torus->ntriangles*3*2*sizeof(float));
3158 mesh.normals = (float *)RL_MALLOC(torus->ntriangles*3*3*sizeof(float));
3159
3160 mesh.vertexCount = torus->ntriangles*3;
3161 mesh.triangleCount = torus->ntriangles;
3162
3163 for (int k = 0; k < mesh.vertexCount; k++)
3164 {
3165 mesh.vertices[k*3] = torus->points[torus->triangles[k]*3];
3166 mesh.vertices[k*3 + 1] = torus->points[torus->triangles[k]*3 + 1];
3167 mesh.vertices[k*3 + 2] = torus->points[torus->triangles[k]*3 + 2];
3168
3169 mesh.normals[k*3] = torus->normals[torus->triangles[k]*3];
3170 mesh.normals[k*3 + 1] = torus->normals[torus->triangles[k]*3 + 1];
3171 mesh.normals[k*3 + 2] = torus->normals[torus->triangles[k]*3 + 2];
3172
3173 mesh.texcoords[k*2] = torus->tcoords[torus->triangles[k]*2];
3174 mesh.texcoords[k*2 + 1] = torus->tcoords[torus->triangles[k]*2 + 1];
3175 }
3176
3177 par_shapes_free_mesh(torus);
3178
3179 // Upload vertex data to GPU (static mesh)
3180 UploadMesh(&mesh, false);
3181 }
3182 else TRACELOG(LOG_WARNING, "MESH: Failed to generate mesh: torus");
3183
3184 return mesh;
3185 }
3186
3187 // Generate trefoil knot mesh
3188 Mesh GenMeshKnot(float radius, float size, int radSeg, int sides)
3189 {
3190 Mesh mesh = { 0 };
3191
3192 if ((sides >= 3) && (radSeg >= 3))
3193 {
3194 if (radius > 3.0f) radius = 3.0f;
3195 else if (radius < 0.5f) radius = 0.5f;
3196
3197 par_shapes_mesh *knot = par_shapes_create_trefoil_knot(radSeg, sides, radius);
3198 par_shapes_scale(knot, size, size, size);
3199
3200 mesh.vertices = (float *)RL_MALLOC(knot->ntriangles*3*3*sizeof(float));
3201 mesh.texcoords = (float *)RL_MALLOC(knot->ntriangles*3*2*sizeof(float));
3202 mesh.normals = (float *)RL_MALLOC(knot->ntriangles*3*3*sizeof(float));
3203
3204 mesh.vertexCount = knot->ntriangles*3;
3205 mesh.triangleCount = knot->ntriangles;
3206
3207 for (int k = 0; k < mesh.vertexCount; k++)
3208 {
3209 mesh.vertices[k*3] = knot->points[knot->triangles[k]*3];
3210 mesh.vertices[k*3 + 1] = knot->points[knot->triangles[k]*3 + 1];
3211 mesh.vertices[k*3 + 2] = knot->points[knot->triangles[k]*3 + 2];
3212
3213 mesh.normals[k*3] = knot->normals[knot->triangles[k]*3];
3214 mesh.normals[k*3 + 1] = knot->normals[knot->triangles[k]*3 + 1];
3215 mesh.normals[k*3 + 2] = knot->normals[knot->triangles[k]*3 + 2];
3216
3217 mesh.texcoords[k*2] = knot->tcoords[knot->triangles[k]*2];
3218 mesh.texcoords[k*2 + 1] = knot->tcoords[knot->triangles[k]*2 + 1];
3219 }
3220
3221 par_shapes_free_mesh(knot);
3222
3223 // Upload vertex data to GPU (static mesh)
3224 UploadMesh(&mesh, false);
3225 }
3226 else TRACELOG(LOG_WARNING, "MESH: Failed to generate mesh: knot");
3227
3228 return mesh;
3229 }
3230
3231 // Generate a mesh from heightmap
3232 // NOTE: Vertex data is uploaded to GPU
3233 Mesh GenMeshHeightmap(Image heightmap, Vector3 size)
3234 {
3235 #define GRAY_VALUE(c) ((float)(c.r + c.g + c.b)/3.0f)
3236
3237 Mesh mesh = { 0 };
3238
3239 int mapX = heightmap.width;
3240 int mapZ = heightmap.height;
3241
3242 Color *pixels = LoadImageColors(heightmap);
3243
3244 // NOTE: One vertex per pixel
3245 mesh.triangleCount = (mapX - 1)*(mapZ - 1)*2; // One quad every four pixels
3246
3247 mesh.vertexCount = mesh.triangleCount*3;
3248
3249 mesh.vertices = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float));
3250 mesh.normals = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float));
3251 mesh.texcoords = (float *)RL_MALLOC(mesh.vertexCount*2*sizeof(float));
3252 mesh.colors = NULL;
3253
3254 int vCounter = 0; // Used to count vertices float by float
3255 int tcCounter = 0; // Used to count texcoords float by float
3256 int nCounter = 0; // Used to count normals float by float
3257
3258 Vector3 scaleFactor = { size.x/(mapX - 1), size.y/255.0f, size.z/(mapZ - 1) };
3259
3260 Vector3 vA = { 0 };
3261 Vector3 vB = { 0 };
3262 Vector3 vC = { 0 };
3263 Vector3 vN = { 0 };
3264
3265 for (int z = 0; z < mapZ-1; z++)
3266 {
3267 for (int x = 0; x < mapX-1; x++)
3268 {
3269 // Fill vertices array with data
3270 //----------------------------------------------------------
3271
3272 // one triangle - 3 vertex
3273 mesh.vertices[vCounter] = (float)x*scaleFactor.x;
3274 mesh.vertices[vCounter + 1] = GRAY_VALUE(pixels[x + z*mapX])*scaleFactor.y;
3275 mesh.vertices[vCounter + 2] = (float)z*scaleFactor.z;
3276
3277 mesh.vertices[vCounter + 3] = (float)x*scaleFactor.x;
3278 mesh.vertices[vCounter + 4] = GRAY_VALUE(pixels[x + (z + 1)*mapX])*scaleFactor.y;
3279 mesh.vertices[vCounter + 5] = (float)(z + 1)*scaleFactor.z;
3280
3281 mesh.vertices[vCounter + 6] = (float)(x + 1)*scaleFactor.x;
3282 mesh.vertices[vCounter + 7] = GRAY_VALUE(pixels[(x + 1) + z*mapX])*scaleFactor.y;
3283 mesh.vertices[vCounter + 8] = (float)z*scaleFactor.z;
3284
3285 // Another triangle - 3 vertex
3286 mesh.vertices[vCounter + 9] = mesh.vertices[vCounter + 6];
3287 mesh.vertices[vCounter + 10] = mesh.vertices[vCounter + 7];
3288 mesh.vertices[vCounter + 11] = mesh.vertices[vCounter + 8];
3289
3290 mesh.vertices[vCounter + 12] = mesh.vertices[vCounter + 3];
3291 mesh.vertices[vCounter + 13] = mesh.vertices[vCounter + 4];
3292 mesh.vertices[vCounter + 14] = mesh.vertices[vCounter + 5];
3293
3294 mesh.vertices[vCounter + 15] = (float)(x + 1)*scaleFactor.x;
3295 mesh.vertices[vCounter + 16] = GRAY_VALUE(pixels[(x + 1) + (z + 1)*mapX])*scaleFactor.y;
3296 mesh.vertices[vCounter + 17] = (float)(z + 1)*scaleFactor.z;
3297 vCounter += 18; // 6 vertex, 18 floats
3298
3299 // Fill texcoords array with data
3300 //--------------------------------------------------------------
3301 mesh.texcoords[tcCounter] = (float)x/(mapX - 1);
3302 mesh.texcoords[tcCounter + 1] = (float)z/(mapZ - 1);
3303
3304 mesh.texcoords[tcCounter + 2] = (float)x/(mapX - 1);
3305 mesh.texcoords[tcCounter + 3] = (float)(z + 1)/(mapZ - 1);
3306
3307 mesh.texcoords[tcCounter + 4] = (float)(x + 1)/(mapX - 1);
3308 mesh.texcoords[tcCounter + 5] = (float)z/(mapZ - 1);
3309
3310 mesh.texcoords[tcCounter + 6] = mesh.texcoords[tcCounter + 4];
3311 mesh.texcoords[tcCounter + 7] = mesh.texcoords[tcCounter + 5];
3312
3313 mesh.texcoords[tcCounter + 8] = mesh.texcoords[tcCounter + 2];
3314 mesh.texcoords[tcCounter + 9] = mesh.texcoords[tcCounter + 3];
3315
3316 mesh.texcoords[tcCounter + 10] = (float)(x + 1)/(mapX - 1);
3317 mesh.texcoords[tcCounter + 11] = (float)(z + 1)/(mapZ - 1);
3318 tcCounter += 12; // 6 texcoords, 12 floats
3319
3320 // Fill normals array with data
3321 //--------------------------------------------------------------
3322 for (int i = 0; i < 18; i += 9)
3323 {
3324 vA.x = mesh.vertices[nCounter + i];
3325 vA.y = mesh.vertices[nCounter + i + 1];
3326 vA.z = mesh.vertices[nCounter + i + 2];
3327
3328 vB.x = mesh.vertices[nCounter + i + 3];
3329 vB.y = mesh.vertices[nCounter + i + 4];
3330 vB.z = mesh.vertices[nCounter + i + 5];
3331
3332 vC.x = mesh.vertices[nCounter + i + 6];
3333 vC.y = mesh.vertices[nCounter + i + 7];
3334 vC.z = mesh.vertices[nCounter + i + 8];
3335
3336 vN = Vector3Normalize(Vector3CrossProduct(Vector3Subtract(vB, vA), Vector3Subtract(vC, vA)));
3337
3338 mesh.normals[nCounter + i] = vN.x;
3339 mesh.normals[nCounter + i + 1] = vN.y;
3340 mesh.normals[nCounter + i + 2] = vN.z;
3341
3342 mesh.normals[nCounter + i + 3] = vN.x;
3343 mesh.normals[nCounter + i + 4] = vN.y;
3344 mesh.normals[nCounter + i + 5] = vN.z;
3345
3346 mesh.normals[nCounter + i + 6] = vN.x;
3347 mesh.normals[nCounter + i + 7] = vN.y;
3348 mesh.normals[nCounter + i + 8] = vN.z;
3349 }
3350
3351 nCounter += 18; // 6 vertex, 18 floats
3352 }
3353 }
3354
3355 UnloadImageColors(pixels); // Unload pixels color data
3356
3357 // Upload vertex data to GPU (static mesh)
3358 UploadMesh(&mesh, false);
3359
3360 return mesh;
3361 }
3362
3363 // Generate a cubes mesh from pixel data
3364 // NOTE: Vertex data is uploaded to GPU
3365 Mesh GenMeshCubicmap(Image cubicmap, Vector3 cubeSize)
3366 {
3367 #define COLOR_EQUAL(col1, col2) ((col1.r == col2.r)&&(col1.g == col2.g)&&(col1.b == col2.b)&&(col1.a == col2.a))
3368
3369 Mesh mesh = { 0 };
3370
3371 Color *pixels = LoadImageColors(cubicmap);
3372
3373 // NOTE: Max possible number of triangles numCubes*(12 triangles by cube)
3374 int maxTriangles = cubicmap.width*cubicmap.height*12;
3375
3376 int vCounter = 0; // Used to count vertices
3377 int tcCounter = 0; // Used to count texcoords
3378 int nCounter = 0; // Used to count normals
3379
3380 float w = cubeSize.x;
3381 float h = cubeSize.z;
3382 float h2 = cubeSize.y;
3383
3384 Vector3 *mapVertices = (Vector3 *)RL_MALLOC(maxTriangles*3*sizeof(Vector3));
3385 Vector2 *mapTexcoords = (Vector2 *)RL_MALLOC(maxTriangles*3*sizeof(Vector2));
3386 Vector3 *mapNormals = (Vector3 *)RL_MALLOC(maxTriangles*3*sizeof(Vector3));
3387
3388 // Define the 6 normals of the cube, combined accordingly later
3389 Vector3 n1 = { 1.0f, 0.0f, 0.0f };
3390 Vector3 n2 = { -1.0f, 0.0f, 0.0f };
3391 Vector3 n3 = { 0.0f, 1.0f, 0.0f };
3392 Vector3 n4 = { 0.0f, -1.0f, 0.0f };
3393 Vector3 n5 = { 0.0f, 0.0f, -1.0f };
3394 Vector3 n6 = { 0.0f, 0.0f, 1.0f };
3395
3396 // NOTE: Using texture rectangles to define different
3397 // textures for top-bottom-front-back-right-left (6)
3398 typedef struct RectangleF {
3399 float x;
3400 float y;
3401 float width;
3402 float height;
3403 } RectangleF;
3404
3405 RectangleF rightTexUV = { 0.0f, 0.0f, 0.5f, 0.5f };
3406 RectangleF leftTexUV = { 0.5f, 0.0f, 0.5f, 0.5f };
3407 RectangleF frontTexUV = { 0.0f, 0.0f, 0.5f, 0.5f };
3408 RectangleF backTexUV = { 0.5f, 0.0f, 0.5f, 0.5f };
3409 RectangleF topTexUV = { 0.0f, 0.5f, 0.5f, 0.5f };
3410 RectangleF bottomTexUV = { 0.5f, 0.5f, 0.5f, 0.5f };
3411
3412 for (int z = 0; z < cubicmap.height; ++z)
3413 {
3414 for (int x = 0; x < cubicmap.width; x++)
3415 {
3416 // Define the 8 vertex of the cube, to be combined accordingly later
3417 Vector3 v1 = { w*(x - 0.5f), h2, h*(z - 0.5f) };
3418 Vector3 v2 = { w*(x - 0.5f), h2, h*(z + 0.5f) };
3419 Vector3 v3 = { w*(x + 0.5f), h2, h*(z + 0.5f) };
3420 Vector3 v4 = { w*(x + 0.5f), h2, h*(z - 0.5f) };
3421 Vector3 v5 = { w*(x + 0.5f), 0, h*(z - 0.5f) };
3422 Vector3 v6 = { w*(x - 0.5f), 0, h*(z - 0.5f) };
3423 Vector3 v7 = { w*(x - 0.5f), 0, h*(z + 0.5f) };
3424 Vector3 v8 = { w*(x + 0.5f), 0, h*(z + 0.5f) };
3425
3426 // Check pixel color to be WHITE -> draw full cube
3427 if (COLOR_EQUAL(pixels[z*cubicmap.width + x], WHITE))
3428 {
3429 // Define triangles and checking collateral cubes
3430 //------------------------------------------------
3431
3432 // Define top triangles (2 tris, 6 vertex --> v1-v2-v3, v1-v3-v4)
3433 // WARNING: Not required for a WHITE cubes, created to allow seeing the map from outside
3434 mapVertices[vCounter] = v1;
3435 mapVertices[vCounter + 1] = v2;
3436 mapVertices[vCounter + 2] = v3;
3437 mapVertices[vCounter + 3] = v1;
3438 mapVertices[vCounter + 4] = v3;
3439 mapVertices[vCounter + 5] = v4;
3440 vCounter += 6;
3441
3442 mapNormals[nCounter] = n3;
3443 mapNormals[nCounter + 1] = n3;
3444 mapNormals[nCounter + 2] = n3;
3445 mapNormals[nCounter + 3] = n3;
3446 mapNormals[nCounter + 4] = n3;
3447 mapNormals[nCounter + 5] = n3;
3448 nCounter += 6;
3449
3450 mapTexcoords[tcCounter] = (Vector2){ topTexUV.x, topTexUV.y };
3451 mapTexcoords[tcCounter + 1] = (Vector2){ topTexUV.x, topTexUV.y + topTexUV.height };
3452 mapTexcoords[tcCounter + 2] = (Vector2){ topTexUV.x + topTexUV.width, topTexUV.y + topTexUV.height };
3453 mapTexcoords[tcCounter + 3] = (Vector2){ topTexUV.x, topTexUV.y };
3454 mapTexcoords[tcCounter + 4] = (Vector2){ topTexUV.x + topTexUV.width, topTexUV.y + topTexUV.height };
3455 mapTexcoords[tcCounter + 5] = (Vector2){ topTexUV.x + topTexUV.width, topTexUV.y };
3456 tcCounter += 6;
3457
3458 // Define bottom triangles (2 tris, 6 vertex --> v6-v8-v7, v6-v5-v8)
3459 mapVertices[vCounter] = v6;
3460 mapVertices[vCounter + 1] = v8;
3461 mapVertices[vCounter + 2] = v7;
3462 mapVertices[vCounter + 3] = v6;
3463 mapVertices[vCounter + 4] = v5;
3464 mapVertices[vCounter + 5] = v8;
3465 vCounter += 6;
3466
3467 mapNormals[nCounter] = n4;
3468 mapNormals[nCounter + 1] = n4;
3469 mapNormals[nCounter + 2] = n4;
3470 mapNormals[nCounter + 3] = n4;
3471 mapNormals[nCounter + 4] = n4;
3472 mapNormals[nCounter + 5] = n4;
3473 nCounter += 6;
3474
3475 mapTexcoords[tcCounter] = (Vector2){ bottomTexUV.x + bottomTexUV.width, bottomTexUV.y };
3476 mapTexcoords[tcCounter + 1] = (Vector2){ bottomTexUV.x, bottomTexUV.y + bottomTexUV.height };
3477 mapTexcoords[tcCounter + 2] = (Vector2){ bottomTexUV.x + bottomTexUV.width, bottomTexUV.y + bottomTexUV.height };
3478 mapTexcoords[tcCounter + 3] = (Vector2){ bottomTexUV.x + bottomTexUV.width, bottomTexUV.y };
3479 mapTexcoords[tcCounter + 4] = (Vector2){ bottomTexUV.x, bottomTexUV.y };
3480 mapTexcoords[tcCounter + 5] = (Vector2){ bottomTexUV.x, bottomTexUV.y + bottomTexUV.height };
3481 tcCounter += 6;
3482
3483 // Checking cube on bottom of current cube
3484 if (((z < cubicmap.height - 1) && COLOR_EQUAL(pixels[(z + 1)*cubicmap.width + x], BLACK)) || (z == cubicmap.height - 1))
3485 {
3486 // Define front triangles (2 tris, 6 vertex) --> v2 v7 v3, v3 v7 v8
3487 // NOTE: Collateral occluded faces are not generated
3488 mapVertices[vCounter] = v2;
3489 mapVertices[vCounter + 1] = v7;
3490 mapVertices[vCounter + 2] = v3;
3491 mapVertices[vCounter + 3] = v3;
3492 mapVertices[vCounter + 4] = v7;
3493 mapVertices[vCounter + 5] = v8;
3494 vCounter += 6;
3495
3496 mapNormals[nCounter] = n6;
3497 mapNormals[nCounter + 1] = n6;
3498 mapNormals[nCounter + 2] = n6;
3499 mapNormals[nCounter + 3] = n6;
3500 mapNormals[nCounter + 4] = n6;
3501 mapNormals[nCounter + 5] = n6;
3502 nCounter += 6;
3503
3504 mapTexcoords[tcCounter] = (Vector2){ frontTexUV.x, frontTexUV.y };
3505 mapTexcoords[tcCounter + 1] = (Vector2){ frontTexUV.x, frontTexUV.y + frontTexUV.height };
3506 mapTexcoords[tcCounter + 2] = (Vector2){ frontTexUV.x + frontTexUV.width, frontTexUV.y };
3507 mapTexcoords[tcCounter + 3] = (Vector2){ frontTexUV.x + frontTexUV.width, frontTexUV.y };
3508 mapTexcoords[tcCounter + 4] = (Vector2){ frontTexUV.x, frontTexUV.y + frontTexUV.height };
3509 mapTexcoords[tcCounter + 5] = (Vector2){ frontTexUV.x + frontTexUV.width, frontTexUV.y + frontTexUV.height };
3510 tcCounter += 6;
3511 }
3512
3513 // Checking cube on top of current cube
3514 if (((z > 0) && COLOR_EQUAL(pixels[(z - 1)*cubicmap.width + x], BLACK)) || (z == 0))
3515 {
3516 // Define back triangles (2 tris, 6 vertex) --> v1 v5 v6, v1 v4 v5
3517 // NOTE: Collateral occluded faces are not generated
3518 mapVertices[vCounter] = v1;
3519 mapVertices[vCounter + 1] = v5;
3520 mapVertices[vCounter + 2] = v6;
3521 mapVertices[vCounter + 3] = v1;
3522 mapVertices[vCounter + 4] = v4;
3523 mapVertices[vCounter + 5] = v5;
3524 vCounter += 6;
3525
3526 mapNormals[nCounter] = n5;
3527 mapNormals[nCounter + 1] = n5;
3528 mapNormals[nCounter + 2] = n5;
3529 mapNormals[nCounter + 3] = n5;
3530 mapNormals[nCounter + 4] = n5;
3531 mapNormals[nCounter + 5] = n5;
3532 nCounter += 6;
3533
3534 mapTexcoords[tcCounter] = (Vector2){ backTexUV.x + backTexUV.width, backTexUV.y };
3535 mapTexcoords[tcCounter + 1] = (Vector2){ backTexUV.x, backTexUV.y + backTexUV.height };
3536 mapTexcoords[tcCounter + 2] = (Vector2){ backTexUV.x + backTexUV.width, backTexUV.y + backTexUV.height };
3537 mapTexcoords[tcCounter + 3] = (Vector2){ backTexUV.x + backTexUV.width, backTexUV.y };
3538 mapTexcoords[tcCounter + 4] = (Vector2){ backTexUV.x, backTexUV.y };
3539 mapTexcoords[tcCounter + 5] = (Vector2){ backTexUV.x, backTexUV.y + backTexUV.height };
3540 tcCounter += 6;
3541 }
3542
3543 // Checking cube on right of current cube
3544 if (((x < cubicmap.width - 1) && COLOR_EQUAL(pixels[z*cubicmap.width + (x + 1)], BLACK)) || (x == cubicmap.width - 1))
3545 {
3546 // Define right triangles (2 tris, 6 vertex) --> v3 v8 v4, v4 v8 v5
3547 // NOTE: Collateral occluded faces are not generated
3548 mapVertices[vCounter] = v3;
3549 mapVertices[vCounter + 1] = v8;
3550 mapVertices[vCounter + 2] = v4;
3551 mapVertices[vCounter + 3] = v4;
3552 mapVertices[vCounter + 4] = v8;
3553 mapVertices[vCounter + 5] = v5;
3554 vCounter += 6;
3555
3556 mapNormals[nCounter] = n1;
3557 mapNormals[nCounter + 1] = n1;
3558 mapNormals[nCounter + 2] = n1;
3559 mapNormals[nCounter + 3] = n1;
3560 mapNormals[nCounter + 4] = n1;
3561 mapNormals[nCounter + 5] = n1;
3562 nCounter += 6;
3563
3564 mapTexcoords[tcCounter] = (Vector2){ rightTexUV.x, rightTexUV.y };
3565 mapTexcoords[tcCounter + 1] = (Vector2){ rightTexUV.x, rightTexUV.y + rightTexUV.height };
3566 mapTexcoords[tcCounter + 2] = (Vector2){ rightTexUV.x + rightTexUV.width, rightTexUV.y };
3567 mapTexcoords[tcCounter + 3] = (Vector2){ rightTexUV.x + rightTexUV.width, rightTexUV.y };
3568 mapTexcoords[tcCounter + 4] = (Vector2){ rightTexUV.x, rightTexUV.y + rightTexUV.height };
3569 mapTexcoords[tcCounter + 5] = (Vector2){ rightTexUV.x + rightTexUV.width, rightTexUV.y + rightTexUV.height };
3570 tcCounter += 6;
3571 }
3572
3573 // Checking cube on left of current cube
3574 if (((x > 0) && COLOR_EQUAL(pixels[z*cubicmap.width + (x - 1)], BLACK)) || (x == 0))
3575 {
3576 // Define left triangles (2 tris, 6 vertex) --> v1 v7 v2, v1 v6 v7
3577 // NOTE: Collateral occluded faces are not generated
3578 mapVertices[vCounter] = v1;
3579 mapVertices[vCounter + 1] = v7;
3580 mapVertices[vCounter + 2] = v2;
3581 mapVertices[vCounter + 3] = v1;
3582 mapVertices[vCounter + 4] = v6;
3583 mapVertices[vCounter + 5] = v7;
3584 vCounter += 6;
3585
3586 mapNormals[nCounter] = n2;
3587 mapNormals[nCounter + 1] = n2;
3588 mapNormals[nCounter + 2] = n2;
3589 mapNormals[nCounter + 3] = n2;
3590 mapNormals[nCounter + 4] = n2;
3591 mapNormals[nCounter + 5] = n2;
3592 nCounter += 6;
3593
3594 mapTexcoords[tcCounter] = (Vector2){ leftTexUV.x, leftTexUV.y };
3595 mapTexcoords[tcCounter + 1] = (Vector2){ leftTexUV.x + leftTexUV.width, leftTexUV.y + leftTexUV.height };
3596 mapTexcoords[tcCounter + 2] = (Vector2){ leftTexUV.x + leftTexUV.width, leftTexUV.y };
3597 mapTexcoords[tcCounter + 3] = (Vector2){ leftTexUV.x, leftTexUV.y };
3598 mapTexcoords[tcCounter + 4] = (Vector2){ leftTexUV.x, leftTexUV.y + leftTexUV.height };
3599 mapTexcoords[tcCounter + 5] = (Vector2){ leftTexUV.x + leftTexUV.width, leftTexUV.y + leftTexUV.height };
3600 tcCounter += 6;
3601 }
3602 }
3603 // Check pixel color to be BLACK, in that case only drawing floor and roof
3604 else if (COLOR_EQUAL(pixels[z*cubicmap.width + x], BLACK))
3605 {
3606 // Define top triangles (2 tris, 6 vertex --> v1-v2-v3, v1-v3-v4)
3607 mapVertices[vCounter] = v1;
3608 mapVertices[vCounter + 1] = v3;
3609 mapVertices[vCounter + 2] = v2;
3610 mapVertices[vCounter + 3] = v1;
3611 mapVertices[vCounter + 4] = v4;
3612 mapVertices[vCounter + 5] = v3;
3613 vCounter += 6;
3614
3615 mapNormals[nCounter] = n4;
3616 mapNormals[nCounter + 1] = n4;
3617 mapNormals[nCounter + 2] = n4;
3618 mapNormals[nCounter + 3] = n4;
3619 mapNormals[nCounter + 4] = n4;
3620 mapNormals[nCounter + 5] = n4;
3621 nCounter += 6;
3622
3623 mapTexcoords[tcCounter] = (Vector2){ topTexUV.x, topTexUV.y };
3624 mapTexcoords[tcCounter + 1] = (Vector2){ topTexUV.x + topTexUV.width, topTexUV.y + topTexUV.height };
3625 mapTexcoords[tcCounter + 2] = (Vector2){ topTexUV.x, topTexUV.y + topTexUV.height };
3626 mapTexcoords[tcCounter + 3] = (Vector2){ topTexUV.x, topTexUV.y };
3627 mapTexcoords[tcCounter + 4] = (Vector2){ topTexUV.x + topTexUV.width, topTexUV.y };
3628 mapTexcoords[tcCounter + 5] = (Vector2){ topTexUV.x + topTexUV.width, topTexUV.y + topTexUV.height };
3629 tcCounter += 6;
3630
3631 // Define bottom triangles (2 tris, 6 vertex --> v6-v8-v7, v6-v5-v8)
3632 mapVertices[vCounter] = v6;
3633 mapVertices[vCounter + 1] = v7;
3634 mapVertices[vCounter + 2] = v8;
3635 mapVertices[vCounter + 3] = v6;
3636 mapVertices[vCounter + 4] = v8;
3637 mapVertices[vCounter + 5] = v5;
3638 vCounter += 6;
3639
3640 mapNormals[nCounter] = n3;
3641 mapNormals[nCounter + 1] = n3;
3642 mapNormals[nCounter + 2] = n3;
3643 mapNormals[nCounter + 3] = n3;
3644 mapNormals[nCounter + 4] = n3;
3645 mapNormals[nCounter + 5] = n3;
3646 nCounter += 6;
3647
3648 mapTexcoords[tcCounter] = (Vector2){ bottomTexUV.x + bottomTexUV.width, bottomTexUV.y };
3649 mapTexcoords[tcCounter + 1] = (Vector2){ bottomTexUV.x + bottomTexUV.width, bottomTexUV.y + bottomTexUV.height };
3650 mapTexcoords[tcCounter + 2] = (Vector2){ bottomTexUV.x, bottomTexUV.y + bottomTexUV.height };
3651 mapTexcoords[tcCounter + 3] = (Vector2){ bottomTexUV.x + bottomTexUV.width, bottomTexUV.y };
3652 mapTexcoords[tcCounter + 4] = (Vector2){ bottomTexUV.x, bottomTexUV.y + bottomTexUV.height };
3653 mapTexcoords[tcCounter + 5] = (Vector2){ bottomTexUV.x, bottomTexUV.y };
3654 tcCounter += 6;
3655 }
3656 }
3657 }
3658
3659 // Move data from mapVertices temp arrays to vertices float array
3660 mesh.vertexCount = vCounter;
3661 mesh.triangleCount = vCounter/3;
3662
3663 mesh.vertices = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float));
3664 mesh.normals = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float));
3665 mesh.texcoords = (float *)RL_MALLOC(mesh.vertexCount*2*sizeof(float));
3666 mesh.colors = NULL;
3667
3668 int fCounter = 0;
3669
3670 // Move vertices data
3671 for (int i = 0; i < vCounter; i++)
3672 {
3673 mesh.vertices[fCounter] = mapVertices[i].x;
3674 mesh.vertices[fCounter + 1] = mapVertices[i].y;
3675 mesh.vertices[fCounter + 2] = mapVertices[i].z;
3676 fCounter += 3;
3677 }
3678
3679 fCounter = 0;
3680
3681 // Move normals data
3682 for (int i = 0; i < nCounter; i++)
3683 {
3684 mesh.normals[fCounter] = mapNormals[i].x;
3685 mesh.normals[fCounter + 1] = mapNormals[i].y;
3686 mesh.normals[fCounter + 2] = mapNormals[i].z;
3687 fCounter += 3;
3688 }
3689
3690 fCounter = 0;
3691
3692 // Move texcoords data
3693 for (int i = 0; i < tcCounter; i++)
3694 {
3695 mesh.texcoords[fCounter] = mapTexcoords[i].x;
3696 mesh.texcoords[fCounter + 1] = mapTexcoords[i].y;
3697 fCounter += 2;
3698 }
3699
3700 RL_FREE(mapVertices);
3701 RL_FREE(mapNormals);
3702 RL_FREE(mapTexcoords);
3703
3704 UnloadImageColors(pixels); // Unload pixels color data
3705
3706 // Upload vertex data to GPU (static mesh)
3707 UploadMesh(&mesh, false);
3708
3709 return mesh;
3710 }
3711 #endif // SUPPORT_MESH_GENERATION
3712
3713 // Compute mesh bounding box limits
3714 // NOTE: minVertex and maxVertex should be transformed by model transform matrix
3715 BoundingBox GetMeshBoundingBox(Mesh mesh)
3716 {
3717 // Get min and max vertex to construct bounds (AABB)
3718 Vector3 minVertex = { 0 };
3719 Vector3 maxVertex = { 0 };
3720
3721 if (mesh.vertices != NULL)
3722 {
3723 minVertex = (Vector3){ mesh.vertices[0], mesh.vertices[1], mesh.vertices[2] };
3724 maxVertex = (Vector3){ mesh.vertices[0], mesh.vertices[1], mesh.vertices[2] };
3725
3726 for (int i = 1; i < mesh.vertexCount; i++)
3727 {
3728 minVertex = Vector3Min(minVertex, (Vector3){ mesh.vertices[i*3], mesh.vertices[i*3 + 1], mesh.vertices[i*3 + 2] });
3729 maxVertex = Vector3Max(maxVertex, (Vector3){ mesh.vertices[i*3], mesh.vertices[i*3 + 1], mesh.vertices[i*3 + 2] });
3730 }
3731 }
3732
3733 // Create the bounding box
3734 BoundingBox box = { 0 };
3735 box.min = minVertex;
3736 box.max = maxVertex;
3737
3738 return box;
3739 }
3740
3741 // Compute mesh tangents
3742 void GenMeshTangents(Mesh *mesh)
3743 {
3744 // Check if input mesh data is useful
3745 if ((mesh == NULL) || (mesh->vertices == NULL) || (mesh->texcoords == NULL) || (mesh->normals == NULL))
3746 {
3747 TRACELOG(LOG_WARNING, "MESH: Tangents generation requires vertices, texcoords and normals vertex attribute data");
3748 return;
3749 }
3750
3751 // Allocate or reallocate tangents data
3752 if (mesh->tangents == NULL) mesh->tangents = (float *)RL_MALLOC(mesh->vertexCount*4*sizeof(float));
3753 else
3754 {
3755 RL_FREE(mesh->tangents);
3756 mesh->tangents = (float *)RL_MALLOC(mesh->vertexCount*4*sizeof(float));
3757 }
3758
3759 // Allocate temporary arrays for tangents calculation
3760 Vector3 *tan1 = (Vector3 *)RL_CALLOC(mesh->vertexCount, sizeof(Vector3));
3761 Vector3 *tan2 = (Vector3 *)RL_CALLOC(mesh->vertexCount, sizeof(Vector3));
3762
3763 if (tan1 == NULL || tan2 == NULL)
3764 {
3765 TRACELOG(LOG_WARNING, "MESH: Failed to allocate temporary memory for tangent calculation");
3766 if (tan1) RL_FREE(tan1);
3767 if (tan2) RL_FREE(tan2);
3768 return;
3769 }
3770
3771 // Process all triangles of the mesh
3772 // 'triangleCount' must be always valid
3773 for (int t = 0; t < mesh->triangleCount; t++)
3774 {
3775 // Get triangle vertex indices
3776 int i0 = 0, i1 = 0, i2 = 0;
3777
3778 if (mesh->indices != NULL)
3779 {
3780 // Use indices if available
3781 i0 = mesh->indices[t*3 + 0];
3782 i1 = mesh->indices[t*3 + 1];
3783 i2 = mesh->indices[t*3 + 2];
3784 }
3785 else
3786 {
3787 // Sequential access for non-indexed mesh
3788 i0 = t*3 + 0;
3789 i1 = t*3 + 1;
3790 i2 = t*3 + 2;
3791 }
3792
3793 // Get triangle vertices position
3794 Vector3 v1 = { mesh->vertices[i0*3 + 0], mesh->vertices[i0*3 + 1], mesh->vertices[i0*3 + 2] };
3795 Vector3 v2 = { mesh->vertices[i1*3 + 0], mesh->vertices[i1*3 + 1], mesh->vertices[i1*3 + 2] };
3796 Vector3 v3 = { mesh->vertices[i2*3 + 0], mesh->vertices[i2*3 + 1], mesh->vertices[i2*3 + 2] };
3797
3798 // Get triangle texcoords
3799 Vector2 uv1 = { mesh->texcoords[i0*2 + 0], mesh->texcoords[i0*2 + 1] };
3800 Vector2 uv2 = { mesh->texcoords[i1*2 + 0], mesh->texcoords[i1*2 + 1] };
3801 Vector2 uv3 = { mesh->texcoords[i2*2 + 0], mesh->texcoords[i2*2 + 1] };
3802
3803 // Calculate triangle edges
3804 float x1 = v2.x - v1.x;
3805 float y1 = v2.y - v1.y;
3806 float z1 = v2.z - v1.z;
3807 float x2 = v3.x - v1.x;
3808 float y2 = v3.y - v1.y;
3809 float z2 = v3.z - v1.z;
3810
3811 // Calculate texture coordinate differences
3812 float s1 = uv2.x - uv1.x;
3813 float t1 = uv2.y - uv1.y;
3814 float s2 = uv3.x - uv1.x;
3815 float t2 = uv3.y - uv1.y;
3816
3817 // Calculate denominator and check for degenerate UV
3818 float div = s1*t2 - s2*t1;
3819 float r = (fabsf(div) < 0.0001f)? 0.0f : 1.0f/div;
3820
3821 // Calculate tangent and bitangent directions
3822 Vector3 sdir = { (t2*x1 - t1*x2)*r, (t2*y1 - t1*y2)*r, (t2*z1 - t1*z2)*r };
3823 Vector3 tdir = { (s1*x2 - s2*x1)*r, (s1*y2 - s2*y1)*r, (s1*z2 - s2*z1)*r };
3824
3825 // Accumulate tangents and bitangents for each vertex of the triangle
3826 tan1[i0] = Vector3Add(tan1[i0], sdir);
3827 tan1[i1] = Vector3Add(tan1[i1], sdir);
3828 tan1[i2] = Vector3Add(tan1[i2], sdir);
3829
3830 tan2[i0] = Vector3Add(tan2[i0], tdir);
3831 tan2[i1] = Vector3Add(tan2[i1], tdir);
3832 tan2[i2] = Vector3Add(tan2[i2], tdir);
3833 }
3834
3835 // Calculate final tangents for each vertex
3836 for (int i = 0; i < mesh->vertexCount; i++)
3837 {
3838 Vector3 normal = { mesh->normals[i*3 + 0], mesh->normals[i*3 + 1], mesh->normals[i*3 + 2] };
3839 Vector3 tangent = tan1[i];
3840
3841 // Handle zero tangent (can happen with degenerate UVs)
3842 if (Vector3Length(tangent) < 0.0001f)
3843 {
3844 // Create a tangent perpendicular to the normal
3845 if (fabsf(normal.z) > 0.707f) tangent = (Vector3){ 1.0f, 0.0f, 0.0f };
3846 else tangent = Vector3Normalize((Vector3){ -normal.y, normal.x, 0.0f });
3847
3848 mesh->tangents[i*4 + 0] = tangent.x;
3849 mesh->tangents[i*4 + 1] = tangent.y;
3850 mesh->tangents[i*4 + 2] = tangent.z;
3851 mesh->tangents[i*4 + 3] = 1.0f;
3852 continue;
3853 }
3854
3855 // Gram-Schmidt orthogonalization to make tangent orthogonal to normal
3856 // T_prime = T - N*dot(N, T)
3857 Vector3 orthogonalized = Vector3Subtract(tangent, Vector3Scale(normal, Vector3DotProduct(normal, tangent)));
3858
3859 // Handle cases where orthogonalized vector is too small
3860 if (Vector3Length(orthogonalized) < 0.0001f)
3861 {
3862 // Create a tangent perpendicular to the normal
3863 if (fabsf(normal.z) > 0.707f) orthogonalized = (Vector3){ 1.0f, 0.0f, 0.0f };
3864 else orthogonalized = Vector3Normalize((Vector3){ -normal.y, normal.x, 0.0f });
3865 }
3866 else
3867 {
3868 // Normalize the orthogonalized tangent
3869 orthogonalized = Vector3Normalize(orthogonalized);
3870 }
3871
3872 // Store the calculated tangent
3873 mesh->tangents[i*4 + 0] = orthogonalized.x;
3874 mesh->tangents[i*4 + 1] = orthogonalized.y;
3875 mesh->tangents[i*4 + 2] = orthogonalized.z;
3876
3877 // Calculate the handedness (w component)
3878 mesh->tangents[i*4 + 3] = (Vector3DotProduct(Vector3CrossProduct(normal, orthogonalized), tan2[i]) < 0.0f)? -1.0f : 1.0f;
3879 }
3880
3881 // Free temporary arrays
3882 RL_FREE(tan1);
3883 RL_FREE(tan2);
3884
3885 // Update vertex buffers if available
3886 if (mesh->vboId != NULL)
3887 {
3888 if (mesh->vboId[SHADER_LOC_VERTEX_TANGENT] != 0)
3889 {
3890 // Update existing tangent vertex buffer
3891 rlUpdateVertexBuffer(mesh->vboId[SHADER_LOC_VERTEX_TANGENT], mesh->tangents, mesh->vertexCount*4*sizeof(float), 0);
3892 }
3893 else
3894 {
3895 // Create new tangent vertex buffer
3896 mesh->vboId[SHADER_LOC_VERTEX_TANGENT] = rlLoadVertexBuffer(mesh->tangents, mesh->vertexCount*4*sizeof(float), false);
3897 }
3898
3899 // Set up vertex attributes for shader
3900 rlEnableVertexArray(mesh->vaoId);
3901 rlSetVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT, 4, RL_FLOAT, 0, 0, 0);
3902 rlEnableVertexAttribute(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT);
3903 rlDisableVertexArray();
3904 }
3905
3906 TRACELOG(LOG_INFO, "MESH: Tangents data computed and uploaded for provided mesh");
3907 }
3908
3909 // Draw a model (with texture if set)
3910 void DrawModel(Model model, Vector3 position, float scale, Color tint)
3911 {
3912 Vector3 vScale = { scale, scale, scale };
3913 Vector3 rotationAxis = { 0.0f, 1.0f, 0.0f };
3914
3915 DrawModelEx(model, position, rotationAxis, 0.0f, vScale, tint);
3916 }
3917
3918 // Draw a model with extended parameters
3919 void DrawModelEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint)
3920 {
3921 // Calculate transformation matrix from function parameters
3922 // Get transform matrix (rotation -> scale -> translation)
3923 Matrix matScale = MatrixScale(scale.x, scale.y, scale.z);
3924 Matrix matRotation = MatrixRotate(rotationAxis, rotationAngle*DEG2RAD);
3925 Matrix matTranslation = MatrixTranslate(position.x, position.y, position.z);
3926
3927 Matrix matTransform = MatrixMultiply(MatrixMultiply(matScale, matRotation), matTranslation);
3928
3929 // Combine model transformation matrix (model.transform) with matrix generated by function parameters (matTransform)
3930 model.transform = MatrixMultiply(model.transform, matTransform);
3931
3932 for (int i = 0; i < model.meshCount; i++)
3933 {
3934 Material mat = model.materials[model.meshMaterial[i]];
3935 Color colDiffuse = mat.maps[MATERIAL_MAP_DIFFUSE].color;
3936
3937 // Applying color tint directly to material diffuse map,
3938 // because is comes as an input paramter to the function
3939 Color colTinted = { 0 };
3940 colTinted.r = (unsigned char)(((int)colDiffuse.r*(int)tint.r)/255);
3941 colTinted.g = (unsigned char)(((int)colDiffuse.g*(int)tint.g)/255);
3942 colTinted.b = (unsigned char)(((int)colDiffuse.b*(int)tint.b)/255);
3943 colTinted.a = (unsigned char)(((int)colDiffuse.a*(int)tint.a)/255);
3944
3945 mat.maps[MATERIAL_MAP_DIFFUSE].color = colTinted;
3946
3947 // Upload runtime bone transforms matrices, to compute skinning on the shader (GPU-skinning)
3948 // NOTE: Required location must be found and Mesh bones indices and weights must be also uploaded to shader
3949 if ((mat.shader.locs != NULL) && (mat.shader.locs[SHADER_LOC_MATRIX_BONETRANSFORMS] != -1) && (model.boneMatrices != NULL))
3950 {
3951 rlEnableShader(mat.shader.id); // Enable shader to set bone transform matrices
3952 rlSetUniformMatrices(mat.shader.locs[SHADER_LOC_MATRIX_BONETRANSFORMS], model.boneMatrices, model.skeleton.boneCount);
3953 }
3954
3955 DrawMesh(model.meshes[i], mat, model.transform);
3956
3957 // Restore material diffuse map color (before tint applied)
3958 mat.maps[MATERIAL_MAP_DIFFUSE].color = colDiffuse;
3959 }
3960 }
3961
3962 // Draw a model wires (with texture if set)
3963 void DrawModelWires(Model model, Vector3 position, float scale, Color tint)
3964 {
3965 rlEnableWireMode();
3966
3967 DrawModel(model, position, scale, tint);
3968
3969 rlDisableWireMode();
3970 }
3971
3972 // Draw a model wires (with texture if set) with extended parameters
3973 void DrawModelWiresEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint)
3974 {
3975 rlEnableWireMode();
3976
3977 DrawModelEx(model, position, rotationAxis, rotationAngle, scale, tint);
3978
3979 rlDisableWireMode();
3980 }
3981
3982 // Draw a billboard
3983 void DrawBillboard(Camera camera, Texture2D texture, Vector3 position, float scale, Color tint)
3984 {
3985 Rectangle source = { 0.0f, 0.0f, (float)texture.width, (float)texture.height };
3986
3987 DrawBillboardRec(camera, texture, source, position, (Vector2){ scale*fabsf((float)source.width/source.height), scale }, tint);
3988 }
3989
3990 // Draw a billboard (part of a texture defined by a rectangle)
3991 void DrawBillboardRec(Camera camera, Texture2D texture, Rectangle source, Vector3 position, Vector2 size, Color tint)
3992 {
3993 // NOTE: Billboard locked on axis-Y
3994 Vector3 up = { 0.0f, 1.0f, 0.0f };
3995
3996 DrawBillboardPro(camera, texture, source, position, up, size, Vector2Scale(size, 0.5), 0.0f, tint);
3997 }
3998
3999 // Draw a billboard with additional parameters
4000 void DrawBillboardPro(Camera camera, Texture2D texture, Rectangle source, Vector3 position, Vector3 up, Vector2 size, Vector2 origin, float rotation, Color tint)
4001 {
4002 // Compute the up vector and the right vector
4003 Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up);
4004 Vector3 right = { matView.m0, matView.m4, matView.m8 };
4005 right = Vector3Scale(right, size.x);
4006 up = Vector3Scale(up, size.y);
4007
4008 // Flip the content of the billboard while maintaining the counterclockwise edge rendering order
4009 if (size.x < 0.0f)
4010 {
4011 source.x -= size.x;
4012 source.width *= -1.0;
4013 right = Vector3Negate(right);
4014 origin.x *= -1.0f;
4015 }
4016 if (size.y < 0.0f)
4017 {
4018 source.y -= size.y;
4019 source.height *= -1.0;
4020 up = Vector3Negate(up);
4021 origin.y *= -1.0f;
4022 }
4023
4024 // Draw the texture region described by source on the following rectangle in 3D space:
4025 //
4026 // size.x <--.
4027 // 3 ^---------------------------+ 2 \ rotation
4028 // | | /
4029 // | |
4030 // | origin.x position |
4031 // up |.............. | size.y
4032 // | . |
4033 // | . origin.y |
4034 // | . |
4035 // 0 +---------------------------> 1
4036 // right
4037 Vector3 forward;
4038 if (rotation != 0.0) forward = Vector3CrossProduct(right, up);
4039
4040 Vector3 origin3D = Vector3Add(Vector3Scale(Vector3Normalize(right), origin.x), Vector3Scale(Vector3Normalize(up), origin.y));
4041
4042 Vector3 points[4];
4043 points[0] = Vector3Zero();
4044 points[1] = right;
4045 points[2] = Vector3Add(up, right);
4046 points[3] = up;
4047
4048 for (int i = 0; i < 4; i++)
4049 {
4050 points[i] = Vector3Subtract(points[i], origin3D);
4051 if (rotation != 0.0) points[i] = Vector3RotateByAxisAngle(points[i], forward, rotation*DEG2RAD);
4052 points[i] = Vector3Add(points[i], position);
4053 }
4054
4055 Vector2 texcoords[4];
4056 texcoords[0] = (Vector2){ (float)source.x/texture.width, (float)(source.y + source.height)/texture.height };
4057 texcoords[1] = (Vector2){ (float)(source.x + source.width)/texture.width, (float)(source.y + source.height)/texture.height };
4058 texcoords[2] = (Vector2){ (float)(source.x + source.width)/texture.width, (float)source.y/texture.height };
4059 texcoords[3] = (Vector2){ (float)source.x/texture.width, (float)source.y/texture.height };
4060
4061 rlSetTexture(texture.id);
4062 rlBegin(RL_QUADS);
4063
4064 rlColor4ub(tint.r, tint.g, tint.b, tint.a);
4065 for (int i = 0; i < 4; i++)
4066 {
4067 rlTexCoord2f(texcoords[i].x, texcoords[i].y);
4068 rlVertex3f(points[i].x, points[i].y, points[i].z);
4069 }
4070
4071 rlEnd();
4072 rlSetTexture(0);
4073 }
4074
4075 // Draw a bounding box with wires
4076 void DrawBoundingBox(BoundingBox box, Color color)
4077 {
4078 Vector3 size = { 0 };
4079
4080 size.x = fabsf(box.max.x - box.min.x);
4081 size.y = fabsf(box.max.y - box.min.y);
4082 size.z = fabsf(box.max.z - box.min.z);
4083
4084 Vector3 center = { box.min.x + size.x/2.0f, box.min.y + size.y/2.0f, box.min.z + size.z/2.0f };
4085
4086 DrawCubeWires(center, size.x, size.y, size.z, color);
4087 }
4088
4089 // Check collision between two spheres
4090 bool CheckCollisionSpheres(Vector3 center1, float radius1, Vector3 center2, float radius2)
4091 {
4092 bool collision = false;
4093
4094 // Simple way to check for collision, checking distance between two points
4095 // Unfortunately, sqrtf() is a costly operation, so avoid it with following solution
4096 /*
4097 float dx = center1.x - center2.x; // X distance between centers
4098 float dy = center1.y - center2.y; // Y distance between centers
4099 float dz = center1.z - center2.z; // Z distance between centers
4100
4101 float distance = sqrtf(dx*dx + dy*dy + dz*dz); // Distance between centers
4102
4103 if (distance <= (radius1 + radius2)) collision = true;
4104 */
4105
4106 // Check for distances squared to avoid sqrtf()
4107 float radSum = radius1 + radius2;
4108 if (Vector3DistanceSqr(center1, center2) <= (radSum*radSum)) collision = true;
4109
4110 return collision;
4111 }
4112
4113 // Check collision between two boxes
4114 // NOTE: Boxes are defined by two points minimum and maximum
4115 bool CheckCollisionBoxes(BoundingBox box1, BoundingBox box2)
4116 {
4117 bool collision = true;
4118
4119 if ((box1.max.x >= box2.min.x) && (box1.min.x <= box2.max.x))
4120 {
4121 if ((box1.max.y < box2.min.y) || (box1.min.y > box2.max.y)) collision = false;
4122 if ((box1.max.z < box2.min.z) || (box1.min.z > box2.max.z)) collision = false;
4123 }
4124 else collision = false;
4125
4126 return collision;
4127 }
4128
4129 // Check collision between box and sphere
4130 bool CheckCollisionBoxSphere(BoundingBox box, Vector3 center, float radius)
4131 {
4132 bool collision = false;
4133
4134 Vector3 closestPoint = {
4135 Clamp(center.x, box.min.x, box.max.x),
4136 Clamp(center.y, box.min.y, box.max.y),
4137 Clamp(center.z, box.min.z, box.max.z)
4138 };
4139
4140 if (Vector3DistanceSqr(center, closestPoint) <= (radius*radius)) collision = true;
4141
4142 return collision;
4143 }
4144
4145 // Get collision info between ray and sphere
4146 RayCollision GetRayCollisionSphere(Ray ray, Vector3 center, float radius)
4147 {
4148 RayCollision collision = { 0 };
4149
4150 Vector3 raySpherePos = Vector3Subtract(center, ray.position);
4151 float vector = Vector3DotProduct(raySpherePos, ray.direction);
4152 float distance = Vector3Length(raySpherePos);
4153 float d = radius*radius - (distance*distance - vector*vector);
4154
4155 collision.hit = d >= 0.0f;
4156
4157 // Check if ray origin is inside the sphere to calculate the correct collision point
4158 if (distance < radius)
4159 {
4160 collision.distance = vector + sqrtf(d);
4161
4162 // Calculate collision point
4163 collision.point = Vector3Add(ray.position, Vector3Scale(ray.direction, collision.distance));
4164
4165 // Calculate collision normal (pointing outwards)
4166 collision.normal = Vector3Negate(Vector3Normalize(Vector3Subtract(collision.point, center)));
4167 }
4168 else
4169 {
4170 collision.distance = vector - sqrtf(d);
4171
4172 // Calculate collision point
4173 collision.point = Vector3Add(ray.position, Vector3Scale(ray.direction, collision.distance));
4174
4175 // Calculate collision normal (pointing inwards)
4176 collision.normal = Vector3Normalize(Vector3Subtract(collision.point, center));
4177 }
4178
4179 return collision;
4180 }
4181
4182 // Get collision info between ray and box
4183 RayCollision GetRayCollisionBox(Ray ray, BoundingBox box)
4184 {
4185 RayCollision collision = { 0 };
4186
4187 // NOTE: If ray.position is inside the box, the distance is negative (as if the ray was reversed)
4188 // Reversing ray.direction will give use the correct result
4189 bool insideBox = (ray.position.x > box.min.x) && (ray.position.x < box.max.x) &&
4190 (ray.position.y > box.min.y) && (ray.position.y < box.max.y) &&
4191 (ray.position.z > box.min.z) && (ray.position.z < box.max.z);
4192
4193 if (insideBox) ray.direction = Vector3Negate(ray.direction);
4194
4195 float t[11] = { 0 };
4196
4197 t[8] = 1.0f/ray.direction.x;
4198 t[9] = 1.0f/ray.direction.y;
4199 t[10] = 1.0f/ray.direction.z;
4200
4201 t[0] = (box.min.x - ray.position.x)*t[8];
4202 t[1] = (box.max.x - ray.position.x)*t[8];
4203 t[2] = (box.min.y - ray.position.y)*t[9];
4204 t[3] = (box.max.y - ray.position.y)*t[9];
4205 t[4] = (box.min.z - ray.position.z)*t[10];
4206 t[5] = (box.max.z - ray.position.z)*t[10];
4207 t[6] = (float)fmax(fmax(fmin(t[0], t[1]), fmin(t[2], t[3])), fmin(t[4], t[5]));
4208 t[7] = (float)fmin(fmin(fmax(t[0], t[1]), fmax(t[2], t[3])), fmax(t[4], t[5]));
4209
4210 collision.hit = !((t[7] < 0) || (t[6] > t[7]));
4211 collision.distance = t[6];
4212 collision.point = Vector3Add(ray.position, Vector3Scale(ray.direction, collision.distance));
4213
4214 // Get box center point
4215 collision.normal = Vector3Lerp(box.min, box.max, 0.5f);
4216 // Get vector center point->hit point
4217 collision.normal = Vector3Subtract(collision.point, collision.normal);
4218 // Scale vector to unit cube
4219 // NOTE: Use an additional .01 to fix numerical errors
4220 collision.normal = Vector3Scale(collision.normal, 2.01f);
4221 collision.normal = Vector3Divide(collision.normal, Vector3Subtract(box.max, box.min));
4222 // The relevant elements of the vector are now slightly larger than 1.0f (or smaller than -1.0f)
4223 // and the others are somewhere between -1.0 and 1.0 casting to int is exactly our wanted normal!
4224 collision.normal.x = (float)((int)collision.normal.x);
4225 collision.normal.y = (float)((int)collision.normal.y);
4226 collision.normal.z = (float)((int)collision.normal.z);
4227
4228 collision.normal = Vector3Normalize(collision.normal);
4229
4230 if (insideBox)
4231 {
4232 // Reset ray.direction
4233 ray.direction = Vector3Negate(ray.direction);
4234 // Fix result
4235 collision.distance *= -1.0f;
4236 collision.normal = Vector3Negate(collision.normal);
4237 }
4238
4239 return collision;
4240 }
4241
4242 // Get collision info between ray and mesh
4243 RayCollision GetRayCollisionMesh(Ray ray, Mesh mesh, Matrix transform)
4244 {
4245 RayCollision collision = { 0 };
4246
4247 // Check if mesh vertex data on CPU for testing
4248 if (mesh.vertices != NULL)
4249 {
4250 int triangleCount = mesh.triangleCount;
4251
4252 // Test against all triangles in mesh
4253 for (int i = 0; i < triangleCount; i++)
4254 {
4255 Vector3 a = { 0 };
4256 Vector3 b = { 0 };
4257 Vector3 c = { 0 };
4258 Vector3 *vertdata = (Vector3 *)mesh.vertices;
4259
4260 if (mesh.indices)
4261 {
4262 a = vertdata[mesh.indices[i*3 + 0]];
4263 b = vertdata[mesh.indices[i*3 + 1]];
4264 c = vertdata[mesh.indices[i*3 + 2]];
4265 }
4266 else
4267 {
4268 a = vertdata[i*3 + 0];
4269 b = vertdata[i*3 + 1];
4270 c = vertdata[i*3 + 2];
4271 }
4272
4273 a = Vector3Transform(a, transform);
4274 b = Vector3Transform(b, transform);
4275 c = Vector3Transform(c, transform);
4276
4277 RayCollision triHitInfo = GetRayCollisionTriangle(ray, a, b, c);
4278
4279 if (triHitInfo.hit)
4280 {
4281 // Save the closest hit triangle
4282 if ((!collision.hit) || (collision.distance > triHitInfo.distance)) collision = triHitInfo;
4283 }
4284 }
4285 }
4286
4287 return collision;
4288 }
4289
4290 // Get collision info between ray and triangle
4291 // NOTE: The points are expected to be in counter-clockwise winding
4292 // NOTE: Based on https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm
4293 RayCollision GetRayCollisionTriangle(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3)
4294 {
4295 #define EPSILON 0.000001f // A small number
4296
4297 RayCollision collision = { 0 };
4298 Vector3 edge1 = { 0 };
4299 Vector3 edge2 = { 0 };
4300 Vector3 p = { 0 };
4301 Vector3 q = { 0 };
4302 Vector3 tv = { 0 };
4303 float det = 0.0f, invDet = 0.0f, u = 0.0f, v = 0.0f, t = 0.0f;
4304
4305 // Find vectors for two edges sharing V1
4306 edge1 = Vector3Subtract(p2, p1);
4307 edge2 = Vector3Subtract(p3, p1);
4308
4309 // Begin calculating determinant - also used to calculate u parameter
4310 p = Vector3CrossProduct(ray.direction, edge2);
4311
4312 // If determinant is near zero, ray lies in plane of triangle or ray is parallel to plane of triangle
4313 det = Vector3DotProduct(edge1, p);
4314
4315 // Avoid culling!
4316 if ((det > -EPSILON) && (det < EPSILON)) return collision;
4317
4318 invDet = 1.0f/det;
4319
4320 // Calculate distance from V1 to ray origin
4321 tv = Vector3Subtract(ray.position, p1);
4322
4323 // Calculate u parameter and test bound
4324 u = Vector3DotProduct(tv, p)*invDet;
4325
4326 // The intersection lies outside the triangle
4327 if ((u < 0.0f) || (u > 1.0f)) return collision;
4328
4329 // Prepare to test v parameter
4330 q = Vector3CrossProduct(tv, edge1);
4331
4332 // Calculate V parameter and test bound
4333 v = Vector3DotProduct(ray.direction, q)*invDet;
4334
4335 // The intersection lies outside the triangle
4336 if ((v < 0.0f) || ((u + v) > 1.0f)) return collision;
4337
4338 t = Vector3DotProduct(edge2, q)*invDet;
4339
4340 if (t > EPSILON)
4341 {
4342 // Ray hit, get hit point and normal
4343 collision.hit = true;
4344 collision.distance = t;
4345 collision.normal = Vector3Normalize(Vector3CrossProduct(edge1, edge2));
4346 collision.point = Vector3Add(ray.position, Vector3Scale(ray.direction, t));
4347 }
4348
4349 return collision;
4350 }
4351
4352 // Get collision info between ray and quad
4353 // NOTE: The points are expected to be in counter-clockwise winding
4354 RayCollision GetRayCollisionQuad(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4)
4355 {
4356 RayCollision collision = { 0 };
4357
4358 collision = GetRayCollisionTriangle(ray, p1, p2, p4);
4359
4360 if (!collision.hit) collision = GetRayCollisionTriangle(ray, p2, p3, p4);
4361
4362 return collision;
4363 }
4364
4365 //----------------------------------------------------------------------------------
4366 // Module Internal Functions Definition
4367 //----------------------------------------------------------------------------------
4368 #if SUPPORT_FILEFORMAT_IQM || SUPPORT_FILEFORMAT_GLTF
4369 // Build pose from parent joints
4370 // NOTE: Required for animations loading (required by IQM and GLTF)
4371 static void BuildPoseFromParentJoints(BoneInfo *bones, int boneCount, Transform *transforms)
4372 {
4373 for (int i = 0; i < boneCount; i++)
4374 {
4375 if (bones[i].parent >= 0)
4376 {
4377 if (bones[i].parent > i)
4378 {
4379 TRACELOG(LOG_WARNING, "Skipping bone not topologically sorted: Bone %d has parent %d", i, bones[i].parent);
4380 continue;
4381 }
4382 transforms[i].rotation = QuaternionMultiply(transforms[bones[i].parent].rotation, transforms[i].rotation);
4383 transforms[i].scale = Vector3Multiply(transforms[i].scale, transforms[bones[i].parent].scale);
4384 transforms[i].translation = Vector3Multiply(transforms[i].translation, transforms[bones[i].parent].scale);
4385 transforms[i].translation = Vector3RotateByQuaternion(transforms[i].translation, transforms[bones[i].parent].rotation);
4386 transforms[i].translation = Vector3Add(transforms[i].translation, transforms[bones[i].parent].translation);
4387 }
4388 }
4389 }
4390 #endif
4391
4392 #if SUPPORT_FILEFORMAT_OBJ
4393 // Load OBJ mesh data
4394 // Notes to keep in mind:
4395 // - A mesh is created for every material present in the obj file
4396 // - The model.meshCount is therefore the materialCount returned from tinyobj
4397 // - The mesh is automatically triangulated by tinyobj
4398 static Model LoadOBJ(const char *fileName)
4399 {
4400 tinyobj_attrib_t objAttributes = { 0 };
4401 tinyobj_shape_t *objShapes = NULL;
4402 unsigned int objShapeCount = 0;
4403
4404 tinyobj_material_t *objMaterials = NULL;
4405 unsigned int objMaterialCount = 0;
4406
4407 Model model = { 0 };
4408 model.transform = MatrixIdentity();
4409
4410 char *fileText = LoadFileText(fileName);
4411
4412 if (fileText == NULL)
4413 {
4414 TRACELOG(LOG_WARNING, "MODEL: [%s] Unable to read obj file", fileName);
4415 return model;
4416 }
4417
4418 char currentDir[MAX_FILEPATH_LENGTH] = { 0 };
4419 strncpy(currentDir, GetWorkingDirectory(), MAX_FILEPATH_LENGTH - 1); // Save current working directory
4420 const char *workingDir = GetDirectoryPath(fileName); // Switch to OBJ directory for material path correctness
4421 if (CHDIR(workingDir) != 0) TRACELOG(LOG_WARNING, "MODEL: [%s] Failed to change working directory", workingDir);
4422
4423 unsigned int dataSize = (unsigned int)strlen(fileText);
4424
4425 unsigned int flags = TINYOBJ_FLAG_TRIANGULATE;
4426 int ret = tinyobj_parse_obj(&objAttributes, &objShapes, &objShapeCount, &objMaterials, &objMaterialCount, fileText, dataSize, flags);
4427
4428 if (ret != TINYOBJ_SUCCESS)
4429 {
4430 TRACELOG(LOG_WARNING, "MODEL: Unable to read obj data %s", fileName);
4431 return model;
4432 }
4433
4434 UnloadFileText(fileText);
4435
4436 unsigned int faceVertIndex = 0;
4437 unsigned int nextShape = 1;
4438 int lastMaterial = -1;
4439 unsigned int meshIndex = 0;
4440
4441 // Count meshes
4442 unsigned int nextShapeEnd = objAttributes.num_face_num_verts;
4443
4444 // See how many verts till the next shape
4445 if (objShapeCount > 1) nextShapeEnd = objShapes[nextShape].face_offset;
4446
4447 // Walk all the faces
4448 for (unsigned int faceId = 0; faceId < objAttributes.num_faces; faceId++)
4449 {
4450 if (faceId >= nextShapeEnd)
4451 {
4452 // Try to find the last vert in the next shape
4453 nextShape++;
4454 if (nextShape < objShapeCount) nextShapeEnd = objShapes[nextShape].face_offset;
4455 else nextShapeEnd = objAttributes.num_face_num_verts; // This is actually the total number of face verts in the file, not faces
4456 meshIndex++;
4457 }
4458 else if ((lastMaterial != -1) && (objAttributes.material_ids[faceId] != lastMaterial))
4459 {
4460 meshIndex++; // If this is a new material, a new mesh is allocated
4461 }
4462
4463 lastMaterial = objAttributes.material_ids[faceId];
4464 faceVertIndex += objAttributes.face_num_verts[faceId];
4465 }
4466
4467 // Allocate the base meshes and materials
4468 model.meshCount = meshIndex + 1;
4469 model.meshes = (Mesh *)MemAlloc(sizeof(Mesh)*model.meshCount);
4470
4471 if (objMaterialCount > 0)
4472 {
4473 model.materialCount = objMaterialCount;
4474 model.materials = (Material *)MemAlloc(sizeof(Material)*objMaterialCount);
4475 }
4476 else // Allocate at least one material
4477 {
4478 model.materialCount = 1;
4479 model.materials = (Material *)MemAlloc(sizeof(Material)*1);
4480 }
4481
4482 model.meshMaterial = (int *)MemAlloc(sizeof(int)*model.meshCount);
4483
4484 // See how many verts are in each mesh
4485 unsigned int *localMeshVertexCounts = (unsigned int *)MemAlloc(sizeof(unsigned int)*model.meshCount);
4486
4487 faceVertIndex = 0;
4488 nextShapeEnd = objAttributes.num_face_num_verts;
4489 lastMaterial = -1;
4490 meshIndex = 0;
4491 unsigned int localMeshVertexCount = 0;
4492
4493 nextShape = 1;
4494 if (objShapeCount > 1) nextShapeEnd = objShapes[nextShape].face_offset;
4495
4496 // Walk all the faces
4497 for (unsigned int faceId = 0; faceId < objAttributes.num_faces; faceId++)
4498 {
4499 bool newMesh = false; // Is a new mesh required?
4500 if (faceId >= nextShapeEnd)
4501 {
4502 // Try to find the last vert in the next shape
4503 nextShape++;
4504 if (nextShape < objShapeCount) nextShapeEnd = objShapes[nextShape].face_offset;
4505 else nextShapeEnd = objAttributes.num_face_num_verts; // this is actually the total number of face verts in the file, not faces
4506
4507 newMesh = true;
4508 }
4509 else if ((lastMaterial != -1) && (objAttributes.material_ids[faceId] != lastMaterial))
4510 {
4511 newMesh = true;
4512 }
4513
4514 lastMaterial = objAttributes.material_ids[faceId];
4515
4516 if (newMesh)
4517 {
4518 localMeshVertexCounts[meshIndex] = localMeshVertexCount;
4519
4520 localMeshVertexCount = 0;
4521 meshIndex++;
4522 }
4523
4524 faceVertIndex += objAttributes.face_num_verts[faceId];
4525 localMeshVertexCount += objAttributes.face_num_verts[faceId];
4526 }
4527
4528 localMeshVertexCounts[meshIndex] = localMeshVertexCount;
4529
4530 for (int i = 0; i < model.meshCount; i++)
4531 {
4532 // Allocate the buffers for each mesh
4533 unsigned int vertexCount = localMeshVertexCounts[i];
4534
4535 model.meshes[i].vertexCount = vertexCount;
4536 model.meshes[i].triangleCount = vertexCount/3;
4537
4538 model.meshes[i].vertices = (float *)MemAlloc(sizeof(float)*vertexCount*3);
4539 model.meshes[i].normals = (float *)MemAlloc(sizeof(float)*vertexCount*3);
4540 #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)
4541 model.meshes[i].texcoords = (float *)MemAlloc(sizeof(float)*vertexCount*2);
4542 model.meshes[i].colors = (unsigned char *)MemAlloc(sizeof(unsigned char)*vertexCount*4);
4543 #else
4544 if (objAttributes.texcoords != NULL && objAttributes.num_texcoords > 0)
4545 model.meshes[i].texcoords = (float *)MemAlloc(sizeof(float)*vertexCount*2);
4546 else model.meshes[i].texcoords = NULL;
4547 model.meshes[i].colors = NULL;
4548 #endif
4549 }
4550
4551 MemFree(localMeshVertexCounts);
4552 localMeshVertexCounts = NULL;
4553
4554 // Fill meshes
4555 faceVertIndex = 0;
4556
4557 nextShapeEnd = objAttributes.num_face_num_verts;
4558
4559 // See how many verts till the next shape
4560 nextShape = 1;
4561 if (objShapeCount > 1) nextShapeEnd = objShapes[nextShape].face_offset;
4562 lastMaterial = -1;
4563 meshIndex = 0;
4564 localMeshVertexCount = 0;
4565
4566 // Walk all the faces
4567 for (unsigned int faceId = 0; faceId < objAttributes.num_faces; faceId++)
4568 {
4569 bool newMesh = false; // Is a new mesh required?
4570 if (faceId >= nextShapeEnd)
4571 {
4572 // Try to find the last vert in the next shape
4573 nextShape++;
4574 if (nextShape < objShapeCount) nextShapeEnd = objShapes[nextShape].face_offset;
4575 else nextShapeEnd = objAttributes.num_face_num_verts; // This is actually the total number of face verts in the file, not faces
4576 newMesh = true;
4577 }
4578
4579 // If this is a new material, a new mesh is allocated
4580 if (lastMaterial != -1 && objAttributes.material_ids[faceId] != lastMaterial) newMesh = true;
4581 lastMaterial = objAttributes.material_ids[faceId];
4582
4583 if (newMesh)
4584 {
4585 localMeshVertexCount = 0;
4586 meshIndex++;
4587 }
4588
4589 int matId = 0;
4590 if ((lastMaterial >= 0) && (lastMaterial < (int)objMaterialCount)) matId = lastMaterial;
4591
4592 model.meshMaterial[meshIndex] = matId;
4593
4594 for (int f = 0; f < objAttributes.face_num_verts[faceId]; f++)
4595 {
4596 int vertIndex = objAttributes.faces[faceVertIndex].v_idx;
4597 int normalIndex = objAttributes.faces[faceVertIndex].vn_idx;
4598 int texcordIndex = objAttributes.faces[faceVertIndex].vt_idx;
4599
4600 for (int i = 0; i < 3; i++) model.meshes[meshIndex].vertices[localMeshVertexCount*3 + i] = objAttributes.vertices[vertIndex*3 + i];
4601
4602 if ((objAttributes.texcoords != NULL) && (texcordIndex != TINYOBJ_INVALID_INDEX) && (texcordIndex >= 0) && (model.meshes[meshIndex].texcoords))
4603 {
4604 for (int i = 0; i < 2; i++) model.meshes[meshIndex].texcoords[localMeshVertexCount*2 + i] = objAttributes.texcoords[texcordIndex*2 + i];
4605 model.meshes[meshIndex].texcoords[localMeshVertexCount*2 + 1] = 1.0f - model.meshes[meshIndex].texcoords[localMeshVertexCount*2 + 1];
4606 }
4607
4608 if ((objAttributes.normals != NULL) && (normalIndex != TINYOBJ_INVALID_INDEX) && (normalIndex >= 0))
4609 {
4610 for (int i = 0; i < 3; i++) model.meshes[meshIndex].normals[localMeshVertexCount*3 + i] = objAttributes.normals[normalIndex*3 + i];
4611 }
4612 else
4613 {
4614 model.meshes[meshIndex].normals[localMeshVertexCount*3 + 0] = 0.0f;
4615 model.meshes[meshIndex].normals[localMeshVertexCount*3 + 1] = 1.0f;
4616 model.meshes[meshIndex].normals[localMeshVertexCount*3 + 2] = 0.0f;
4617 }
4618 #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)
4619 for (int i = 0; i < 4; i++) model.meshes[meshIndex].colors[localMeshVertexCount*4 + i] = 255;
4620 #endif
4621 faceVertIndex++;
4622 localMeshVertexCount++;
4623 }
4624 }
4625
4626 if (objMaterialCount > 0) ProcessMaterialsOBJ(model.materials, objMaterials, objMaterialCount);
4627 else model.materials[0] = LoadMaterialDefault(); // Set default material for the mesh
4628
4629 tinyobj_attrib_free(&objAttributes);
4630 tinyobj_shapes_free(objShapes, objShapeCount);
4631 tinyobj_materials_free(objMaterials, objMaterialCount);
4632
4633 // Restore current working directory
4634 if (CHDIR(currentDir) != 0)
4635 {
4636 TRACELOG(LOG_WARNING, "MODEL: [%s] Failed to change working directory", currentDir);
4637 }
4638
4639 return model;
4640 }
4641 #endif
4642
4643 #if SUPPORT_FILEFORMAT_IQM
4644 // Load IQM mesh data
4645 static Model LoadIQM(const char *fileName)
4646 {
4647 #define IQM_MAGIC "INTERQUAKEMODEL" // IQM file magic number
4648 #define IQM_VERSION 2 // Only IQM version 2 supported
4649
4650 #define BONE_NAME_LENGTH 32 // BoneInfo name string length
4651 #define MESH_NAME_LENGTH 32 // Mesh name string length
4652 #define MATERIAL_NAME_LENGTH 32 // Material name string length
4653
4654 int dataSize = 0;
4655 unsigned char *fileData = LoadFileData(fileName, &dataSize);
4656 unsigned char *fileDataPtr = fileData;
4657
4658 // IQM file structs
4659 //-----------------------------------------------------------------------------------
4660 typedef struct IQMHeader {
4661 char magic[16];
4662 unsigned int version;
4663 unsigned int dataSize;
4664 unsigned int flags;
4665 unsigned int num_text, ofs_text;
4666 unsigned int num_meshes, ofs_meshes;
4667 unsigned int num_vertexarrays, num_vertexes, ofs_vertexarrays;
4668 unsigned int num_triangles, ofs_triangles, ofs_adjacency;
4669 unsigned int num_joints, ofs_joints;
4670 unsigned int num_poses, ofs_poses;
4671 unsigned int num_anims, ofs_anims;
4672 unsigned int num_frames, num_framechannels, ofs_frames, ofs_bounds;
4673 unsigned int num_comment, ofs_comment;
4674 unsigned int num_extensions, ofs_extensions;
4675 } IQMHeader;
4676
4677 typedef struct IQMMesh {
4678 unsigned int name;
4679 unsigned int material;
4680 unsigned int first_vertex, num_vertexes;
4681 unsigned int first_triangle, num_triangles;
4682 } IQMMesh;
4683
4684 typedef struct IQMTriangle {
4685 unsigned int vertex[3];
4686 } IQMTriangle;
4687
4688 typedef struct IQMJoint {
4689 unsigned int name;
4690 int parent;
4691 float translate[3], rotate[4], scale[3];
4692 } IQMJoint;
4693
4694 typedef struct IQMVertexArray {
4695 unsigned int type;
4696 unsigned int flags;
4697 unsigned int format;
4698 unsigned int size;
4699 unsigned int offset;
4700 } IQMVertexArray;
4701
4702 // NOTE: Below IQM structures are not used but listed for reference
4703 /*
4704 typedef struct IQMAdjacency {
4705 unsigned int triangle[3];
4706 } IQMAdjacency;
4707
4708 typedef struct IQMPose {
4709 int parent;
4710 unsigned int mask;
4711 float channeloffset[10];
4712 float channelscale[10];
4713 } IQMPose;
4714
4715 typedef struct IQMAnim {
4716 unsigned int name;
4717 unsigned int first_frame, num_frames;
4718 float framerate;
4719 unsigned int flags;
4720 } IQMAnim;
4721
4722 typedef struct IQMBounds {
4723 float bbmin[3], bbmax[3];
4724 float xyradius, radius;
4725 } IQMBounds;
4726 */
4727 //-----------------------------------------------------------------------------------
4728
4729 // IQM vertex data types
4730 enum {
4731 IQM_POSITION = 0,
4732 IQM_TEXCOORD = 1,
4733 IQM_NORMAL = 2,
4734 IQM_TANGENT = 3, // NOTE: Tangents unused by default
4735 IQM_BLENDINDEXES = 4,
4736 IQM_BLENDWEIGHTS = 5,
4737 IQM_COLOR = 6,
4738 IQM_CUSTOM = 0x10 // NOTE: Custom vertex values unused by default
4739 };
4740
4741 Model model = { 0 };
4742
4743 IQMMesh *imesh = NULL;
4744 IQMTriangle *tri = NULL;
4745 IQMVertexArray *va = NULL;
4746 IQMJoint *ijoint = NULL;
4747
4748 float *vertex = NULL;
4749 float *normal = NULL;
4750 float *text = NULL;
4751 char *blendi = NULL;
4752 unsigned char *blendw = NULL;
4753 unsigned char *color = NULL;
4754
4755 // In case file can not be read, return an empty model
4756 if (fileDataPtr == NULL) return model;
4757
4758 const char *basePath = GetDirectoryPath(fileName);
4759
4760 // Read IQM header
4761 IQMHeader *iqmHeader = (IQMHeader *)fileDataPtr;
4762
4763 if (memcmp(iqmHeader->magic, IQM_MAGIC, sizeof(IQM_MAGIC)) != 0)
4764 {
4765 TRACELOG(LOG_WARNING, "MODEL: [%s] IQM file is not a valid model", fileName);
4766 UnloadFileData(fileData);
4767 return model;
4768 }
4769
4770 if (iqmHeader->version != IQM_VERSION)
4771 {
4772 TRACELOG(LOG_WARNING, "MODEL: [%s] IQM file version not supported (%i)", fileName, iqmHeader->version);
4773 UnloadFileData(fileData);
4774 return model;
4775 }
4776
4777 //fileDataPtr += sizeof(IQMHeader); // Move file data pointer
4778
4779 // Meshes data processing
4780 imesh = (IQMMesh *)RL_MALLOC(iqmHeader->num_meshes*sizeof(IQMMesh));
4781 //fseek(iqmFile, iqmHeader->ofs_meshes, SEEK_SET);
4782 //fread(imesh, sizeof(IQMMesh)*iqmHeader->num_meshes, 1, iqmFile);
4783 memcpy(imesh, fileDataPtr + iqmHeader->ofs_meshes, iqmHeader->num_meshes*sizeof(IQMMesh));
4784
4785 model.meshCount = iqmHeader->num_meshes;
4786 model.meshes = (Mesh *)RL_CALLOC(model.meshCount, sizeof(Mesh));
4787
4788 model.materialCount = model.meshCount;
4789 model.materials = (Material *)RL_CALLOC(model.materialCount, sizeof(Material));
4790 model.meshMaterial = (int *)RL_CALLOC(model.meshCount, sizeof(int));
4791
4792 char name[MESH_NAME_LENGTH] = { 0 };
4793 char material[MATERIAL_NAME_LENGTH] = { 0 };
4794
4795 for (int i = 0; i < model.meshCount; i++)
4796 {
4797 //fseek(iqmFile, iqmHeader->ofs_text + imesh[a].name, SEEK_SET);
4798 //fread(name, sizeof(char), MESH_NAME_LENGTH, iqmFile);
4799 memcpy(name, fileDataPtr + iqmHeader->ofs_text + imesh[i].name, MESH_NAME_LENGTH*sizeof(char));
4800
4801 //fseek(iqmFile, iqmHeader->ofs_text + imesh[a].material, SEEK_SET);
4802 //fread(material, sizeof(char), MATERIAL_NAME_LENGTH, iqmFile);
4803 memcpy(material, fileDataPtr + iqmHeader->ofs_text + imesh[i].material, MATERIAL_NAME_LENGTH*sizeof(char));
4804
4805 model.materials[i] = LoadMaterialDefault();
4806 model.materials[i].maps[MATERIAL_MAP_ALBEDO].texture = LoadTexture(TextFormat("%s/%s", basePath, material));
4807
4808 model.meshMaterial[i] = i;
4809
4810 TRACELOG(LOG_DEBUG, "MODEL: [%s] mesh name (%s), material (%s)", fileName, name, material);
4811
4812 model.meshes[i].vertexCount = imesh[i].num_vertexes;
4813
4814 model.meshes[i].vertices = (float *)RL_CALLOC(model.meshes[i].vertexCount*3, sizeof(float)); // Default vertex positions
4815 model.meshes[i].normals = (float *)RL_CALLOC(model.meshes[i].vertexCount*3, sizeof(float)); // Default vertex normals
4816 model.meshes[i].texcoords = (float *)RL_CALLOC(model.meshes[i].vertexCount*2, sizeof(float)); // Default vertex texcoords
4817
4818 model.meshes[i].boneIndices = (unsigned char *)RL_CALLOC(model.meshes[i].vertexCount*4, sizeof(unsigned char)); // Up-to 4 bones supported!
4819 model.meshes[i].boneWeights = (float *)RL_CALLOC(model.meshes[i].vertexCount*4, sizeof(float)); // Up-to 4 bones supported!
4820
4821 model.meshes[i].triangleCount = imesh[i].num_triangles;
4822 model.meshes[i].indices = (unsigned short *)RL_CALLOC(model.meshes[i].triangleCount*3, sizeof(unsigned short));
4823
4824 #if !SUPPORT_GPU_SKINNING
4825 // Animated vertex data, processed for rendering
4826 // NOTE: Animated vertex should be re-uploaded to GPU (if not using GPU skinning)
4827 model.meshes[i].animVertices = (float *)RL_CALLOC(model.meshes[i].vertexCount*3, sizeof(float));
4828 model.meshes[i].animNormals = (float *)RL_CALLOC(model.meshes[i].vertexCount*3, sizeof(float));
4829 #endif
4830 }
4831
4832 // Triangles data processing
4833 tri = (IQMTriangle *)RL_MALLOC(iqmHeader->num_triangles*sizeof(IQMTriangle));
4834 //fseek(iqmFile, iqmHeader->ofs_triangles, SEEK_SET);
4835 //fread(tri, sizeof(IQMTriangle), iqmHeader->num_triangles, iqmFile);
4836 memcpy(tri, fileDataPtr + iqmHeader->ofs_triangles, iqmHeader->num_triangles*sizeof(IQMTriangle));
4837
4838 for (int m = 0; m < model.meshCount; m++)
4839 {
4840 int tcounter = 0;
4841
4842 for (unsigned int i = imesh[m].first_triangle; i < (imesh[m].first_triangle + imesh[m].num_triangles); i++)
4843 {
4844 // IQM triangles indexes are stored in counter-clockwise, but raylib processes the index in linear order,
4845 // expecting they point to the counter-clockwise vertex triangle, so triangle indexes need to be reversed
4846 // NOTE: raylib renders vertex data in counter-clockwise order (standard convention) by default
4847 model.meshes[m].indices[tcounter + 2] = tri[i].vertex[0] - imesh[m].first_vertex;
4848 model.meshes[m].indices[tcounter + 1] = tri[i].vertex[1] - imesh[m].first_vertex;
4849 model.meshes[m].indices[tcounter] = tri[i].vertex[2] - imesh[m].first_vertex;
4850 tcounter += 3;
4851 }
4852 }
4853
4854 // Vertex arrays data processing
4855 va = (IQMVertexArray *)RL_MALLOC(iqmHeader->num_vertexarrays*sizeof(IQMVertexArray));
4856 //fseek(iqmFile, iqmHeader->ofs_vertexarrays, SEEK_SET);
4857 //fread(va, sizeof(IQMVertexArray), iqmHeader->num_vertexarrays, iqmFile);
4858 memcpy(va, fileDataPtr + iqmHeader->ofs_vertexarrays, iqmHeader->num_vertexarrays*sizeof(IQMVertexArray));
4859
4860 for (unsigned int i = 0; i < iqmHeader->num_vertexarrays; i++)
4861 {
4862 switch (va[i].type)
4863 {
4864 case IQM_POSITION:
4865 {
4866 vertex = (float *)RL_MALLOC(iqmHeader->num_vertexes*3*sizeof(float));
4867 //fseek(iqmFile, va[a].offset, SEEK_SET);
4868 //fread(vertex, iqmHeader->num_vertexes*3*sizeof(float), 1, iqmFile);
4869 memcpy(vertex, fileDataPtr + va[i].offset, iqmHeader->num_vertexes*3*sizeof(float));
4870
4871 for (unsigned int m = 0; m < iqmHeader->num_meshes; m++)
4872 {
4873 int vCounter = 0;
4874 for (unsigned int i = imesh[m].first_vertex*3; i < (imesh[m].first_vertex + imesh[m].num_vertexes)*3; i++)
4875 {
4876 model.meshes[m].vertices[vCounter] = vertex[i];
4877 if (model.meshes[m].animVertices != NULL) model.meshes[m].animVertices[vCounter] = vertex[i];
4878 vCounter++;
4879 }
4880 }
4881 } break;
4882 case IQM_NORMAL:
4883 {
4884 normal = (float *)RL_MALLOC(iqmHeader->num_vertexes*3*sizeof(float));
4885 //fseek(iqmFile, va[a].offset, SEEK_SET);
4886 //fread(normal, iqmHeader->num_vertexes*3*sizeof(float), 1, iqmFile);
4887 memcpy(normal, fileDataPtr + va[i].offset, iqmHeader->num_vertexes*3*sizeof(float));
4888
4889 for (unsigned int m = 0; m < iqmHeader->num_meshes; m++)
4890 {
4891 int vCounter = 0;
4892 for (unsigned int i = imesh[m].first_vertex*3; i < (imesh[m].first_vertex + imesh[m].num_vertexes)*3; i++)
4893 {
4894 model.meshes[m].normals[vCounter] = normal[i];
4895 if (model.meshes[m].animNormals != NULL) model.meshes[m].animNormals[vCounter] = normal[i];
4896 vCounter++;
4897 }
4898 }
4899 } break;
4900 case IQM_TEXCOORD:
4901 {
4902 text = (float *)RL_MALLOC(iqmHeader->num_vertexes*2*sizeof(float));
4903 //fseek(iqmFile, va[a].offset, SEEK_SET);
4904 //fread(text, iqmHeader->num_vertexes*2*sizeof(float), 1, iqmFile);
4905 memcpy(text, fileDataPtr + va[i].offset, iqmHeader->num_vertexes*2*sizeof(float));
4906
4907 for (unsigned int m = 0; m < iqmHeader->num_meshes; m++)
4908 {
4909 int vCounter = 0;
4910 for (unsigned int i = imesh[m].first_vertex*2; i < (imesh[m].first_vertex + imesh[m].num_vertexes)*2; i++)
4911 {
4912 model.meshes[m].texcoords[vCounter] = text[i];
4913 vCounter++;
4914 }
4915 }
4916 } break;
4917 case IQM_BLENDINDEXES:
4918 {
4919 blendi = (char *)RL_MALLOC(iqmHeader->num_vertexes*4*sizeof(char));
4920 //fseek(iqmFile, va[a].offset, SEEK_SET);
4921 //fread(blendi, iqmHeader->num_vertexes*4*sizeof(char), 1, iqmFile);
4922 memcpy(blendi, fileDataPtr + va[i].offset, iqmHeader->num_vertexes*4*sizeof(char));
4923
4924 for (unsigned int m = 0; m < iqmHeader->num_meshes; m++)
4925 {
4926 int boneCounter = 0;
4927 for (unsigned int i = imesh[m].first_vertex*4; i < (imesh[m].first_vertex + imesh[m].num_vertexes)*4; i++)
4928 {
4929 model.meshes[m].boneIndices[boneCounter] = blendi[i];
4930 boneCounter++;
4931 }
4932 }
4933 } break;
4934 case IQM_BLENDWEIGHTS:
4935 {
4936 blendw = (unsigned char *)RL_MALLOC(iqmHeader->num_vertexes*4*sizeof(unsigned char));
4937 //fseek(iqmFile, va[a].offset, SEEK_SET);
4938 //fread(blendw, iqmHeader->num_vertexes*4*sizeof(unsigned char), 1, iqmFile);
4939 memcpy(blendw, fileDataPtr + va[i].offset, iqmHeader->num_vertexes*4*sizeof(unsigned char));
4940
4941 for (unsigned int m = 0; m < iqmHeader->num_meshes; m++)
4942 {
4943 int boneCounter = 0;
4944 for (unsigned int i = imesh[m].first_vertex*4; i < (imesh[m].first_vertex + imesh[m].num_vertexes)*4; i++)
4945 {
4946 model.meshes[m].boneWeights[boneCounter] = blendw[i]/255.0f;
4947 boneCounter++;
4948 }
4949 }
4950 } break;
4951 case IQM_COLOR:
4952 {
4953 color = (unsigned char *)RL_MALLOC(iqmHeader->num_vertexes*4*sizeof(unsigned char));
4954 //fseek(iqmFile, va[a].offset, SEEK_SET);
4955 //fread(blendw, iqmHeader->num_vertexes*4*sizeof(unsigned char), 1, iqmFile);
4956 memcpy(color, fileDataPtr + va[i].offset, iqmHeader->num_vertexes*4*sizeof(unsigned char));
4957
4958 for (unsigned int m = 0; m < iqmHeader->num_meshes; m++)
4959 {
4960 model.meshes[m].colors = (unsigned char *)RL_CALLOC(model.meshes[m].vertexCount*4, sizeof(unsigned char));
4961
4962 int vCounter = 0;
4963 for (unsigned int i = imesh[m].first_vertex*4; i < (imesh[m].first_vertex + imesh[m].num_vertexes)*4; i++)
4964 {
4965 model.meshes[m].colors[vCounter] = color[i];
4966 vCounter++;
4967 }
4968 }
4969 } break;
4970 }
4971 }
4972
4973 // Bones (joints) data processing
4974 ijoint = (IQMJoint *)RL_MALLOC(iqmHeader->num_joints*sizeof(IQMJoint));
4975 //fseek(iqmFile, iqmHeader->ofs_joints, SEEK_SET);
4976 //fread(ijoint, sizeof(IQMJoint), iqmHeader->num_joints, iqmFile);
4977 memcpy(ijoint, fileDataPtr + iqmHeader->ofs_joints, iqmHeader->num_joints*sizeof(IQMJoint));
4978
4979 model.skeleton.boneCount = iqmHeader->num_joints;
4980 model.skeleton.bones = (BoneInfo *)RL_CALLOC(iqmHeader->num_joints, sizeof(BoneInfo));
4981 model.skeleton.bindPose = (Transform *)RL_CALLOC(iqmHeader->num_joints, sizeof(Transform));
4982
4983 for (unsigned int i = 0; i < iqmHeader->num_joints; i++)
4984 {
4985 // Bones
4986 model.skeleton.bones[i].parent = ijoint[i].parent;
4987 //fseek(iqmFile, iqmHeader->ofs_text + ijoint[a].name, SEEK_SET);
4988 //fread(model.bones[a].name, sizeof(char), BONE_NAME_LENGTH, iqmFile);
4989 memcpy(model.skeleton.bones[i].name, fileDataPtr + iqmHeader->ofs_text + ijoint[i].name, BONE_NAME_LENGTH*sizeof(char));
4990
4991 // Bind pose (base pose)
4992 model.skeleton.bindPose[i].translation.x = ijoint[i].translate[0];
4993 model.skeleton.bindPose[i].translation.y = ijoint[i].translate[1];
4994 model.skeleton.bindPose[i].translation.z = ijoint[i].translate[2];
4995
4996 model.skeleton.bindPose[i].rotation.x = ijoint[i].rotate[0];
4997 model.skeleton.bindPose[i].rotation.y = ijoint[i].rotate[1];
4998 model.skeleton.bindPose[i].rotation.z = ijoint[i].rotate[2];
4999 model.skeleton.bindPose[i].rotation.w = ijoint[i].rotate[3];
5000
5001 model.skeleton.bindPose[i].scale.x = ijoint[i].scale[0];
5002 model.skeleton.bindPose[i].scale.y = ijoint[i].scale[1];
5003 model.skeleton.bindPose[i].scale.z = ijoint[i].scale[2];
5004 }
5005
5006 BuildPoseFromParentJoints(model.skeleton.bones, model.skeleton.boneCount, model.skeleton.bindPose);
5007
5008 // Initialize runtime animation data: current pose and bone matrices
5009 model.currentPose = (Transform *)RL_CALLOC(model.skeleton.boneCount, sizeof(Transform));
5010 model.boneMatrices = (Matrix *)RL_CALLOC(model.skeleton.boneCount, sizeof(Matrix));
5011 for (int j = 0; j < model.skeleton.boneCount; j++) model.boneMatrices[j] = MatrixIdentity();
5012
5013 UnloadFileData(fileData);
5014
5015 RL_FREE(imesh);
5016 RL_FREE(tri);
5017 RL_FREE(va);
5018 RL_FREE(vertex);
5019 RL_FREE(normal);
5020 RL_FREE(text);
5021 RL_FREE(blendi);
5022 RL_FREE(blendw);
5023 RL_FREE(ijoint);
5024 RL_FREE(color);
5025
5026 return model;
5027 }
5028
5029 // Load IQM animation data
5030 static ModelAnimation *LoadModelAnimationsIQM(const char *fileName, int *animCount)
5031 {
5032 #define IQM_MAGIC "INTERQUAKEMODEL" // IQM file magic number
5033 #define IQM_VERSION 2 // only IQM version 2 supported
5034
5035 int dataSize = 0;
5036 unsigned char *fileData = LoadFileData(fileName, &dataSize);
5037 unsigned char *fileDataPtr = fileData;
5038
5039 typedef struct IQMHeader {
5040 char magic[16];
5041 unsigned int version;
5042 unsigned int dataSize;
5043 unsigned int flags;
5044 unsigned int num_text, ofs_text;
5045 unsigned int num_meshes, ofs_meshes;
5046 unsigned int num_vertexarrays, num_vertexes, ofs_vertexarrays;
5047 unsigned int num_triangles, ofs_triangles, ofs_adjacency;
5048 unsigned int num_joints, ofs_joints;
5049 unsigned int num_poses, ofs_poses;
5050 unsigned int num_anims, ofs_anims;
5051 unsigned int num_frames, num_framechannels, ofs_frames, ofs_bounds;
5052 unsigned int num_comment, ofs_comment;
5053 unsigned int num_extensions, ofs_extensions;
5054 } IQMHeader;
5055
5056 typedef struct IQMJoint {
5057 unsigned int name;
5058 int parent;
5059 float translate[3], rotate[4], scale[3];
5060 } IQMJoint;
5061
5062 typedef struct IQMPose {
5063 int parent;
5064 unsigned int mask;
5065 float channeloffset[10];
5066 float channelscale[10];
5067 } IQMPose;
5068
5069 typedef struct IQMAnim {
5070 unsigned int name;
5071 unsigned int first_frame, num_frames;
5072 float framerate;
5073 unsigned int flags;
5074 } IQMAnim;
5075
5076 // In case file can not be read, return an empty model
5077 if (fileDataPtr == NULL) return NULL;
5078
5079 // Read IQM header
5080 IQMHeader *iqmHeader = (IQMHeader *)fileDataPtr;
5081
5082 if (memcmp(iqmHeader->magic, IQM_MAGIC, sizeof(IQM_MAGIC)) != 0)
5083 {
5084 TRACELOG(LOG_WARNING, "MODEL: [%s] IQM file is not a valid model", fileName);
5085 UnloadFileData(fileData);
5086 return NULL;
5087 }
5088
5089 if (iqmHeader->version != IQM_VERSION)
5090 {
5091 TRACELOG(LOG_WARNING, "MODEL: [%s] IQM file version not supported (%i)", fileName, iqmHeader->version);
5092 UnloadFileData(fileData);
5093 return NULL;
5094 }
5095
5096 // Get bones data
5097 IQMPose *poses = (IQMPose *)RL_MALLOC(iqmHeader->num_poses*sizeof(IQMPose));
5098 //fseek(iqmFile, iqmHeader->ofs_poses, SEEK_SET);
5099 //fread(poses, sizeof(IQMPose), iqmHeader->num_poses, iqmFile);
5100 memcpy(poses, fileDataPtr + iqmHeader->ofs_poses, iqmHeader->num_poses*sizeof(IQMPose));
5101
5102 // Get animations data
5103 *animCount = iqmHeader->num_anims;
5104 IQMAnim *anim = (IQMAnim *)RL_MALLOC(iqmHeader->num_anims*sizeof(IQMAnim));
5105 //fseek(iqmFile, iqmHeader->ofs_anims, SEEK_SET);
5106 //fread(anim, sizeof(IQMAnim), iqmHeader->num_anims, iqmFile);
5107 memcpy(anim, fileDataPtr + iqmHeader->ofs_anims, iqmHeader->num_anims*sizeof(IQMAnim));
5108
5109 ModelAnimation *animations = (ModelAnimation *)RL_CALLOC(iqmHeader->num_anims, sizeof(ModelAnimation));
5110
5111 // frameposes
5112 unsigned short *framedata = (unsigned short *)RL_CALLOC(iqmHeader->num_frames*iqmHeader->num_framechannels, sizeof(unsigned short));
5113 //fseek(iqmFile, iqmHeader->ofs_frames, SEEK_SET);
5114 //fread(framedata, sizeof(unsigned short), iqmHeader->num_frames*iqmHeader->num_framechannels, iqmFile);
5115 memcpy(framedata, fileDataPtr + iqmHeader->ofs_frames, iqmHeader->num_frames*iqmHeader->num_framechannels*sizeof(unsigned short));
5116
5117 // joints
5118 IQMJoint *joints = (IQMJoint *)RL_CALLOC(iqmHeader->num_joints, sizeof(IQMJoint));
5119 memcpy(joints, fileDataPtr + iqmHeader->ofs_joints, iqmHeader->num_joints*sizeof(IQMJoint));
5120
5121 for (unsigned int a = 0; a < iqmHeader->num_anims; a++)
5122 {
5123 animations[a].boneCount = iqmHeader->num_poses;
5124 BoneInfo *bones = (BoneInfo *)RL_CALLOC(iqmHeader->num_poses, sizeof(BoneInfo));
5125
5126 animations[a].keyframeCount = anim[a].num_frames;
5127 animations[a].keyframePoses = (Transform **)RL_CALLOC(anim[a].num_frames, sizeof(Transform *));
5128 memcpy(animations[a].name, fileDataPtr + iqmHeader->ofs_text + anim[a].name, 32);
5129 // TODO: Use animation framerate data?
5130 //animations[a].framerate = anim.framerate;
5131
5132 TRACELOG(LOG_INFO, "MODEL: [%s] Loaded animation: %s | Frames: %d | Framerate: %f", fileName, animations[a].name, animations[a].keyframeCount, anim[a].framerate);
5133
5134 for (unsigned int j = 0; j < iqmHeader->num_poses; j++)
5135 {
5136 bones[j].parent = poses[j].parent;
5137
5138 // NOTE: No need to store bones names, bones only required to generate keyframe poses
5139 //if (iqmHeader->num_joints > 0) memcpy(bones[j].name, fileDataPtr + iqmHeader->ofs_text + joints[j].name, BONE_NAME_LENGTH*sizeof(char));
5140 //else memcpy(bones[j].name, "ANIMJOINTNAME", 13); // Default bone name otherwise
5141 }
5142
5143 for (unsigned int j = 0; j < anim[a].num_frames; j++)
5144 animations[a].keyframePoses[j] = (Transform *)RL_MALLOC(iqmHeader->num_poses*sizeof(Transform));
5145
5146 int dcounter = anim[a].first_frame*iqmHeader->num_framechannels;
5147
5148 for (unsigned int frame = 0; frame < anim[a].num_frames; frame++)
5149 {
5150 for (unsigned int i = 0; i < iqmHeader->num_poses; i++)
5151 {
5152 animations[a].keyframePoses[frame][i].translation.x = poses[i].channeloffset[0];
5153
5154 if (poses[i].mask & 0x01)
5155 {
5156 animations[a].keyframePoses[frame][i].translation.x += framedata[dcounter]*poses[i].channelscale[0];
5157 dcounter++;
5158 }
5159
5160 animations[a].keyframePoses[frame][i].translation.y = poses[i].channeloffset[1];
5161
5162 if (poses[i].mask & 0x02)
5163 {
5164 animations[a].keyframePoses[frame][i].translation.y += framedata[dcounter]*poses[i].channelscale[1];
5165 dcounter++;
5166 }
5167
5168 animations[a].keyframePoses[frame][i].translation.z = poses[i].channeloffset[2];
5169
5170 if (poses[i].mask & 0x04)
5171 {
5172 animations[a].keyframePoses[frame][i].translation.z += framedata[dcounter]*poses[i].channelscale[2];
5173 dcounter++;
5174 }
5175
5176 animations[a].keyframePoses[frame][i].rotation.x = poses[i].channeloffset[3];
5177
5178 if (poses[i].mask & 0x08)
5179 {
5180 animations[a].keyframePoses[frame][i].rotation.x += framedata[dcounter]*poses[i].channelscale[3];
5181 dcounter++;
5182 }
5183
5184 animations[a].keyframePoses[frame][i].rotation.y = poses[i].channeloffset[4];
5185
5186 if (poses[i].mask & 0x10)
5187 {
5188 animations[a].keyframePoses[frame][i].rotation.y += framedata[dcounter]*poses[i].channelscale[4];
5189 dcounter++;
5190 }
5191
5192 animations[a].keyframePoses[frame][i].rotation.z = poses[i].channeloffset[5];
5193
5194 if (poses[i].mask & 0x20)
5195 {
5196 animations[a].keyframePoses[frame][i].rotation.z += framedata[dcounter]*poses[i].channelscale[5];
5197 dcounter++;
5198 }
5199
5200 animations[a].keyframePoses[frame][i].rotation.w = poses[i].channeloffset[6];
5201
5202 if (poses[i].mask & 0x40)
5203 {
5204 animations[a].keyframePoses[frame][i].rotation.w += framedata[dcounter]*poses[i].channelscale[6];
5205 dcounter++;
5206 }
5207
5208 animations[a].keyframePoses[frame][i].scale.x = poses[i].channeloffset[7];
5209
5210 if (poses[i].mask & 0x80)
5211 {
5212 animations[a].keyframePoses[frame][i].scale.x += framedata[dcounter]*poses[i].channelscale[7];
5213 dcounter++;
5214 }
5215
5216 animations[a].keyframePoses[frame][i].scale.y = poses[i].channeloffset[8];
5217
5218 if (poses[i].mask & 0x100)
5219 {
5220 animations[a].keyframePoses[frame][i].scale.y += framedata[dcounter]*poses[i].channelscale[8];
5221 dcounter++;
5222 }
5223
5224 animations[a].keyframePoses[frame][i].scale.z = poses[i].channeloffset[9];
5225
5226 if (poses[i].mask & 0x200)
5227 {
5228 animations[a].keyframePoses[frame][i].scale.z += framedata[dcounter]*poses[i].channelscale[9];
5229 dcounter++;
5230 }
5231
5232 animations[a].keyframePoses[frame][i].rotation = QuaternionNormalize(animations[a].keyframePoses[frame][i].rotation);
5233 }
5234 }
5235
5236 // Build frameposes
5237 for (unsigned int frame = 0; frame < anim[a].num_frames; frame++)
5238 {
5239 for (int i = 0; i < animations[a].boneCount; i++)
5240 {
5241 if (bones[i].parent >= 0)
5242 {
5243 animations[a].keyframePoses[frame][i].rotation = QuaternionMultiply(animations[a].keyframePoses[frame][bones[i].parent].rotation, animations[a].keyframePoses[frame][i].rotation);
5244 animations[a].keyframePoses[frame][i].translation = Vector3RotateByQuaternion(animations[a].keyframePoses[frame][i].translation, animations[a].keyframePoses[frame][bones[i].parent].rotation);
5245 animations[a].keyframePoses[frame][i].translation = Vector3Add(animations[a].keyframePoses[frame][i].translation, animations[a].keyframePoses[frame][bones[i].parent].translation);
5246 animations[a].keyframePoses[frame][i].scale = Vector3Multiply(animations[a].keyframePoses[frame][i].scale, animations[a].keyframePoses[frame][bones[i].parent].scale);
5247 }
5248 }
5249 }
5250
5251 RL_FREE(bones);
5252 }
5253
5254 UnloadFileData(fileData);
5255
5256 RL_FREE(joints);
5257 RL_FREE(framedata);
5258 RL_FREE(poses);
5259 RL_FREE(anim);
5260
5261 return animations;
5262 }
5263
5264 #endif
5265
5266 #if SUPPORT_FILEFORMAT_GLTF
5267 // Load file data callback for cgltf
5268 static cgltf_result LoadFileGLTFCallback(const struct cgltf_memory_options *memoryOptions, const struct cgltf_file_options *fileOptions, const char *path, cgltf_size *size, void **data)
5269 {
5270 int filesize;
5271 unsigned char *filedata = LoadFileData(path, &filesize);
5272
5273 if (filedata == NULL) return cgltf_result_io_error;
5274
5275 *size = filesize;
5276 *data = filedata;
5277
5278 return cgltf_result_success;
5279 }
5280
5281 // Release file data callback for cgltf
5282 static void ReleaseFileGLTFCallback(const struct cgltf_memory_options *memoryOptions, const struct cgltf_file_options *fileOptions, void *data, cgltf_size size)
5283 {
5284 UnloadFileData((unsigned char *)data);
5285 }
5286
5287 // Load image from different glTF provided methods (uri, path, buffer_view)
5288 static Image LoadImageFromCgltfImage(cgltf_image *cgltfImage, const char *texPath)
5289 {
5290 Image image = { 0 };
5291
5292 if (cgltfImage == NULL) return image;
5293
5294 if (cgltfImage->uri != NULL) // Check if image data is provided as an uri (base64 or path)
5295 {
5296 if ((strlen(cgltfImage->uri) > 5) &&
5297 (cgltfImage->uri[0] == 'd') &&
5298 (cgltfImage->uri[1] == 'a') &&
5299 (cgltfImage->uri[2] == 't') &&
5300 (cgltfImage->uri[3] == 'a') &&
5301 (cgltfImage->uri[4] == ':')) // Check if image is provided as base64 text data
5302 {
5303 // Data URI Format: data:<mediatype>;base64,<data>
5304
5305 // Find the comma
5306 int i = 0;
5307 while ((cgltfImage->uri[i] != ',') && (cgltfImage->uri[i] != 0)) i++;
5308
5309 if (cgltfImage->uri[i] == 0) TRACELOG(LOG_WARNING, "IMAGE: glTF data URI is not a valid image");
5310 else
5311 {
5312 int base64Size = (int)strlen(cgltfImage->uri + i + 1);
5313 while (cgltfImage->uri[i + base64Size] == '=') base64Size--; // Ignore optional paddings
5314 int numberOfEncodedBits = base64Size*6 - (base64Size*6) % 8 ; // Encoded bits minus extra bits, so it becomes a multiple of 8 bits
5315 int outSize = numberOfEncodedBits/8 ; // Actual encoded bytes
5316 void *data = NULL;
5317
5318 cgltf_options options = { 0 };
5319 options.file.read = LoadFileGLTFCallback;
5320 options.file.release = ReleaseFileGLTFCallback;
5321 cgltf_result result = cgltf_load_buffer_base64(&options, outSize, cgltfImage->uri + i + 1, &data);
5322
5323 if (result == cgltf_result_success)
5324 {
5325 image = LoadImageFromMemory(".png", (unsigned char *)data, outSize);
5326 RL_FREE(data);
5327 }
5328 }
5329 }
5330 else // Check if image is provided as image path
5331 {
5332 image = LoadImage(TextFormat("%s/%s", texPath, cgltfImage->uri));
5333 }
5334 }
5335 else if ((cgltfImage->buffer_view != NULL) && (cgltfImage->buffer_view->buffer->data != NULL)) // Check if image is provided as data buffer
5336 {
5337 unsigned char *data = (unsigned char *)RL_MALLOC(cgltfImage->buffer_view->size);
5338 int offset = (int)cgltfImage->buffer_view->offset;
5339 int stride = (int)cgltfImage->buffer_view->stride? (int)cgltfImage->buffer_view->stride : 1;
5340
5341 // Copy buffer data to memory for loading
5342 for (unsigned int i = 0; i < cgltfImage->buffer_view->size; i++)
5343 {
5344 data[i] = ((unsigned char *)cgltfImage->buffer_view->buffer->data)[offset];
5345 offset += stride;
5346 }
5347
5348 // Check mime_type for image: (cgltfImage->mime_type == "image/png")
5349 // NOTE: Detected that some models define mime_type as "image\\/png"
5350 if ((strcmp(cgltfImage->mime_type, "image\\/png") == 0) || (strcmp(cgltfImage->mime_type, "image/png") == 0))
5351 {
5352 image = LoadImageFromMemory(".png", data, (int)cgltfImage->buffer_view->size);
5353 }
5354 else if ((strcmp(cgltfImage->mime_type, "image\\/jpeg") == 0) || (strcmp(cgltfImage->mime_type, "image/jpeg") == 0))
5355 {
5356 image = LoadImageFromMemory(".jpg", data, (int)cgltfImage->buffer_view->size);
5357 }
5358 else TRACELOG(LOG_WARNING, "MODEL: glTF image data MIME type not recognized", TextFormat("%s/%s", texPath, cgltfImage->uri));
5359
5360 RL_FREE(data);
5361 }
5362
5363 return image;
5364 }
5365
5366 // Load bone info from GLTF skin data
5367 static BoneInfo *LoadBoneInfoGLTF(cgltf_skin skin, int *boneCount)
5368 {
5369 *boneCount = (int)skin.joints_count;
5370 BoneInfo *bones = (BoneInfo *)RL_CALLOC(skin.joints_count, sizeof(BoneInfo));
5371
5372 for (unsigned int i = 0; i < skin.joints_count; i++)
5373 {
5374 cgltf_node node = *skin.joints[i];
5375 if (node.name != NULL) strncpy(bones[i].name, node.name, sizeof(bones[i].name) - 1);
5376
5377 // Find parent bone index
5378 int parentIndex = -1;
5379
5380 for (unsigned int j = 0; j < skin.joints_count; j++)
5381 {
5382 if (skin.joints[j] == node.parent)
5383 {
5384 parentIndex = (int)j;
5385 break;
5386 }
5387 }
5388
5389 bones[i].parent = parentIndex;
5390 }
5391
5392 return bones;
5393 }
5394
5395 // Load glTF file into model struct, .gltf and .glb supported
5396 static Model LoadGLTF(const char *fileName)
5397 {
5398 /*********************************************************************************************
5399
5400 Function implemented by Wilhem Barbier(@wbrbr), with modifications by Tyler Bezera(@gamerfiend)
5401 Transform handling implemented by Paul Melis (@paulmelis)
5402 Reviewed by Ramon Santamaria (@raysan5)
5403
5404 FEATURES:
5405 - Supports .gltf and .glb files
5406 - Supports embedded (base64) or external textures
5407 - Supports PBR metallic/roughness flow, loads material textures, values and colors
5408 PBR specular/glossiness flow and extended texture flows not supported
5409 - Supports multiple meshes per model (every primitives is loaded as a separate mesh)
5410 - Supports basic animations
5411 - Transforms, including parent-child relations, are applied on the mesh data,
5412 but the hierarchy is not kept (as it can't be represented)
5413 - Mesh instances in the glTF file (a.e. same mesh linked from multiple nodes)
5414 are turned into separate raylib Meshes
5415
5416 RESTRICTIONS:
5417 - Only triangle meshes supported
5418 - Vertex attribute types and formats supported:
5419 > Vertices (position): vec3: float
5420 > Normals: vec3: float
5421 > Texcoords: vec2: float
5422 > Colors: vec4: u8, u16, f32 (normalized)
5423 > Indices: u16, u32 (truncated to u16)
5424 - Scenes defined in the glTF file are ignored. All nodes in the file are used
5425
5426 ***********************************************************************************************/
5427
5428 // Macro to simplify attributes loading code
5429 #define LOAD_ATTRIBUTE(accesor, numComp, srcType, dstPtr) LOAD_ATTRIBUTE_CAST(accesor, numComp, srcType, dstPtr, srcType)
5430
5431 #define LOAD_ATTRIBUTE_CAST(accesor, numComp, srcType, dstPtr, dstType) \
5432 { \
5433 int n = 0; \
5434 srcType *buffer = (srcType *)accesor->buffer_view->buffer->data + accesor->buffer_view->offset/sizeof(srcType) + accesor->offset/sizeof(srcType); \
5435 for (unsigned int k = 0; k < accesor->count; k++) \
5436 {\
5437 for (int l = 0; l < numComp; l++) \
5438 {\
5439 dstPtr[numComp*k + l] = (dstType)buffer[n + l];\
5440 }\
5441 n += (int)(accesor->stride/sizeof(srcType));\
5442 }\
5443 }
5444
5445 Model model = { 0 };
5446
5447 // glTF file loading
5448 int dataSize = 0;
5449 unsigned char *fileData = LoadFileData(fileName, &dataSize);
5450
5451 if (fileData == NULL) return model;
5452
5453 // glTF data loading
5454 cgltf_options options = { 0 };
5455 options.file.read = LoadFileGLTFCallback;
5456 options.file.release = ReleaseFileGLTFCallback;
5457 cgltf_data *data = NULL;
5458 cgltf_result result = cgltf_parse(&options, fileData, dataSize, &data);
5459
5460 if (result == cgltf_result_success)
5461 {
5462 if (data->file_type == cgltf_file_type_glb) TRACELOG(LOG_INFO, "MODEL: [%s] Model basic data (glb) loaded successfully", fileName);
5463 else if (data->file_type == cgltf_file_type_gltf) TRACELOG(LOG_INFO, "MODEL: [%s] Model basic data (glTF) loaded successfully", fileName);
5464 else TRACELOG(LOG_WARNING, "MODEL: [%s] Model format not recognized", fileName);
5465
5466 TRACELOG(LOG_INFO, " > Meshes count: %i", data->meshes_count);
5467 TRACELOG(LOG_INFO, " > Materials count: %i (+1 default)", data->materials_count);
5468 TRACELOG(LOG_DEBUG, " > Buffers count: %i", data->buffers_count);
5469 TRACELOG(LOG_DEBUG, " > Images count: %i", data->images_count);
5470 TRACELOG(LOG_DEBUG, " > Textures count: %i", data->textures_count);
5471
5472 // Force reading data buffers (fills buffer_view->buffer->data)
5473 // NOTE: If an uri is defined to base64 data or external path, it's automatically loaded
5474 result = cgltf_load_buffers(&options, data, fileName);
5475 if (result != cgltf_result_success) TRACELOG(LOG_INFO, "MODEL: [%s] Failed to load mesh/material buffers", fileName);
5476
5477 int primitivesCount = 0;
5478 bool dracoCompression = false;
5479
5480 // NOTE: Load every primitive in the glTF as a separate raylib Mesh
5481 // Determine total number of meshes needed from the node hierarchy
5482 for (unsigned int i = 0; i < data->nodes_count; i++)
5483 {
5484 cgltf_node *node = &(data->nodes[i]);
5485 cgltf_mesh *mesh = node->mesh;
5486 if (!mesh) continue;
5487
5488 for (unsigned int p = 0; p < mesh->primitives_count; p++)
5489 {
5490 if (mesh->primitives[p].has_draco_mesh_compression)
5491 {
5492 dracoCompression = true;
5493 TRACELOG(LOG_WARNING, "MODEL: [%s] Failed to load mesh data, Draco compression not supported", fileName);
5494 break;
5495 }
5496 else if (mesh->primitives[p].type == cgltf_primitive_type_triangles) primitivesCount++;
5497 }
5498 }
5499
5500 if (dracoCompression)
5501 {
5502 TRACELOG(LOG_WARNING, "MODEL: [%s] Failed to load glTF data", fileName);
5503 cgltf_free(data);
5504 UnloadFileData(fileData);
5505 return model;
5506 }
5507
5508 TRACELOG(LOG_DEBUG, " > Primitives (triangles only) count based on hierarchy : %i", primitivesCount);
5509
5510 // Load our model data: meshes and materials
5511 model.meshCount = primitivesCount;
5512 model.meshes = (Mesh *)RL_CALLOC(model.meshCount, sizeof(Mesh));
5513
5514 // NOTE: Keep an extra slot for default material, in case some mesh requires it
5515 model.materialCount = (int)data->materials_count + 1;
5516 model.materials = (Material *)RL_CALLOC(model.materialCount, sizeof(Material));
5517 model.materials[0] = LoadMaterialDefault(); // Load default material (index: 0)
5518
5519 // Load mesh-material indices, by default all meshes are mapped to material index: 0
5520 model.meshMaterial = (int *)RL_CALLOC(model.meshCount, sizeof(int));
5521
5522 // Load materials data
5523 //----------------------------------------------------------------------------------------------------
5524 for (unsigned int i = 0, j = 1; i < data->materials_count; i++, j++)
5525 {
5526 model.materials[j] = LoadMaterialDefault();
5527 const char *texPath = GetDirectoryPath(fileName);
5528
5529 // Check glTF material flow: PBR metallic/roughness flow
5530 // NOTE: Alternatively, materials can follow PBR specular/glossiness flow
5531 if (data->materials[i].has_pbr_metallic_roughness)
5532 {
5533 // Load base color texture (albedo)
5534 if (data->materials[i].pbr_metallic_roughness.base_color_texture.texture)
5535 {
5536 Image imAlbedo = LoadImageFromCgltfImage(data->materials[i].pbr_metallic_roughness.base_color_texture.texture->image, texPath);
5537 if (imAlbedo.data != NULL)
5538 {
5539 model.materials[j].maps[MATERIAL_MAP_ALBEDO].texture = LoadTextureFromImage(imAlbedo);
5540 UnloadImage(imAlbedo);
5541 }
5542 }
5543 // Load base color factor (tint)
5544 model.materials[j].maps[MATERIAL_MAP_ALBEDO].color.r = (unsigned char)(data->materials[i].pbr_metallic_roughness.base_color_factor[0]*255);
5545 model.materials[j].maps[MATERIAL_MAP_ALBEDO].color.g = (unsigned char)(data->materials[i].pbr_metallic_roughness.base_color_factor[1]*255);
5546 model.materials[j].maps[MATERIAL_MAP_ALBEDO].color.b = (unsigned char)(data->materials[i].pbr_metallic_roughness.base_color_factor[2]*255);
5547 model.materials[j].maps[MATERIAL_MAP_ALBEDO].color.a = (unsigned char)(data->materials[i].pbr_metallic_roughness.base_color_factor[3]*255);
5548
5549 // Load metallic/roughness texture
5550 if (data->materials[i].pbr_metallic_roughness.metallic_roughness_texture.texture)
5551 {
5552 Image imMetallicRoughness = LoadImageFromCgltfImage(data->materials[i].pbr_metallic_roughness.metallic_roughness_texture.texture->image, texPath);
5553 if (imMetallicRoughness.data != NULL)
5554 {
5555 Image imMetallic = { 0 };
5556 Image imRoughness = { 0 };
5557
5558 imMetallic.data = RL_MALLOC(imMetallicRoughness.width*imMetallicRoughness.height);
5559 imRoughness.data = RL_MALLOC(imMetallicRoughness.width*imMetallicRoughness.height);
5560
5561 imMetallic.width = imRoughness.width = imMetallicRoughness.width;
5562 imMetallic.height = imRoughness.height = imMetallicRoughness.height;
5563
5564 imMetallic.format = imRoughness.format = PIXELFORMAT_UNCOMPRESSED_GRAYSCALE;
5565 imMetallic.mipmaps = imRoughness.mipmaps = 1;
5566
5567 for (int x = 0; x < imRoughness.width; x++)
5568 {
5569 for (int y = 0; y < imRoughness.height; y++)
5570 {
5571 Color color = GetImageColor(imMetallicRoughness, x, y);
5572
5573 ((unsigned char *)imRoughness.data)[y*imRoughness.width + x] = color.g; // Roughness color channel
5574 ((unsigned char *)imMetallic.data)[y*imMetallic.width + x] = color.b; // Metallic color channel
5575 }
5576 }
5577
5578 model.materials[j].maps[MATERIAL_MAP_ROUGHNESS].texture = LoadTextureFromImage(imRoughness);
5579 model.materials[j].maps[MATERIAL_MAP_METALNESS].texture = LoadTextureFromImage(imMetallic);
5580
5581 UnloadImage(imRoughness);
5582 UnloadImage(imMetallic);
5583 UnloadImage(imMetallicRoughness);
5584 }
5585
5586 // Load metallic/roughness material properties
5587 float roughness = data->materials[i].pbr_metallic_roughness.roughness_factor;
5588 model.materials[j].maps[MATERIAL_MAP_ROUGHNESS].value = roughness;
5589
5590 float metallic = data->materials[i].pbr_metallic_roughness.metallic_factor;
5591 model.materials[j].maps[MATERIAL_MAP_METALNESS].value = metallic;
5592 }
5593
5594 // Load normal texture
5595 if (data->materials[i].normal_texture.texture)
5596 {
5597 Image imNormal = LoadImageFromCgltfImage(data->materials[i].normal_texture.texture->image, texPath);
5598 if (imNormal.data != NULL)
5599 {
5600 model.materials[j].maps[MATERIAL_MAP_NORMAL].texture = LoadTextureFromImage(imNormal);
5601 UnloadImage(imNormal);
5602 }
5603 }
5604
5605 // Load ambient occlusion texture
5606 if (data->materials[i].occlusion_texture.texture)
5607 {
5608 Image imOcclusion = LoadImageFromCgltfImage(data->materials[i].occlusion_texture.texture->image, texPath);
5609 if (imOcclusion.data != NULL)
5610 {
5611 model.materials[j].maps[MATERIAL_MAP_OCCLUSION].texture = LoadTextureFromImage(imOcclusion);
5612 UnloadImage(imOcclusion);
5613 }
5614 }
5615
5616 // Load emissive texture
5617 if (data->materials[i].emissive_texture.texture)
5618 {
5619 Image imEmissive = LoadImageFromCgltfImage(data->materials[i].emissive_texture.texture->image, texPath);
5620 if (imEmissive.data != NULL)
5621 {
5622 model.materials[j].maps[MATERIAL_MAP_EMISSION].texture = LoadTextureFromImage(imEmissive);
5623 UnloadImage(imEmissive);
5624 }
5625
5626 // Load emissive color factor
5627 model.materials[j].maps[MATERIAL_MAP_EMISSION].color.r = (unsigned char)(data->materials[i].emissive_factor[0]*255);
5628 model.materials[j].maps[MATERIAL_MAP_EMISSION].color.g = (unsigned char)(data->materials[i].emissive_factor[1]*255);
5629 model.materials[j].maps[MATERIAL_MAP_EMISSION].color.b = (unsigned char)(data->materials[i].emissive_factor[2]*255);
5630 model.materials[j].maps[MATERIAL_MAP_EMISSION].color.a = 255;
5631 }
5632 }
5633
5634 // Other possible materials not supported by raylib pipeline:
5635 // has_clearcoat, has_transmission, has_volume, has_ior, has specular, has_sheen
5636 }
5637 //----------------------------------------------------------------------------------------------------
5638
5639 // Load meshes data
5640 //
5641 // NOTE: Visit each node in the hierarchy and process any mesh linked from it
5642 // - Each primitive within a glTF node becomes a raylib Mesh
5643 // - The local-to-world transform of each node is used to transform the points/normals/tangents of the created Mesh(es)
5644 // - Any glTF mesh linked from more than one Node (a.e. instancing) is turned into multiple Mesh's, as each Node will have its own transform applied
5645 //
5646 // WARNING: The code below disregards the scenes defined in the file, all nodes are used
5647 //----------------------------------------------------------------------------------------------------
5648 int meshIndex = 0;
5649 for (unsigned int i = 0; i < data->nodes_count; i++)
5650 {
5651 cgltf_node *node = &(data->nodes[i]);
5652
5653 cgltf_mesh *mesh = node->mesh;
5654 if (!mesh) continue;
5655
5656 cgltf_float worldTransform[16];
5657 cgltf_node_transform_world(node, worldTransform);
5658
5659 Matrix worldMatrix = {
5660 worldTransform[0], worldTransform[4], worldTransform[8], worldTransform[12],
5661 worldTransform[1], worldTransform[5], worldTransform[9], worldTransform[13],
5662 worldTransform[2], worldTransform[6], worldTransform[10], worldTransform[14],
5663 worldTransform[3], worldTransform[7], worldTransform[11], worldTransform[15]
5664 };
5665
5666 Matrix worldMatrixNormals = MatrixTranspose(MatrixInvert(worldMatrix));
5667
5668 for (unsigned int p = 0; p < mesh->primitives_count; p++)
5669 {
5670 // NOTE: Only support primitives defined by triangles
5671 // Other alternatives: points, lines, line_strip, triangle_strip
5672 if (mesh->primitives[p].type != cgltf_primitive_type_triangles) continue;
5673
5674 // NOTE: Attributes data could be provided in several data formats (8, 8u, 16u, 32...),
5675 // Only some formats for each attribute type are supported, read info at the top of this function!
5676
5677 for (unsigned int j = 0; j < mesh->primitives[p].attributes_count; j++)
5678 {
5679 // Check the different attributes for every primitive
5680 if (mesh->primitives[p].attributes[j].type == cgltf_attribute_type_position) // POSITION, vec3, float
5681 {
5682 cgltf_accessor *attribute = mesh->primitives[p].attributes[j].data;
5683
5684 // WARNING: SPECS: POSITION accessor MUST have its min and max properties defined
5685
5686 if (model.meshes[meshIndex].vertices != NULL) TRACELOG(LOG_WARNING, "MODEL: [%s] Vertices attribute data already loaded", fileName);
5687 else
5688 {
5689 if ((attribute->type == cgltf_type_vec3) && (attribute->component_type == cgltf_component_type_r_32f))
5690 {
5691 // Init raylib mesh vertices to copy glTF attribute data
5692 model.meshes[meshIndex].vertexCount = (int)attribute->count;
5693 model.meshes[meshIndex].vertices = (float *)RL_MALLOC(attribute->count*3*sizeof(float));
5694
5695 // Load 3 components of float data type into mesh.vertices
5696 LOAD_ATTRIBUTE(attribute, 3, float, model.meshes[meshIndex].vertices)
5697
5698 // Transform the vertices
5699 float *vertices = model.meshes[meshIndex].vertices;
5700 for (unsigned int k = 0; k < attribute->count; k++)
5701 {
5702 Vector3 vt = Vector3Transform((Vector3){ vertices[3*k], vertices[3*k+1], vertices[3*k+2] }, worldMatrix);
5703 vertices[3*k] = vt.x;
5704 vertices[3*k+1] = vt.y;
5705 vertices[3*k+2] = vt.z;
5706 }
5707 }
5708 else if ((attribute->type == cgltf_type_vec3) && (attribute->component_type == cgltf_component_type_r_16u))
5709 {
5710 // Init raylib mesh vertices to copy glTF attribute data
5711 model.meshes[meshIndex].vertexCount = (int)attribute->count;
5712 model.meshes[meshIndex].vertices = (float *)RL_MALLOC(attribute->count*3*sizeof(float));
5713
5714 // Load data into a temp buffer to be converted to raylib data type
5715 unsigned short *temp = (unsigned short *)RL_MALLOC(attribute->count*3*sizeof(unsigned short));
5716 LOAD_ATTRIBUTE(attribute, 3, unsigned short, temp);
5717
5718 // Convert data to raylib vertex data type (float) the matrix will scale it to the correct size as a float
5719 for (unsigned int t = 0; t < attribute->count*3; t++) model.meshes[meshIndex].vertices[t] = (float)temp[t];
5720
5721 RL_FREE(temp);
5722
5723 // Transform the vertices
5724 float *vertices = model.meshes[meshIndex].vertices;
5725 for (unsigned int k = 0; k < attribute->count; k++)
5726 {
5727 Vector3 vt = Vector3Transform((Vector3){ vertices[3*k], vertices[3*k + 1], vertices[3*k + 2] }, worldMatrix);
5728 vertices[3*k] = vt.x;
5729 vertices[3*k + 1] = vt.y;
5730 vertices[3*k + 2] = vt.z;
5731 }
5732 }
5733 else if ((attribute->type == cgltf_type_vec3) && (attribute->component_type == cgltf_component_type_r_16))
5734 {
5735 // Init raylib mesh vertices to copy glTF attribute data
5736 model.meshes[meshIndex].vertexCount = (int)attribute->count;
5737 model.meshes[meshIndex].vertices = (float *)RL_MALLOC(attribute->count*3*sizeof(float));
5738
5739 // Load data into a temp buffer to be converted to raylib data type
5740 short *temp = (short *)RL_MALLOC(attribute->count*3*sizeof(short));
5741 LOAD_ATTRIBUTE(attribute, 3, short, temp);
5742
5743 // Convert data to raylib vertex data type (float) the matrix will scale it to the correct size as a float
5744 for (unsigned int t = 0; t < attribute->count*3; t++) model.meshes[meshIndex].vertices[t] = (float)temp[t];
5745
5746 RL_FREE(temp);
5747
5748 // Transform the vertices
5749 float *vertices = model.meshes[meshIndex].vertices;
5750 for (unsigned int k = 0; k < attribute->count; k++)
5751 {
5752 Vector3 vt = Vector3Transform((Vector3){ vertices[3*k], vertices[3*k + 1], vertices[3*k + 2] }, worldMatrix);
5753 vertices[3*k] = vt.x;
5754 vertices[3*k + 1] = vt.y;
5755 vertices[3*k + 2] = vt.z;
5756 }
5757 }
5758 else TRACELOG(LOG_WARNING, "MODEL: [%s] Vertices attribute data format not supported, use vec3 float", fileName);
5759 }
5760 }
5761 else if (mesh->primitives[p].attributes[j].type == cgltf_attribute_type_normal) // NORMAL, vec3, float
5762 {
5763 cgltf_accessor *attribute = mesh->primitives[p].attributes[j].data;
5764
5765 if (model.meshes[meshIndex].normals != NULL) TRACELOG(LOG_WARNING, "MODEL: [%s] Normals attribute data already loaded", fileName);
5766 else
5767 {
5768 if ((attribute->type == cgltf_type_vec3) && (attribute->component_type == cgltf_component_type_r_32f))
5769 {
5770 // Init raylib mesh normals to copy glTF attribute data
5771 model.meshes[meshIndex].normals = (float *)RL_MALLOC(attribute->count*3*sizeof(float));
5772
5773 // Load 3 components of float data type into mesh.normals
5774 LOAD_ATTRIBUTE(attribute, 3, float, model.meshes[meshIndex].normals)
5775
5776 // Transform the normals
5777 float *normals = model.meshes[meshIndex].normals;
5778 for (unsigned int k = 0; k < attribute->count; k++)
5779 {
5780 Vector3 nt = Vector3Transform((Vector3){ normals[3*k], normals[3*k+1], normals[3*k+2] }, worldMatrixNormals);
5781 normals[3*k] = nt.x;
5782 normals[3*k+1] = nt.y;
5783 normals[3*k+2] = nt.z;
5784 }
5785 }
5786 else if ((attribute->type == cgltf_type_vec3) && (attribute->component_type == cgltf_component_type_r_16))
5787 {
5788 // Init raylib mesh normals to copy glTF attribute data
5789 model.meshes[meshIndex].normals = (float *)RL_MALLOC(attribute->count*3*sizeof(float));
5790
5791 // Load data into a temp buffer to be converted to raylib data type
5792 short *temp = (short *)RL_MALLOC(attribute->count*3*sizeof(short));
5793 LOAD_ATTRIBUTE(attribute, 3, short, temp);
5794
5795 // Convert data to raylib normal data type (float)
5796 for (unsigned int t = 0; t < attribute->count*3; t++) model.meshes[meshIndex].normals[t] = (float)temp[t];
5797
5798 RL_FREE(temp);
5799
5800 // Transform the normals
5801 float *normals = model.meshes[meshIndex].normals;
5802 for (unsigned int k = 0; k < attribute->count; k++)
5803 {
5804 Vector3 nt = Vector3Normalize(Vector3Transform((Vector3){ normals[3*k], normals[3*k + 1], normals[3*k + 2] }, worldMatrixNormals));
5805 normals[3*k] = nt.x;
5806 normals[3*k + 1] = nt.y;
5807 normals[3*k + 2] = nt.z;
5808 }
5809 }
5810 else if ((attribute->type == cgltf_type_vec3) && (attribute->component_type == cgltf_component_type_r_8u))
5811 {
5812 // Init raylib mesh normals to copy glTF attribute data
5813 model.meshes[meshIndex].normals = (float *)RL_MALLOC(attribute->count*3*sizeof(float));
5814
5815 // Load data into a temp buffer to be converted to raylib data type
5816 unsigned char *temp = (unsigned char *)RL_MALLOC(attribute->count*3*sizeof(unsigned char));
5817 LOAD_ATTRIBUTE(attribute, 3, unsigned char, temp);
5818
5819 // Convert data to raylib normal data type (float)
5820 for (unsigned int t = 0; t < attribute->count*3; t++) model.meshes[meshIndex].normals[t] = (float)temp[t];
5821
5822 RL_FREE(temp);
5823
5824 // Transform the normals
5825 float *normals = model.meshes[meshIndex].normals;
5826 for (unsigned int k = 0; k < attribute->count; k++)
5827 {
5828 Vector3 nt = Vector3Normalize(Vector3Transform((Vector3){ normals[3*k], normals[3*k + 1], normals[3*k + 2] }, worldMatrixNormals));
5829 normals[3*k] = nt.x;
5830 normals[3*k + 1] = nt.y;
5831 normals[3*k + 2] = nt.z;
5832 }
5833 }
5834 else if ((attribute->type == cgltf_type_vec3) && (attribute->component_type == cgltf_component_type_r_8))
5835 {
5836 // Init raylib mesh normals to copy glTF attribute data
5837 model.meshes[meshIndex].normals = (float *)RL_MALLOC(attribute->count*3*sizeof(float));
5838
5839 // Load data into a temp buffer to be converted to raylib data type
5840 char *temp = (char *)RL_MALLOC(attribute->count*3*sizeof(char));
5841 LOAD_ATTRIBUTE(attribute, 3, char, temp);
5842
5843 // Convert data to raylib normal data type (float)
5844 for (unsigned int t = 0; t < attribute->count*3; t++) model.meshes[meshIndex].normals[t] = (float)temp[t];
5845
5846 RL_FREE(temp);
5847
5848 // Transform the normals
5849 float *normals = model.meshes[meshIndex].normals;
5850 for (unsigned int k = 0; k < attribute->count; k++)
5851 {
5852 Vector3 nt = Vector3Normalize(Vector3Transform((Vector3){ normals[3*k], normals[3*k + 1], normals[3*k + 2] }, worldMatrixNormals));
5853 normals[3*k] = nt.x;
5854 normals[3*k + 1] = nt.y;
5855 normals[3*k + 2] = nt.z;
5856 }
5857 }
5858 else TRACELOG(LOG_WARNING, "MODEL: [%s] Normals attribute data format not supported, use vec3 float", fileName);
5859 }
5860 }
5861 else if (mesh->primitives[p].attributes[j].type == cgltf_attribute_type_tangent) // TANGENT, vec4, float, w is tangent basis sign
5862 {
5863 cgltf_accessor *attribute = mesh->primitives[p].attributes[j].data;
5864
5865 if (model.meshes[meshIndex].tangents != NULL) TRACELOG(LOG_WARNING, "MODEL: [%s] Tangents attribute data already loaded", fileName);
5866 else
5867 {
5868 if ((attribute->type == cgltf_type_vec4) && (attribute->component_type == cgltf_component_type_r_32f))
5869 {
5870 // Init raylib mesh tangent to copy glTF attribute data
5871 model.meshes[meshIndex].tangents = (float *)RL_MALLOC(attribute->count*4*sizeof(float));
5872
5873 // Load 4 components of float data type into mesh.tangents
5874 LOAD_ATTRIBUTE(attribute, 4, float, model.meshes[meshIndex].tangents)
5875
5876 // Transform the tangents
5877 float *tangents = model.meshes[meshIndex].tangents;
5878 for (unsigned int k = 0; k < attribute->count; k++)
5879 {
5880 Vector3 tt = Vector3Transform((Vector3){ tangents[4*k], tangents[4*k+1], tangents[4*k+2] }, worldMatrix);
5881 tangents[4*k] = tt.x;
5882 tangents[4*k+1] = tt.y;
5883 tangents[4*k+2] = tt.z;
5884 }
5885 }
5886 else TRACELOG(LOG_WARNING, "MODEL: [%s] Tangents attribute data format not supported, use vec4 float", fileName);
5887 }
5888 }
5889 else if (mesh->primitives[p].attributes[j].type == cgltf_attribute_type_texcoord) // TEXCOORD_n, vec2, float/u8n/u16n
5890 {
5891 // Support up to 2 texture coordinates attributes
5892 float *texcoordPtr = NULL;
5893
5894 cgltf_accessor *attribute = mesh->primitives[p].attributes[j].data;
5895
5896 if (attribute->type == cgltf_type_vec2)
5897 {
5898 if (attribute->component_type == cgltf_component_type_r_32f) // vec2, float
5899 {
5900 // Init raylib mesh texcoords to copy glTF attribute data
5901 texcoordPtr = (float *)RL_MALLOC(attribute->count*2*sizeof(float));
5902
5903 // Load 3 components of float data type into mesh.texcoords
5904 LOAD_ATTRIBUTE(attribute, 2, float, texcoordPtr)
5905 }
5906 else if (attribute->component_type == cgltf_component_type_r_8u) // vec2, u8n
5907 {
5908 // Init raylib mesh texcoords to copy glTF attribute data
5909 texcoordPtr = (float *)RL_MALLOC(attribute->count*2*sizeof(float));
5910
5911 // Load data into a temp buffer to be converted to raylib data type
5912 unsigned char *temp = (unsigned char *)RL_MALLOC(attribute->count*2*sizeof(unsigned char));
5913 LOAD_ATTRIBUTE(attribute, 2, unsigned char, temp);
5914
5915 // Convert data to raylib texcoord data type (float)
5916 for (unsigned int t = 0; t < attribute->count*2; t++) texcoordPtr[t] = (float)temp[t]/255.0f;
5917
5918 RL_FREE(temp);
5919 }
5920 else if (attribute->component_type == cgltf_component_type_r_16u) // vec2, u16n
5921 {
5922 // Init raylib mesh texcoords to copy glTF attribute data
5923 texcoordPtr = (float *)RL_MALLOC(attribute->count*2*sizeof(float));
5924
5925 // Load data into a temp buffer to be converted to raylib data type
5926 unsigned short *temp = (unsigned short *)RL_MALLOC(attribute->count*2*sizeof(unsigned short));
5927 LOAD_ATTRIBUTE(attribute, 2, unsigned short, temp);
5928
5929 // Convert data to raylib texcoord data type (float)
5930 for (unsigned int t = 0; t < attribute->count*2; t++) texcoordPtr[t] = (float)temp[t]/65535.0f;
5931
5932 RL_FREE(temp);
5933 }
5934 else TRACELOG(LOG_WARNING, "MODEL: [%s] Texcoords attribute data format not supported", fileName);
5935 }
5936 else TRACELOG(LOG_WARNING, "MODEL: [%s] Texcoords attribute data format not supported, use vec2 float", fileName);
5937
5938 int index = mesh->primitives[p].attributes[j].index;
5939 if (index == 0) model.meshes[meshIndex].texcoords = texcoordPtr;
5940 else if (index == 1) model.meshes[meshIndex].texcoords2 = texcoordPtr;
5941 else
5942 {
5943 TRACELOG(LOG_WARNING, "MODEL: [%s] No more than 2 texture coordinates attributes supported", fileName);
5944 if (texcoordPtr != NULL) RL_FREE(texcoordPtr);
5945 }
5946 }
5947 else if (mesh->primitives[p].attributes[j].type == cgltf_attribute_type_color) // COLOR_n, vec3/vec4, float/u8n/u16n
5948 {
5949 cgltf_accessor *attribute = mesh->primitives[p].attributes[j].data;
5950
5951 // WARNING: SPECS: All components of each COLOR_n accessor element MUST be clamped to [0.0, 1.0] range
5952
5953 if (model.meshes[meshIndex].colors != NULL) TRACELOG(LOG_WARNING, "MODEL: [%s] Colors attribute data already loaded", fileName);
5954 else
5955 {
5956 if (attribute->type == cgltf_type_vec3) // RGB
5957 {
5958 if (attribute->component_type == cgltf_component_type_r_8u)
5959 {
5960 // Init raylib mesh color to copy glTF attribute data
5961 model.meshes[meshIndex].colors = (unsigned char *)RL_MALLOC(attribute->count*4*sizeof(unsigned char));
5962
5963 // Load data into a temp buffer to be converted to raylib data type
5964 unsigned char *temp = (unsigned char *)RL_MALLOC(attribute->count*3*sizeof(unsigned char));
5965 LOAD_ATTRIBUTE(attribute, 3, unsigned char, temp);
5966
5967 // Convert data to raylib color data type (4 bytes)
5968 for (unsigned int c = 0, k = 0; c < (attribute->count*4 - 3); c += 4, k += 3)
5969 {
5970 model.meshes[meshIndex].colors[c] = temp[k];
5971 model.meshes[meshIndex].colors[c + 1] = temp[k + 1];
5972 model.meshes[meshIndex].colors[c + 2] = temp[k + 2];
5973 model.meshes[meshIndex].colors[c + 3] = 255;
5974 }
5975
5976 RL_FREE(temp);
5977 }
5978 else if (attribute->component_type == cgltf_component_type_r_16u)
5979 {
5980 // Init raylib mesh color to copy glTF attribute data
5981 model.meshes[meshIndex].colors = (unsigned char *)RL_MALLOC(attribute->count*4*sizeof(unsigned char));
5982
5983 // Load data into a temp buffer to be converted to raylib data type
5984 unsigned short *temp = (unsigned short *)RL_MALLOC(attribute->count*3*sizeof(unsigned short));
5985 LOAD_ATTRIBUTE(attribute, 3, unsigned short, temp);
5986
5987 // Convert data to raylib color data type (4 bytes)
5988 for (unsigned int c = 0, k = 0; c < (attribute->count*4 - 3); c += 4, k += 3)
5989 {
5990 model.meshes[meshIndex].colors[c] = (unsigned char)(((float)temp[k]/65535.0f)*255.0f);
5991 model.meshes[meshIndex].colors[c + 1] = (unsigned char)(((float)temp[k + 1]/65535.0f)*255.0f);
5992 model.meshes[meshIndex].colors[c + 2] = (unsigned char)(((float)temp[k + 2]/65535.0f)*255.0f);
5993 model.meshes[meshIndex].colors[c + 3] = 255;
5994 }
5995
5996 RL_FREE(temp);
5997 }
5998 else if (attribute->component_type == cgltf_component_type_r_32f)
5999 {
6000 // Init raylib mesh color to copy glTF attribute data
6001 model.meshes[meshIndex].colors = (unsigned char *)RL_MALLOC(attribute->count*4*sizeof(unsigned char));
6002
6003 // Load data into a temp buffer to be converted to raylib data type
6004 float *temp = (float *)RL_MALLOC(attribute->count*3*sizeof(float));
6005 LOAD_ATTRIBUTE(attribute, 3, float, temp);
6006
6007 // Convert data to raylib color data type (4 bytes)
6008 for (unsigned int c = 0, k = 0; c < (attribute->count*4 - 3); c += 4, k += 3)
6009 {
6010 model.meshes[meshIndex].colors[c] = (unsigned char)(temp[k]*255.0f);
6011 model.meshes[meshIndex].colors[c + 1] = (unsigned char)(temp[k + 1]*255.0f);
6012 model.meshes[meshIndex].colors[c + 2] = (unsigned char)(temp[k + 2]*255.0f);
6013 model.meshes[meshIndex].colors[c + 3] = 255;
6014 }
6015
6016 RL_FREE(temp);
6017 }
6018 else TRACELOG(LOG_WARNING, "MODEL: [%s] Color attribute data format not supported", fileName);
6019 }
6020 else if (attribute->type == cgltf_type_vec4) // RGBA
6021 {
6022 if (attribute->component_type == cgltf_component_type_r_8u)
6023 {
6024 // Init raylib mesh color to copy glTF attribute data
6025 model.meshes[meshIndex].colors = (unsigned char *)RL_MALLOC(attribute->count*4*sizeof(unsigned char));
6026
6027 // Load 4 components of unsigned char data type into mesh.colors
6028 LOAD_ATTRIBUTE(attribute, 4, unsigned char, model.meshes[meshIndex].colors)
6029 }
6030 else if (attribute->component_type == cgltf_component_type_r_16u)
6031 {
6032 // Init raylib mesh color to copy glTF attribute data
6033 model.meshes[meshIndex].colors = (unsigned char *)RL_MALLOC(attribute->count*4*sizeof(unsigned char));
6034
6035 // Load data into a temp buffer to be converted to raylib data type
6036 unsigned short *temp = (unsigned short *)RL_MALLOC(attribute->count*4*sizeof(unsigned short));
6037 LOAD_ATTRIBUTE(attribute, 4, unsigned short, temp);
6038
6039 // Convert data to raylib color data type (4 bytes)
6040 for (unsigned int c = 0; c < attribute->count*4; c++) model.meshes[meshIndex].colors[c] = (unsigned char)(((float)temp[c]/65535.0f)*255.0f);
6041
6042 RL_FREE(temp);
6043 }
6044 else if (attribute->component_type == cgltf_component_type_r_32f)
6045 {
6046 // Init raylib mesh color to copy glTF attribute data
6047 model.meshes[meshIndex].colors = (unsigned char *)RL_MALLOC(attribute->count*4*sizeof(unsigned char));
6048
6049 // Load data into a temp buffer to be converted to raylib data type
6050 float *temp = (float *)RL_MALLOC(attribute->count*4*sizeof(float));
6051 LOAD_ATTRIBUTE(attribute, 4, float, temp);
6052
6053 // Convert data to raylib color data type (4 bytes), color data must be normalized
6054 for (unsigned int c = 0; c < attribute->count*4; c++) model.meshes[meshIndex].colors[c] = (unsigned char)(temp[c]*255.0f);
6055
6056 RL_FREE(temp);
6057 }
6058 else TRACELOG(LOG_WARNING, "MODEL: [%s] Color attribute data format not supported", fileName);
6059 }
6060 else TRACELOG(LOG_WARNING, "MODEL: [%s] Color attribute data format not supported", fileName);
6061 }
6062 }
6063
6064 // NOTE: Attributes related to animations data are processed after mesh data loading
6065 }
6066
6067 // Load primitive indices data (if provided)
6068 if ((mesh->primitives[p].indices != NULL) && (mesh->primitives[p].indices->buffer_view != NULL))
6069 {
6070 cgltf_accessor *attribute = mesh->primitives[p].indices;
6071
6072 model.meshes[meshIndex].triangleCount = (int)attribute->count/3;
6073
6074 if (model.meshes[meshIndex].indices != NULL) TRACELOG(LOG_WARNING, "MODEL: [%s] Indices attribute data already loaded", fileName);
6075 else
6076 {
6077 if (attribute->component_type == cgltf_component_type_r_16u)
6078 {
6079 // Init raylib mesh indices to copy glTF attribute data
6080 model.meshes[meshIndex].indices = (unsigned short *)RL_MALLOC(attribute->count*sizeof(unsigned short));
6081
6082 // Load unsigned short data type into mesh.indices
6083 LOAD_ATTRIBUTE(attribute, 1, unsigned short, model.meshes[meshIndex].indices)
6084 }
6085 else if (attribute->component_type == cgltf_component_type_r_8u)
6086 {
6087 // Init raylib mesh indices to copy glTF attribute data
6088 model.meshes[meshIndex].indices = (unsigned short *)RL_MALLOC(attribute->count*sizeof(unsigned short));
6089 LOAD_ATTRIBUTE_CAST(attribute, 1, unsigned char, model.meshes[meshIndex].indices, unsigned short)
6090
6091 }
6092 else if (attribute->component_type == cgltf_component_type_r_32u)
6093 {
6094 // Init raylib mesh indices to copy glTF attribute data
6095 model.meshes[meshIndex].indices = (unsigned short *)RL_MALLOC(attribute->count*sizeof(unsigned short));
6096 LOAD_ATTRIBUTE_CAST(attribute, 1, unsigned int, model.meshes[meshIndex].indices, unsigned short);
6097
6098 TRACELOG(LOG_WARNING, "MODEL: [%s] Indices data converted from u32 to u16, possible loss of data", fileName);
6099 }
6100 else TRACELOG(LOG_WARNING, "MODEL: [%s] Indices data format not supported, use u16", fileName);
6101 }
6102 }
6103 else model.meshes[meshIndex].triangleCount = model.meshes[meshIndex].vertexCount/3; // Unindexed mesh
6104
6105 // Assign to the primitive mesh the corresponding material index
6106 // NOTE: If no material defined, mesh uses the already assigned default material (index: 0)
6107 for (unsigned int m = 0; m < data->materials_count; m++)
6108 {
6109 // The primitive actually keeps the pointer to the corresponding material,
6110 // raylib instead assigns to the mesh the by its index, as loaded in model.materials array
6111 // To get the index, check if material pointers match, and assign the corresponding index,
6112 // skipping index 0, the default material
6113 if (&data->materials[m] == mesh->primitives[p].material)
6114 {
6115 model.meshMaterial[meshIndex] = m + 1;
6116 break;
6117 }
6118 }
6119
6120 meshIndex++; // Move to next mesh
6121 }
6122 }
6123 //----------------------------------------------------------------------------------------------------
6124
6125 // Load animation data
6126 // REF: https://www.khronos.org/registry/glTF/specs/2.0/glTF-2.0.html#skins
6127 // REF: https://www.khronos.org/registry/glTF/specs/2.0/glTF-2.0.html#skinned-mesh-attributes
6128 //
6129 // LIMITATIONS:
6130 // - Only supports 1 armature per file, and skips loading it if there are multiple armatures
6131 // - Only supports linear interpolation (default method in Blender when checked "Always Sample Animations" when exporting a GLTF file)
6132 // - Only supports translation/rotation/scale animation channel.path, weights not considered (a.e. morph targets)
6133 //----------------------------------------------------------------------------------------------------
6134 if (data->skins_count > 0)
6135 {
6136 cgltf_skin skin = data->skins[0];
6137 model.skeleton.bones = LoadBoneInfoGLTF(skin, &model.skeleton.boneCount);
6138 model.skeleton.bindPose = (Transform *)RL_CALLOC(model.skeleton.boneCount, sizeof(Transform));
6139
6140 for (int i = 0; i < model.skeleton.boneCount; i++)
6141 {
6142 cgltf_node *node = skin.joints[i];
6143 cgltf_float worldTransform[16];
6144 cgltf_node_transform_world(node, worldTransform);
6145 Matrix worldMatrix = {
6146 worldTransform[0], worldTransform[4], worldTransform[8], worldTransform[12],
6147 worldTransform[1], worldTransform[5], worldTransform[9], worldTransform[13],
6148 worldTransform[2], worldTransform[6], worldTransform[10], worldTransform[14],
6149 worldTransform[3], worldTransform[7], worldTransform[11], worldTransform[15]
6150 };
6151
6152 MatrixDecompose(worldMatrix,
6153 &(model.skeleton.bindPose[i].translation),
6154 &(model.skeleton.bindPose[i].rotation),
6155 &(model.skeleton.bindPose[i].scale));
6156 }
6157
6158 if (data->skins_count > 1) TRACELOG(LOG_WARNING, "MODEL: [%s] can only load one skin (armature) per model, but gltf skins_count == %i", fileName, data->skins_count);
6159 }
6160
6161 meshIndex = 0;
6162 for (unsigned int i = 0; i < data->nodes_count; i++)
6163 {
6164 cgltf_node *node = &(data->nodes[i]);
6165
6166 cgltf_mesh *mesh = node->mesh;
6167 if (!mesh) continue;
6168
6169 for (unsigned int p = 0; p < mesh->primitives_count; p++)
6170 {
6171 bool hasJoints = false;
6172
6173 // NOTE: Only support primitives defined by triangles
6174 if (mesh->primitives[p].type != cgltf_primitive_type_triangles) continue;
6175
6176 for (unsigned int j = 0; j < mesh->primitives[p].attributes_count; j++)
6177 {
6178 // NOTE: JOINTS_1 + WEIGHT_1 will be used for +4 joints influencing a vertex -> Not supported by raylib
6179 if (mesh->primitives[p].attributes[j].type == cgltf_attribute_type_joints) // JOINTS_n (vec4: 4 bones max per vertex / u8, u16)
6180 {
6181 hasJoints = true;
6182 cgltf_accessor *attribute = mesh->primitives[p].attributes[j].data;
6183
6184 // NOTE: JOINTS_n can only be vec4 and u8/u16
6185 // SPECS: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes-overview
6186
6187 // WARNING: raylib only supports model.meshes[].boneIndices as u8 (unsigned char),
6188 // if data is provided in any other format, it is converted to supported format but
6189 // it could imply data loss (a warning message is issued in that case)
6190
6191 if (attribute->type == cgltf_type_vec4)
6192 {
6193 if (attribute->component_type == cgltf_component_type_r_8u)
6194 {
6195 // Init raylib mesh boneIndices to copy glTF attribute data
6196 model.meshes[meshIndex].boneIndices = (unsigned char *)RL_CALLOC(model.meshes[meshIndex].vertexCount*4, sizeof(unsigned char));
6197
6198 // Load attribute: vec4, u8 (unsigned char)
6199 LOAD_ATTRIBUTE(attribute, 4, unsigned char, model.meshes[meshIndex].boneIndices)
6200 }
6201 else if (attribute->component_type == cgltf_component_type_r_16u)
6202 {
6203 // Init raylib mesh boneIndices to copy glTF attribute data
6204 model.meshes[meshIndex].boneIndices = (unsigned char *)RL_CALLOC(model.meshes[meshIndex].vertexCount*4, sizeof(unsigned char));
6205
6206 // Load data into a temp buffer to be converted to raylib data type
6207 unsigned short *temp = (unsigned short *)RL_CALLOC(model.meshes[meshIndex].vertexCount*4, sizeof(unsigned short));
6208 LOAD_ATTRIBUTE(attribute, 4, unsigned short, temp);
6209
6210 // Convert data to raylib color data type (4 bytes)
6211 bool boneIdOverflowWarning = false;
6212 for (int b = 0; b < model.meshes[meshIndex].vertexCount*4; b++)
6213 {
6214 if ((temp[b] > 255) && !boneIdOverflowWarning)
6215 {
6216 TRACELOG(LOG_WARNING, "MODEL: [%s] Joint attribute data format (u16) overflow", fileName);
6217 boneIdOverflowWarning = true;
6218 }
6219
6220 // Despite the possible overflow, convert data to unsigned char
6221 model.meshes[meshIndex].boneIndices[b] = (unsigned char)temp[b];
6222 }
6223
6224 RL_FREE(temp);
6225 }
6226 else TRACELOG(LOG_WARNING, "MODEL: [%s] Joint attribute data format not supported", fileName);
6227 }
6228 else TRACELOG(LOG_WARNING, "MODEL: [%s] Joint attribute data format not supported", fileName);
6229 }
6230 else if (mesh->primitives[p].attributes[j].type == cgltf_attribute_type_weights) // WEIGHTS_n (vec4, u8n/u16n/f32)
6231 {
6232 cgltf_accessor *attribute = mesh->primitives[p].attributes[j].data;
6233
6234 if (attribute->type == cgltf_type_vec4)
6235 {
6236 if (attribute->component_type == cgltf_component_type_r_8u)
6237 {
6238 // Init raylib mesh bone weight to copy glTF attribute data
6239 model.meshes[meshIndex].boneWeights = (float *)RL_CALLOC(model.meshes[meshIndex].vertexCount*4, sizeof(float));
6240
6241 // Load data into a temp buffer to be converted to raylib data type
6242 unsigned char *temp = (unsigned char *)RL_MALLOC(attribute->count*4*sizeof(unsigned char));
6243 LOAD_ATTRIBUTE(attribute, 4, unsigned char, temp);
6244
6245 // Convert data to raylib bone weight data type (4 bytes)
6246 for (unsigned int b = 0; b < attribute->count*4; b++) model.meshes[meshIndex].boneWeights[b] = (float)temp[b]/255.0f;
6247
6248 RL_FREE(temp);
6249 }
6250 else if (attribute->component_type == cgltf_component_type_r_16u)
6251 {
6252 // Init raylib mesh bone weight to copy glTF attribute data
6253 model.meshes[meshIndex].boneWeights = (float *)RL_CALLOC(model.meshes[meshIndex].vertexCount*4, sizeof(float));
6254
6255 // Load data into a temp buffer to be converted to raylib data type
6256 unsigned short *temp = (unsigned short *)RL_MALLOC(attribute->count*4*sizeof(unsigned short));
6257 LOAD_ATTRIBUTE(attribute, 4, unsigned short, temp);
6258
6259 // Convert data to raylib bone weight data type
6260 for (unsigned int b = 0; b < attribute->count*4; b++) model.meshes[meshIndex].boneWeights[b] = (float)temp[b]/65535.0f;
6261
6262 RL_FREE(temp);
6263 }
6264 else if (attribute->component_type == cgltf_component_type_r_32f)
6265 {
6266 // Init raylib mesh bone weight to copy glTF attribute data
6267 model.meshes[meshIndex].boneWeights = (float *)RL_CALLOC(model.meshes[meshIndex].vertexCount*4, sizeof(float));
6268
6269 // Load 4 components of float data type into mesh.boneWeights
6270 // for cgltf_attribute_type_weights:
6271 // - data.meshes[0] (256 vertices)
6272 // - 256 values, provided as cgltf_type_vec4 of float (4 byte per joint, stride 16)
6273 LOAD_ATTRIBUTE(attribute, 4, float, model.meshes[meshIndex].boneWeights)
6274 }
6275 else TRACELOG(LOG_WARNING, "MODEL: [%s] Joint weight attribute data format not supported, use vec4 float", fileName);
6276 }
6277 else TRACELOG(LOG_WARNING, "MODEL: [%s] Joint weight attribute data format not supported, use vec4 float", fileName);
6278 }
6279 }
6280
6281 // Check if animated, and the mesh was not given any bone assignments, but is the child of a bone node
6282 // in this case, all the verts need to be attached to the parent bone so it will animate with the bone
6283 if ((data->skins_count > 0) && !hasJoints && (node->parent != NULL) && (node->parent->mesh == NULL))
6284 {
6285 int parentBoneId = -1;
6286 for (int joint = 0; joint < model.skeleton.boneCount; joint++)
6287 {
6288 if (data->skins[0].joints[joint] == node->parent)
6289 {
6290 parentBoneId = joint;
6291 break;
6292 }
6293 }
6294
6295 if (parentBoneId >= 0)
6296 {
6297 model.meshes[meshIndex].boneIndices = (unsigned char *)RL_CALLOC(model.meshes[meshIndex].vertexCount*4, sizeof(unsigned char));
6298 model.meshes[meshIndex].boneWeights = (float *)RL_CALLOC(model.meshes[meshIndex].vertexCount*4, sizeof(float));
6299
6300 for (int vertexIndex = 0; vertexIndex < model.meshes[meshIndex].vertexCount*4; vertexIndex += 4)
6301 {
6302 model.meshes[meshIndex].boneIndices[vertexIndex] = (unsigned char)parentBoneId;
6303 model.meshes[meshIndex].boneWeights[vertexIndex] = 1.0f;
6304 }
6305 }
6306 }
6307
6308 #if !SUPPORT_GPU_SKINNING
6309 // Animated vertex data (CPU skinning)
6310 model.meshes[meshIndex].animVertices = (float *)RL_CALLOC(model.meshes[meshIndex].vertexCount*3, sizeof(float));
6311 memcpy(model.meshes[meshIndex].animVertices, model.meshes[meshIndex].vertices, model.meshes[meshIndex].vertexCount*3*sizeof(float));
6312 model.meshes[meshIndex].animNormals = (float *)RL_CALLOC(model.meshes[meshIndex].vertexCount*3, sizeof(float));
6313 if (model.meshes[meshIndex].normals != NULL) memcpy(model.meshes[meshIndex].animNormals, model.meshes[meshIndex].normals, model.meshes[meshIndex].vertexCount*3*sizeof(float));
6314 #endif
6315 model.meshes[meshIndex].boneCount = model.skeleton.boneCount;
6316
6317 meshIndex++; // Move to next mesh
6318 }
6319 }
6320
6321 // Initialize runtime animation data: current pose and bone matrices
6322 model.currentPose = (Transform *)RL_CALLOC(model.skeleton.boneCount, sizeof(Transform));
6323 model.boneMatrices = (Matrix *)RL_CALLOC(model.skeleton.boneCount, sizeof(Matrix));
6324 for (int j = 0; j < model.skeleton.boneCount; j++) model.boneMatrices[j] = MatrixIdentity();
6325 //----------------------------------------------------------------------------------------------------
6326
6327 // Free unused allocated memory in case of no bones defined
6328 if (model.skeleton.boneCount == 0)
6329 {
6330 RL_FREE(model.currentPose);
6331 RL_FREE(model.boneMatrices);
6332 model.currentPose = NULL;
6333 model.boneMatrices = NULL;
6334 }
6335
6336 // Free all cgltf loaded data
6337 cgltf_free(data);
6338 }
6339 else TRACELOG(LOG_WARNING, "MODEL: [%s] Failed to load glTF data", fileName);
6340
6341 // WARNING: cgltf requires the file pointer available while reading data
6342 UnloadFileData(fileData);
6343
6344 return model;
6345 }
6346
6347 // Get interpolated pose for bone sampler at a specific time. Returns true on success
6348 static bool GetPoseAtTimeGLTF(cgltf_interpolation_type interpolationType, cgltf_accessor *input, cgltf_accessor *output, float time, void *data)
6349 {
6350 if (interpolationType >= cgltf_interpolation_type_max_enum) return false;
6351
6352 // Input and output should have the same count
6353 float tstart = 0.0f;
6354 float tend = 0.0f;
6355 int keyframe = 0; // Defaults to first pose
6356
6357 for (int i = 0; i < (int)input->count - 1; i++)
6358 {
6359 cgltf_bool r1 = cgltf_accessor_read_float(input, i, &tstart, 1);
6360 if (!r1) return false;
6361
6362 cgltf_bool r2 = cgltf_accessor_read_float(input, i + 1, &tend, 1);
6363 if (!r2) return false;
6364
6365 if ((tstart <= time) && (time < tend))
6366 {
6367 keyframe = i;
6368 break;
6369 }
6370 }
6371
6372 // Constant animation, no need to interpolate
6373 if (FloatEquals(tend, tstart))
6374 {
6375 interpolationType = cgltf_interpolation_type_step;
6376 }
6377
6378 float duration = fmaxf((tend - tstart), EPSILON);
6379 float t = (time - tstart)/duration;
6380 t = (t < 0.0f)? 0.0f : t;
6381 t = (t > 1.0f)? 1.0f : t;
6382
6383 if (output->component_type != cgltf_component_type_r_32f) return false;
6384
6385 if (output->type == cgltf_type_vec3)
6386 {
6387 switch (interpolationType)
6388 {
6389 case cgltf_interpolation_type_step:
6390 {
6391 float tmp[3] = { 0.0f };
6392 cgltf_accessor_read_float(output, keyframe, tmp, 3);
6393 Vector3 v1 = {tmp[0], tmp[1], tmp[2]};
6394 Vector3 *r = (Vector3 *)data;
6395
6396 *r = v1;
6397 } break;
6398 case cgltf_interpolation_type_linear:
6399 {
6400 float tmp[3] = { 0.0f };
6401 cgltf_accessor_read_float(output, keyframe, tmp, 3);
6402 Vector3 v1 = {tmp[0], tmp[1], tmp[2]};
6403 cgltf_accessor_read_float(output, keyframe+1, tmp, 3);
6404 Vector3 v2 = {tmp[0], tmp[1], tmp[2]};
6405 Vector3 *r = (Vector3 *)data;
6406
6407 *r = Vector3Lerp(v1, v2, t);
6408 } break;
6409 case cgltf_interpolation_type_cubic_spline:
6410 {
6411 float tmp[3] = { 0.0f };
6412 cgltf_accessor_read_float(output, 3*keyframe+1, tmp, 3);
6413 Vector3 v1 = {tmp[0], tmp[1], tmp[2]};
6414 cgltf_accessor_read_float(output, 3*keyframe+2, tmp, 3);
6415 Vector3 tangent1 = {tmp[0], tmp[1], tmp[2]};
6416 cgltf_accessor_read_float(output, 3*(keyframe+1)+1, tmp, 3);
6417 Vector3 v2 = {tmp[0], tmp[1], tmp[2]};
6418 cgltf_accessor_read_float(output, 3*(keyframe+1), tmp, 3);
6419 Vector3 tangent2 = {tmp[0], tmp[1], tmp[2]};
6420 Vector3 *r = (Vector3 *)data;
6421
6422 *r = Vector3CubicHermite(v1, tangent1, v2, tangent2, t);
6423 } break;
6424 default: break;
6425 }
6426 }
6427 else if (output->type == cgltf_type_vec4)
6428 {
6429 // Only v4 is for rotations, so it's a quaternion
6430 switch (interpolationType)
6431 {
6432 case cgltf_interpolation_type_step:
6433 {
6434 float tmp[4] = { 0.0f };
6435 cgltf_accessor_read_float(output, keyframe, tmp, 4);
6436 Vector4 v1 = {tmp[0], tmp[1], tmp[2], tmp[3]};
6437 Vector4 *r = (Vector4 *)data;
6438
6439 *r = v1;
6440 } break;
6441 case cgltf_interpolation_type_linear:
6442 {
6443 float tmp[4] = { 0.0f };
6444 cgltf_accessor_read_float(output, keyframe, tmp, 4);
6445 Vector4 v1 = {tmp[0], tmp[1], tmp[2], tmp[3]};
6446 cgltf_accessor_read_float(output, keyframe+1, tmp, 4);
6447 Vector4 v2 = {tmp[0], tmp[1], tmp[2], tmp[3]};
6448 Vector4 *r = (Vector4 *)data;
6449
6450 *r = QuaternionSlerp(v1, v2, t);
6451 } break;
6452 case cgltf_interpolation_type_cubic_spline:
6453 {
6454 float tmp[4] = { 0.0f };
6455 cgltf_accessor_read_float(output, 3*keyframe+1, tmp, 4);
6456 Vector4 v1 = {tmp[0], tmp[1], tmp[2], tmp[3]};
6457 cgltf_accessor_read_float(output, 3*keyframe+2, tmp, 4);
6458 Vector4 outTangent1 = {tmp[0], tmp[1], tmp[2], 0.0f};
6459 cgltf_accessor_read_float(output, 3*(keyframe+1)+1, tmp, 4);
6460 Vector4 v2 = {tmp[0], tmp[1], tmp[2], tmp[3]};
6461 cgltf_accessor_read_float(output, 3*(keyframe+1), tmp, 4);
6462 Vector4 inTangent2 = {tmp[0], tmp[1], tmp[2], 0.0f};
6463 Vector4 *r = (Vector4 *)data;
6464
6465 v1 = QuaternionNormalize(v1);
6466 v2 = QuaternionNormalize(v2);
6467
6468 if (Vector4DotProduct(v1, v2) < 0.0f)
6469 {
6470 v2 = Vector4Negate(v2);
6471 }
6472
6473 outTangent1 = Vector4Scale(outTangent1, duration);
6474 inTangent2 = Vector4Scale(inTangent2, duration);
6475
6476 *r = QuaternionCubicHermiteSpline(v1, outTangent1, v2, inTangent2, t);
6477 } break;
6478 default: break;
6479 }
6480 }
6481
6482 return true;
6483 }
6484
6485 #define GLTF_FRAMERATE 60.0f // glTF animation framerate (frames per second)
6486
6487 static ModelAnimation *LoadModelAnimationsGLTF(const char *fileName, int *animCount)
6488 {
6489 // glTF file loading
6490 int dataSize = 0;
6491 unsigned char *fileData = LoadFileData(fileName, &dataSize);
6492
6493 ModelAnimation *animations = NULL;
6494
6495 // glTF data loading
6496 cgltf_options options = { 0 };
6497 options.file.read = LoadFileGLTFCallback;
6498 options.file.release = ReleaseFileGLTFCallback;
6499 cgltf_data *data = NULL;
6500 cgltf_result result = cgltf_parse(&options, fileData, dataSize, &data);
6501
6502 if (result != cgltf_result_success)
6503 {
6504 TRACELOG(LOG_WARNING, "MODEL: [%s] Failed to load glTF data", fileName);
6505 *animCount = 0;
6506 return NULL;
6507 }
6508
6509 result = cgltf_load_buffers(&options, data, fileName);
6510 if (result != cgltf_result_success) TRACELOG(LOG_INFO, "MODEL: [%s] Failed to load animation buffers", fileName);
6511
6512 if (result == cgltf_result_success)
6513 {
6514 if (data->skins_count > 0)
6515 {
6516 cgltf_skin skin = data->skins[0];
6517 *animCount = (int)data->animations_count;
6518 animations = (ModelAnimation *)RL_CALLOC(data->animations_count, sizeof(ModelAnimation));
6519
6520 Transform worldTransform = { 0 };
6521 cgltf_float cgltf_worldTransform[16] = { 0 };
6522 cgltf_node *node = skin.joints[0];
6523 cgltf_node_transform_world(node->parent, cgltf_worldTransform);
6524 Matrix worldMatrix = {
6525 cgltf_worldTransform[0], cgltf_worldTransform[4], cgltf_worldTransform[8], cgltf_worldTransform[12],
6526 cgltf_worldTransform[1], cgltf_worldTransform[5], cgltf_worldTransform[9], cgltf_worldTransform[13],
6527 cgltf_worldTransform[2], cgltf_worldTransform[6], cgltf_worldTransform[10], cgltf_worldTransform[14],
6528 cgltf_worldTransform[3], cgltf_worldTransform[7], cgltf_worldTransform[11], cgltf_worldTransform[15]
6529 };
6530 MatrixDecompose(worldMatrix, &worldTransform.translation, &worldTransform.rotation, &worldTransform.scale);
6531
6532 for (unsigned int a = 0; a < data->animations_count; a++)
6533 {
6534 BoneInfo *bones = LoadBoneInfoGLTF(skin, &animations[a].boneCount);
6535
6536 cgltf_animation animData = data->animations[a];
6537
6538 struct Channels {
6539 cgltf_animation_channel *translate;
6540 cgltf_animation_channel *rotate;
6541 cgltf_animation_channel *scale;
6542 cgltf_interpolation_type interpolationType;
6543 };
6544
6545 struct Channels *boneChannels = (struct Channels *)RL_CALLOC(animations[a].boneCount, sizeof(struct Channels));
6546 float animDuration = 0.0f;
6547
6548 for (unsigned int j = 0; j < animData.channels_count; j++)
6549 {
6550 cgltf_animation_channel channel = animData.channels[j];
6551 int boneIndex = -1;
6552
6553 for (unsigned int k = 0; k < skin.joints_count; k++)
6554 {
6555 if (animData.channels[j].target_node == skin.joints[k])
6556 {
6557 boneIndex = k;
6558 break;
6559 }
6560 }
6561
6562 if (boneIndex == -1) continue; // Animation channel for a node not in the skeleton
6563
6564 boneChannels[boneIndex].interpolationType = animData.channels[j].sampler->interpolation;
6565
6566 if (animData.channels[j].sampler->interpolation != cgltf_interpolation_type_max_enum)
6567 {
6568 if (channel.target_path == cgltf_animation_path_type_translation)
6569 {
6570 boneChannels[boneIndex].translate = &animData.channels[j];
6571 }
6572 else if (channel.target_path == cgltf_animation_path_type_rotation)
6573 {
6574 boneChannels[boneIndex].rotate = &animData.channels[j];
6575 }
6576 else if (channel.target_path == cgltf_animation_path_type_scale)
6577 {
6578 boneChannels[boneIndex].scale = &animData.channels[j];
6579 }
6580 else
6581 {
6582 TRACELOG(LOG_WARNING, "MODEL: [%s] Unsupported target_path on channel %d's sampler for animation %d. Skipping.", fileName, j, a);
6583 }
6584 }
6585 else TRACELOG(LOG_WARNING, "MODEL: [%s] Invalid interpolation curve encountered for GLTF animation.", fileName);
6586
6587 float time = 0.0f;
6588 cgltf_bool result = cgltf_accessor_read_float(channel.sampler->input, channel.sampler->input->count - 1, &time, 1);
6589
6590 if (!result)
6591 {
6592 TRACELOG(LOG_WARNING, "MODEL: [%s] Failed to load input time", fileName);
6593 continue;
6594 }
6595
6596 animDuration = (time > animDuration)? time : animDuration;
6597 }
6598
6599 if (animData.name != NULL) strncpy(animations[a].name, animData.name, sizeof(animations[a].name) - 1);
6600
6601 animations[a].keyframeCount = (int)(animDuration*GLTF_FRAMERATE) + 1;
6602 animations[a].keyframePoses = (Transform **)RL_CALLOC(animations[a].keyframeCount, sizeof(Transform *));
6603
6604 for (int j = 0; j < animations[a].keyframeCount; j++)
6605 {
6606 animations[a].keyframePoses[j] = (Transform *)RL_CALLOC(animations[a].boneCount, sizeof(Transform));
6607 float time = (float)j / GLTF_FRAMERATE;
6608
6609 for (int k = 0; k < animations[a].boneCount; k++)
6610 {
6611 Vector3 translation = {skin.joints[k]->translation[0], skin.joints[k]->translation[1], skin.joints[k]->translation[2]};
6612 Quaternion rotation = {skin.joints[k]->rotation[0], skin.joints[k]->rotation[1], skin.joints[k]->rotation[2], skin.joints[k]->rotation[3]};
6613 Vector3 scale = {skin.joints[k]->scale[0], skin.joints[k]->scale[1], skin.joints[k]->scale[2]};
6614
6615 if (boneChannels[k].translate)
6616 {
6617 if (!GetPoseAtTimeGLTF(boneChannels[k].interpolationType, boneChannels[k].translate->sampler->input, boneChannels[k].translate->sampler->output, time, &translation))
6618 {
6619 TRACELOG(LOG_INFO, "MODEL: [%s] Failed to load translate pose data for bone %s", fileName, bones[k].name);
6620 }
6621 }
6622
6623 if (boneChannels[k].rotate)
6624 {
6625 if (!GetPoseAtTimeGLTF(boneChannels[k].interpolationType, boneChannels[k].rotate->sampler->input, boneChannels[k].rotate->sampler->output, time, &rotation))
6626 {
6627 TRACELOG(LOG_INFO, "MODEL: [%s] Failed to load rotate pose data for bone %s", fileName, bones[k].name);
6628 }
6629 }
6630
6631 if (boneChannels[k].scale)
6632 {
6633 if (!GetPoseAtTimeGLTF(boneChannels[k].interpolationType, boneChannels[k].scale->sampler->input, boneChannels[k].scale->sampler->output, time, &scale))
6634 {
6635 TRACELOG(LOG_INFO, "MODEL: [%s] Failed to load scale pose data for bone %s", fileName, bones[k].name);
6636 }
6637 }
6638
6639 animations[a].keyframePoses[j][k] = (Transform){
6640 .translation = translation,
6641 .rotation = rotation,
6642 .scale = scale
6643 };
6644 }
6645
6646 Transform *root = &animations[a].keyframePoses[j][0];
6647 root->rotation = QuaternionMultiply(worldTransform.rotation, root->rotation);
6648 root->scale = Vector3Multiply(root->scale, worldTransform.scale);
6649 root->translation = Vector3Multiply(root->translation, worldTransform.scale);
6650 root->translation = Vector3RotateByQuaternion(root->translation, worldTransform.rotation);
6651 root->translation = Vector3Add(root->translation, worldTransform.translation);
6652
6653 BuildPoseFromParentJoints(bones, animations[a].boneCount, animations[a].keyframePoses[j]);
6654 }
6655
6656 TRACELOG(LOG_INFO, "MODEL: [%s] Loaded animation: %s | Frames: %d | Duration: %fs", fileName, (animData.name != NULL)? animData.name : "NULL", animations[a].keyframeCount, animDuration);
6657 RL_FREE(boneChannels);
6658 RL_FREE(bones);
6659 }
6660 }
6661
6662 if (data->skins_count > 1)
6663 {
6664 TRACELOG(LOG_WARNING, "MODEL: [%s] Expected one unique skin to load animation data from, but found %i", fileName, data->skins_count);
6665 }
6666
6667 cgltf_free(data);
6668 }
6669
6670 UnloadFileData(fileData);
6671
6672 return animations;
6673 }
6674 #endif
6675
6676 #if SUPPORT_FILEFORMAT_VOX
6677 // Load VOX (MagicaVoxel) mesh data
6678 static Model LoadVOX(const char *fileName)
6679 {
6680 Model model = { 0 };
6681
6682 int nbvertices = 0;
6683 int meshescount = 0;
6684
6685 // Read vox file into buffer
6686 int dataSize = 0;
6687 unsigned char *fileData = LoadFileData(fileName, &dataSize);
6688
6689 if (fileData == 0)
6690 {
6691 TRACELOG(LOG_WARNING, "MODEL: [%s] Failed to load VOX file", fileName);
6692 return model;
6693 }
6694
6695 // Read and build voxarray description
6696 VoxArray3D voxarray = { 0 };
6697 int ret = Vox_LoadFromMemory(fileData, dataSize, &voxarray);
6698
6699 if (ret != VOX_SUCCESS)
6700 {
6701 // Error
6702 UnloadFileData(fileData);
6703
6704 TRACELOG(LOG_WARNING, "MODEL: [%s] Failed to load VOX data", fileName);
6705 return model;
6706 }
6707 else
6708 {
6709 // Success: Compute meshes count
6710 nbvertices = voxarray.vertices.used;
6711 meshescount = 1 + (nbvertices/65536);
6712
6713 TRACELOG(LOG_INFO, "MODEL: [%s] VOX data loaded successfully : %i vertices/%i meshes", fileName, nbvertices, meshescount);
6714 }
6715
6716 // Build models from meshes
6717 model.transform = MatrixIdentity();
6718
6719 model.meshCount = meshescount;
6720 model.meshes = (Mesh *)RL_CALLOC(model.meshCount, sizeof(Mesh));
6721
6722 model.meshMaterial = (int *)RL_CALLOC(model.meshCount, sizeof(int));
6723
6724 model.materialCount = 1;
6725 model.materials = (Material *)RL_CALLOC(model.materialCount, sizeof(Material));
6726 model.materials[0] = LoadMaterialDefault();
6727
6728 // Init model meshes
6729 int verticesRemain = voxarray.vertices.used;
6730 int verticesMax = 65532; // 5461 voxels x 12 vertices per voxel -> 65532 (must be inf 65536)
6731
6732 // 6*4 = 12 vertices per voxel
6733 Vector3 *pvertices = (Vector3 *)voxarray.vertices.array;
6734 Vector3 *pnormals = (Vector3 *)voxarray.normals.array;
6735 Color *pcolors = (Color *)voxarray.colors.array;
6736
6737 unsigned short *pindices = voxarray.indices.array; // 5461*6*6 = 196596 indices max per mesh
6738
6739 int size = 0;
6740
6741 for (int i = 0; i < meshescount; i++)
6742 {
6743 Mesh *pmesh = &model.meshes[i];
6744 memset(pmesh, 0, sizeof(Mesh));
6745
6746 // Copy vertices
6747 pmesh->vertexCount = (int)fmin(verticesMax, verticesRemain);
6748
6749 size = pmesh->vertexCount*sizeof(float)*3;
6750 pmesh->vertices = (float *)RL_MALLOC(size);
6751 memcpy(pmesh->vertices, pvertices, size);
6752
6753 // Copy normals
6754 pmesh->normals = (float *)RL_MALLOC(size);
6755 memcpy(pmesh->normals, pnormals, size);
6756
6757 // Copy indices
6758 size = voxarray.indices.used*sizeof(unsigned short);
6759 pmesh->indices = (unsigned short *)RL_MALLOC(size);
6760 memcpy(pmesh->indices, pindices, size);
6761
6762 pmesh->triangleCount = (pmesh->vertexCount/4)*2;
6763
6764 // Copy colors
6765 size = pmesh->vertexCount*sizeof(Color);
6766 pmesh->colors = (unsigned char *)RL_MALLOC(size);
6767 memcpy(pmesh->colors, pcolors, size);
6768
6769 // First material index
6770 model.meshMaterial[i] = 0;
6771
6772 verticesRemain -= verticesMax;
6773 pvertices += verticesMax;
6774 pnormals += verticesMax;
6775 pcolors += verticesMax;
6776 }
6777
6778 // Free buffers
6779 Vox_FreeArrays(&voxarray);
6780 UnloadFileData(fileData);
6781
6782 return model;
6783 }
6784 #endif
6785
6786 #if SUPPORT_FILEFORMAT_M3D
6787 // Hook LoadFileData()/UnloadFileData() calls to M3D loaders
6788 unsigned char *m3d_loaderhook(char *fn, unsigned int *len) { return LoadFileData((const char *)fn, (int *)len); }
6789 void m3d_freehook(void *data) { UnloadFileData((unsigned char *)data); }
6790
6791 // Load M3D mesh data
6792 static Model LoadM3D(const char *fileName)
6793 {
6794 Model model = { 0 };
6795
6796 m3d_t *m3d = NULL;
6797 m3dp_t *prop = NULL;
6798 int i, j, k, l, n, mi = -2, vcolor = 0;
6799
6800 int dataSize = 0;
6801 unsigned char *fileData = LoadFileData(fileName, &dataSize);
6802
6803 if (fileData != NULL)
6804 {
6805 m3d = m3d_load(fileData, m3d_loaderhook, m3d_freehook, NULL);
6806
6807 if (!m3d || M3D_ERR_ISFATAL(m3d->errcode))
6808 {
6809 TRACELOG(LOG_WARNING, "MODEL: [%s] Failed to load M3D data, error code %d", fileName, m3d? m3d->errcode : -2);
6810 if (m3d) m3d_free(m3d);
6811 UnloadFileData(fileData);
6812 return model;
6813 }
6814 else TRACELOG(LOG_INFO, "MODEL: [%s] M3D data loaded successfully: %i faces/%i materials", fileName, m3d->numface, m3d->nummaterial);
6815
6816 // Check if face is found, if not, probably just a material library
6817 if (!m3d->numface)
6818 {
6819 m3d_free(m3d);
6820 UnloadFileData(fileData);
6821 return model;
6822 }
6823
6824 if (m3d->nummaterial > 0)
6825 {
6826 model.meshCount = model.materialCount = m3d->nummaterial;
6827 TRACELOG(LOG_INFO, "MODEL: model has %i material meshes", model.materialCount);
6828 }
6829 else
6830 {
6831 model.meshCount = 1; model.materialCount = 0;
6832 TRACELOG(LOG_INFO, "MODEL: No materials, putting all meshes in a default material");
6833 }
6834
6835 // A default material is always required, so adding +1
6836 model.materialCount++;
6837
6838 // Faces must be in non-decreasing materialid order. Verify that quickly, sorting them otherwise
6839 // WARNING: Sorting is not needed, valid M3D model files should already be sorted
6840 // Keeping the sorting function for reference (Check PR #3363 #3385)
6841 /*
6842 for (a = 1; a < m3d->numface; a++)
6843 {
6844 if (m3d->face[a-1].materialid <= m3d->face[a].materialid) continue;
6845
6846 // face[a-1] > face[a]. slide face[a] lower
6847 m3df_t slider = m3d->face[a];
6848 j = a-1;
6849
6850 do
6851 { // face[j] > slider, face[j+1] is svailable vacant gap
6852 m3d->face[j+1] = m3d->face[j];
6853 j = j-1;
6854 }
6855 while (j >= 0 && m3d->face[j].materialid > slider.materialid);
6856
6857 m3d->face[j+1] = slider;
6858 }
6859 */
6860
6861 model.meshes = (Mesh *)RL_CALLOC(model.meshCount, sizeof(Mesh));
6862 model.meshMaterial = (int *)RL_CALLOC(model.meshCount, sizeof(int));
6863 model.materials = (Material *)RL_CALLOC(model.materialCount + 1, sizeof(Material));
6864
6865 // Map no material to index 0 with default shader, everything else materialid + 1
6866 model.materials[0] = LoadMaterialDefault();
6867
6868 for (i = l = 0, k = -1; i < (int)m3d->numface; i++, l++)
6869 {
6870 // Materials are grouped together
6871 if (mi != m3d->face[i].materialid)
6872 {
6873 // There should be only one material switch per material kind,
6874 // but be bulletproof for non-optimal model files
6875 if (k + 1 >= model.meshCount)
6876 {
6877 model.meshCount++;
6878
6879 // Create a second buffer for mesh re-allocation
6880 Mesh *tempMeshes = (Mesh *)RL_CALLOC(model.meshCount, sizeof(Mesh));
6881 memcpy(tempMeshes, model.meshes, (model.meshCount - 1)*sizeof(Mesh));
6882 RL_FREE(model.meshes);
6883 model.meshes = tempMeshes;
6884
6885 // Create a second buffer for material re-allocation
6886 int *tempMeshMaterial = (int *)RL_CALLOC(model.meshCount, sizeof(int));
6887 memcpy(tempMeshMaterial, model.meshMaterial, (model.meshCount - 1)*sizeof(int));
6888 RL_FREE(model.meshMaterial);
6889 model.meshMaterial = tempMeshMaterial;
6890 }
6891
6892 k++;
6893 mi = m3d->face[i].materialid;
6894
6895 // Only allocate colors VertexBuffer if there's a color vertex in the model for this material batch
6896 // if all colors are fully transparent black for all vertices of this material, then assuming no vertex colors
6897 for (j = i, l = vcolor = 0; (j < (int)m3d->numface) && (mi == m3d->face[j].materialid); j++, l++)
6898 {
6899 if (!m3d->vertex[m3d->face[j].vertex[0]].color ||
6900 !m3d->vertex[m3d->face[j].vertex[1]].color ||
6901 !m3d->vertex[m3d->face[j].vertex[2]].color) vcolor = 1;
6902 }
6903
6904 model.meshes[k].vertexCount = l*3;
6905 model.meshes[k].triangleCount = l;
6906 model.meshes[k].vertices = (float *)RL_CALLOC(model.meshes[k].vertexCount*3, sizeof(float));
6907 model.meshes[k].texcoords = (float *)RL_CALLOC(model.meshes[k].vertexCount*2, sizeof(float));
6908 model.meshes[k].normals = (float *)RL_CALLOC(model.meshes[k].vertexCount*3, sizeof(float));
6909
6910 // If no map is provided, or colors are defined, allocate storage for vertex colors
6911 // M3D specs only consider vertex colors if no material is provided, however raylib uses both and mixes the colors
6912 if ((mi == M3D_UNDEF) || vcolor) model.meshes[k].colors = (unsigned char *)RL_CALLOC(model.meshes[k].vertexCount*4, sizeof(unsigned char));
6913
6914 // If no map is provided and vertex colors are allocated, set them to white
6915 if ((mi == M3D_UNDEF) && (model.meshes[k].colors != NULL))
6916 {
6917 for (int c = 0; c < model.meshes[k].vertexCount*4; c++) model.meshes[k].colors[c] = 255;
6918 }
6919
6920 if (m3d->numbone && m3d->numskin)
6921 {
6922 model.meshes[k].boneIndices = (unsigned char *)RL_CALLOC(model.meshes[k].vertexCount*4, sizeof(unsigned char));
6923 model.meshes[k].boneWeights = (float *)RL_CALLOC(model.meshes[k].vertexCount*4, sizeof(float));
6924 #if !SUPPORT_GPU_SKINNING
6925 model.meshes[k].animVertices = (float *)RL_CALLOC(model.meshes[k].vertexCount*3, sizeof(float));
6926 model.meshes[k].animNormals = (float *)RL_CALLOC(model.meshes[k].vertexCount*3, sizeof(float));
6927 #endif
6928 }
6929
6930 model.meshMaterial[k] = mi + 1;
6931 l = 0;
6932 }
6933
6934 // Process meshes per material, add triangles
6935 model.meshes[k].vertices[l*9 + 0] = m3d->vertex[m3d->face[i].vertex[0]].x*m3d->scale;
6936 model.meshes[k].vertices[l*9 + 1] = m3d->vertex[m3d->face[i].vertex[0]].y*m3d->scale;
6937 model.meshes[k].vertices[l*9 + 2] = m3d->vertex[m3d->face[i].vertex[0]].z*m3d->scale;
6938 model.meshes[k].vertices[l*9 + 3] = m3d->vertex[m3d->face[i].vertex[1]].x*m3d->scale;
6939 model.meshes[k].vertices[l*9 + 4] = m3d->vertex[m3d->face[i].vertex[1]].y*m3d->scale;
6940 model.meshes[k].vertices[l*9 + 5] = m3d->vertex[m3d->face[i].vertex[1]].z*m3d->scale;
6941 model.meshes[k].vertices[l*9 + 6] = m3d->vertex[m3d->face[i].vertex[2]].x*m3d->scale;
6942 model.meshes[k].vertices[l*9 + 7] = m3d->vertex[m3d->face[i].vertex[2]].y*m3d->scale;
6943 model.meshes[k].vertices[l*9 + 8] = m3d->vertex[m3d->face[i].vertex[2]].z*m3d->scale;
6944
6945 // Without vertex color (full transparency), using the default color
6946 if (model.meshes[k].colors != NULL)
6947 {
6948 if (m3d->vertex[m3d->face[i].vertex[0]].color & 0xff000000)
6949 memcpy(&model.meshes[k].colors[l*12 + 0], &m3d->vertex[m3d->face[i].vertex[0]].color, 4);
6950 if (m3d->vertex[m3d->face[i].vertex[1]].color & 0xff000000)
6951 memcpy(&model.meshes[k].colors[l*12 + 4], &m3d->vertex[m3d->face[i].vertex[1]].color, 4);
6952 if (m3d->vertex[m3d->face[i].vertex[2]].color & 0xff000000)
6953 memcpy(&model.meshes[k].colors[l*12 + 8], &m3d->vertex[m3d->face[i].vertex[2]].color, 4);
6954 }
6955
6956 if (m3d->face[i].texcoord[0] != M3D_UNDEF)
6957 {
6958 model.meshes[k].texcoords[l*6 + 0] = m3d->tmap[m3d->face[i].texcoord[0]].u;
6959 model.meshes[k].texcoords[l*6 + 1] = 1.0f - m3d->tmap[m3d->face[i].texcoord[0]].v;
6960 model.meshes[k].texcoords[l*6 + 2] = m3d->tmap[m3d->face[i].texcoord[1]].u;
6961 model.meshes[k].texcoords[l*6 + 3] = 1.0f - m3d->tmap[m3d->face[i].texcoord[1]].v;
6962 model.meshes[k].texcoords[l*6 + 4] = m3d->tmap[m3d->face[i].texcoord[2]].u;
6963 model.meshes[k].texcoords[l*6 + 5] = 1.0f - m3d->tmap[m3d->face[i].texcoord[2]].v;
6964 }
6965
6966 if (m3d->face[i].normal[0] != M3D_UNDEF)
6967 {
6968 model.meshes[k].normals[l*9 + 0] = m3d->vertex[m3d->face[i].normal[0]].x;
6969 model.meshes[k].normals[l*9 + 1] = m3d->vertex[m3d->face[i].normal[0]].y;
6970 model.meshes[k].normals[l*9 + 2] = m3d->vertex[m3d->face[i].normal[0]].z;
6971 model.meshes[k].normals[l*9 + 3] = m3d->vertex[m3d->face[i].normal[1]].x;
6972 model.meshes[k].normals[l*9 + 4] = m3d->vertex[m3d->face[i].normal[1]].y;
6973 model.meshes[k].normals[l*9 + 5] = m3d->vertex[m3d->face[i].normal[1]].z;
6974 model.meshes[k].normals[l*9 + 6] = m3d->vertex[m3d->face[i].normal[2]].x;
6975 model.meshes[k].normals[l*9 + 7] = m3d->vertex[m3d->face[i].normal[2]].y;
6976 model.meshes[k].normals[l*9 + 8] = m3d->vertex[m3d->face[i].normal[2]].z;
6977 }
6978
6979 // Add skin (vertex / bone weight pairs)
6980 if (m3d->numbone && m3d->numskin)
6981 {
6982 for (n = 0; n < 3; n++)
6983 {
6984 int skinid = m3d->vertex[m3d->face[i].vertex[n]].skinid;
6985
6986 // Check if there is a skin for this mesh
6987 if ((skinid != M3D_UNDEF) && (skinid < (int)m3d->numskin))
6988 {
6989 for (j = 0; j < 4; j++)
6990 {
6991 model.meshes[k].boneIndices[l*12 + n*4 + j] = m3d->skin[skinid].boneid[j];
6992 model.meshes[k].boneWeights[l*12 + n*4 + j] = m3d->skin[skinid].weight[j];
6993 }
6994 }
6995 else
6996 {
6997 // Boneless meshes with skeletal animations are not supported, so
6998 // putting all vertices without a bone into a special "no bone" bone
6999 model.meshes[k].boneIndices[l*12 + n*4] = m3d->numbone;
7000 model.meshes[k].boneWeights[l*12 + n*4] = 1.0f;
7001 }
7002 }
7003 }
7004 }
7005
7006 // Load materials
7007 for (i = 0; i < (int)m3d->nummaterial; i++)
7008 {
7009 model.materials[i + 1] = LoadMaterialDefault();
7010
7011 for (j = 0; j < m3d->material[i].numprop; j++)
7012 {
7013 prop = &m3d->material[i].prop[j];
7014
7015 switch (prop->type)
7016 {
7017 case m3dp_Kd:
7018 {
7019 memcpy(&model.materials[i + 1].maps[MATERIAL_MAP_DIFFUSE].color, &prop->value.color, 4);
7020 model.materials[i + 1].maps[MATERIAL_MAP_DIFFUSE].value = 0.0f;
7021 } break;
7022 case m3dp_Ks:
7023 {
7024 memcpy(&model.materials[i + 1].maps[MATERIAL_MAP_SPECULAR].color, &prop->value.color, 4);
7025 } break;
7026 case m3dp_Ns:
7027 {
7028 model.materials[i + 1].maps[MATERIAL_MAP_SPECULAR].value = prop->value.fnum;
7029 } break;
7030 case m3dp_Ke:
7031 {
7032 memcpy(&model.materials[i + 1].maps[MATERIAL_MAP_EMISSION].color, &prop->value.color, 4);
7033 model.materials[i + 1].maps[MATERIAL_MAP_EMISSION].value = 0.0f;
7034 } break;
7035 case m3dp_Pm:
7036 {
7037 model.materials[i + 1].maps[MATERIAL_MAP_METALNESS].value = prop->value.fnum;
7038 } break;
7039 case m3dp_Pr:
7040 {
7041 model.materials[i + 1].maps[MATERIAL_MAP_ROUGHNESS].value = prop->value.fnum;
7042 } break;
7043 case m3dp_Ps:
7044 {
7045 model.materials[i + 1].maps[MATERIAL_MAP_NORMAL].color = WHITE;
7046 model.materials[i + 1].maps[MATERIAL_MAP_NORMAL].value = prop->value.fnum;
7047 } break;
7048 default:
7049 {
7050 if (prop->type >= 128)
7051 {
7052 Image image = { 0 };
7053 image.data = m3d->texture[prop->value.textureid].d;
7054 image.width = m3d->texture[prop->value.textureid].w;
7055 image.height = m3d->texture[prop->value.textureid].h;
7056 image.mipmaps = 1;
7057 image.format = (m3d->texture[prop->value.textureid].f == 4)? PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 :
7058 ((m3d->texture[prop->value.textureid].f == 3)? PIXELFORMAT_UNCOMPRESSED_R8G8B8 :
7059 ((m3d->texture[prop->value.textureid].f == 2)? PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA : PIXELFORMAT_UNCOMPRESSED_GRAYSCALE));
7060
7061 switch (prop->type)
7062 {
7063 case m3dp_map_Kd: model.materials[i + 1].maps[MATERIAL_MAP_DIFFUSE].texture = LoadTextureFromImage(image); break;
7064 case m3dp_map_Ks: model.materials[i + 1].maps[MATERIAL_MAP_SPECULAR].texture = LoadTextureFromImage(image); break;
7065 case m3dp_map_Ke: model.materials[i + 1].maps[MATERIAL_MAP_EMISSION].texture = LoadTextureFromImage(image); break;
7066 case m3dp_map_Km: model.materials[i + 1].maps[MATERIAL_MAP_NORMAL].texture = LoadTextureFromImage(image); break;
7067 case m3dp_map_Ka: model.materials[i + 1].maps[MATERIAL_MAP_OCCLUSION].texture = LoadTextureFromImage(image); break;
7068 case m3dp_map_Pm: model.materials[i + 1].maps[MATERIAL_MAP_ROUGHNESS].texture = LoadTextureFromImage(image); break;
7069 default: break;
7070 }
7071 }
7072 } break;
7073 }
7074 }
7075 }
7076
7077 // Load bones
7078 if (m3d->numbone)
7079 {
7080 model.skeleton.boneCount = m3d->numbone + 1;
7081 model.skeleton.bones = (BoneInfo *)RL_CALLOC(model.skeleton.boneCount, sizeof(BoneInfo));
7082 model.skeleton.bindPose = (Transform *)RL_CALLOC(model.skeleton.boneCount, sizeof(Transform));
7083
7084 for (i = 0; i < (int)m3d->numbone; i++)
7085 {
7086 model.skeleton.bones[i].parent = m3d->bone[i].parent;
7087 strncpy(model.skeleton.bones[i].name, m3d->bone[i].name, sizeof(model.skeleton.bones[i].name) - 1);
7088 model.skeleton.bindPose[i].translation.x = m3d->vertex[m3d->bone[i].pos].x*m3d->scale;
7089 model.skeleton.bindPose[i].translation.y = m3d->vertex[m3d->bone[i].pos].y*m3d->scale;
7090 model.skeleton.bindPose[i].translation.z = m3d->vertex[m3d->bone[i].pos].z*m3d->scale;
7091 model.skeleton.bindPose[i].rotation.x = m3d->vertex[m3d->bone[i].ori].x;
7092 model.skeleton.bindPose[i].rotation.y = m3d->vertex[m3d->bone[i].ori].y;
7093 model.skeleton.bindPose[i].rotation.z = m3d->vertex[m3d->bone[i].ori].z;
7094 model.skeleton.bindPose[i].rotation.w = m3d->vertex[m3d->bone[i].ori].w;
7095
7096 // NOTE: If the orientation quaternion is not normalized, then that's encoding scaling
7097 model.skeleton.bindPose[i].rotation = QuaternionNormalize(model.skeleton.bindPose[i].rotation);
7098 model.skeleton.bindPose[i].scale.x = model.skeleton.bindPose[i].scale.y = model.skeleton.bindPose[i].scale.z = 1.0f;
7099
7100 // Child bones are stored in parent bone relative space, convert that into model space
7101 if (model.skeleton.bones[i].parent >= 0)
7102 {
7103 model.skeleton.bindPose[i].rotation = QuaternionMultiply(model.skeleton.bindPose[model.skeleton.bones[i].parent].rotation, model.skeleton.bindPose[i].rotation);
7104 model.skeleton.bindPose[i].translation = Vector3RotateByQuaternion(model.skeleton.bindPose[i].translation, model.skeleton.bindPose[model.skeleton.bones[i].parent].rotation);
7105 model.skeleton.bindPose[i].translation = Vector3Add(model.skeleton.bindPose[i].translation, model.skeleton.bindPose[model.skeleton.bones[i].parent].translation);
7106 model.skeleton.bindPose[i].scale = Vector3Multiply(model.skeleton.bindPose[i].scale, model.skeleton.bindPose[model.skeleton.bones[i].parent].scale);
7107 }
7108 }
7109
7110 // Add a special "no bone" bone
7111 model.skeleton.bones[i].parent = -1;
7112 memcpy(model.skeleton.bones[i].name, "NO BONE", 7);
7113 model.skeleton.bindPose[i].translation.x = 0.0f;
7114 model.skeleton.bindPose[i].translation.y = 0.0f;
7115 model.skeleton.bindPose[i].translation.z = 0.0f;
7116 model.skeleton.bindPose[i].rotation.x = 0.0f;
7117 model.skeleton.bindPose[i].rotation.y = 0.0f;
7118 model.skeleton.bindPose[i].rotation.z = 0.0f;
7119 model.skeleton.bindPose[i].rotation.w = 1.0f;
7120 model.skeleton.bindPose[i].scale.x = model.skeleton.bindPose[i].scale.y = model.skeleton.bindPose[i].scale.z = 1.0f;
7121 }
7122
7123 // Load bone-pose default mesh into animation vertices. These will be updated when UpdateModelAnimation gets
7124 // called, but not before, however DrawMesh uses these if they exist (so not good if they are left empty)
7125 if (m3d->numbone && m3d->numskin)
7126 {
7127 for (i = 0; i < model.meshCount; i++)
7128 {
7129 model.meshes[i].boneCount = model.skeleton.boneCount;
7130
7131 #if !SUPPORT_GPU_SKINNING
7132 // Initialize vertex buffers for CPU skinning
7133 memcpy(model.meshes[i].animVertices, model.meshes[i].vertices, model.meshes[i].vertexCount*3*sizeof(float));
7134 memcpy(model.meshes[i].animNormals, model.meshes[i].normals, model.meshes[i].vertexCount*3*sizeof(float));
7135 #endif
7136 }
7137
7138 // Initialize runtime animation data: current pose and bone matrices
7139 model.currentPose = (Transform *)RL_CALLOC(model.skeleton.boneCount, sizeof(Transform));
7140 model.boneMatrices = (Matrix *)RL_CALLOC(model.skeleton.boneCount, sizeof(Matrix));
7141 for (int j = 0; j < model.skeleton.boneCount; j++) model.boneMatrices[j] = MatrixIdentity();
7142 }
7143
7144 m3d_free(m3d);
7145 UnloadFileData(fileData);
7146 }
7147
7148 return model;
7149 }
7150
7151 #define M3D_ANIMDELAY 17 // Animation frames delay, (~1000 ms/60 FPS = 16.666666* ms)
7152
7153 // Load M3D animation data
7154 static ModelAnimation *LoadModelAnimationsM3D(const char *fileName, int *animCount)
7155 {
7156 ModelAnimation *animations = NULL;
7157
7158 m3d_t *m3d = NULL;
7159 int i = 0, j = 0;
7160 *animCount = 0;
7161
7162 int dataSize = 0;
7163 unsigned char *fileData = LoadFileData(fileName, &dataSize);
7164
7165 if (fileData != NULL)
7166 {
7167 m3d = m3d_load(fileData, m3d_loaderhook, m3d_freehook, NULL);
7168
7169 if (!m3d || M3D_ERR_ISFATAL(m3d->errcode))
7170 {
7171 TRACELOG(LOG_WARNING, "MODEL: [%s] Failed to load M3D data, error code %d", fileName, m3d? m3d->errcode : -2);
7172 UnloadFileData(fileData);
7173 return NULL;
7174 }
7175 else TRACELOG(LOG_INFO, "MODEL: [%s] M3D data loaded successfully: %i animations, %i bones, %i skins", fileName, m3d->numaction, m3d->numbone, m3d->numskin);
7176
7177 // No animation or bones, exit out. skins are not required because some people use one animation for N models
7178 if (!m3d->numaction || !m3d->numbone)
7179 {
7180 m3d_free(m3d);
7181 UnloadFileData(fileData);
7182 return NULL;
7183 }
7184
7185 animations = (ModelAnimation *)RL_CALLOC(m3d->numaction, sizeof(ModelAnimation));
7186 *animCount = m3d->numaction;
7187
7188 for (unsigned int a = 0; a < m3d->numaction; a++)
7189 {
7190 animations[a].boneCount = m3d->numbone + 1;
7191 BoneInfo *bones = (BoneInfo *)RL_CALLOC((m3d->numbone + 1), sizeof(BoneInfo));
7192
7193 animations[a].keyframeCount = m3d->action[a].durationmsec/M3D_ANIMDELAY;
7194 animations[a].keyframePoses = (Transform **)RL_CALLOC(animations[a].keyframeCount, sizeof(Transform *));
7195 strncpy(animations[a].name, m3d->action[a].name, sizeof(animations[a].name) - 1);
7196
7197 TRACELOG(LOG_INFO, "MODEL: [%s] Loaded animation: %s | Frames: %d | Duration: %fs", fileName, animations[a].name, animations[a].keyframeCount, m3d->action[a].durationmsec);
7198
7199 for (i = 0; i < (int)m3d->numbone; i++)
7200 {
7201 bones[i].parent = m3d->bone[i].parent;
7202 strncpy(bones[i].name, m3d->bone[i].name, sizeof(bones[i].name) - 1);
7203 }
7204
7205 // A special, never transformed "no bone" bone, used for boneless vertices
7206 bones[i].parent = -1;
7207 memcpy(bones[i].name, "NO BONE", 7);
7208
7209 // M3D stores frames at arbitrary intervals with sparse skeletons; Full skeletons is required at
7210 // regular intervals, so let the M3D SDK do the heavy lifting and calculate interpolated bones
7211 for (i = 0; i < animations[a].keyframeCount; i++)
7212 {
7213 animations[a].keyframePoses[i] = (Transform *)RL_CALLOC((m3d->numbone + 1), sizeof(Transform));
7214
7215 m3db_t *pose = m3d_pose(m3d, a, i*M3D_ANIMDELAY);
7216
7217 if (pose != NULL)
7218 {
7219 for (j = 0; j < (int)m3d->numbone; j++)
7220 {
7221 animations[a].keyframePoses[i][j].translation.x = m3d->vertex[pose[j].pos].x*m3d->scale;
7222 animations[a].keyframePoses[i][j].translation.y = m3d->vertex[pose[j].pos].y*m3d->scale;
7223 animations[a].keyframePoses[i][j].translation.z = m3d->vertex[pose[j].pos].z*m3d->scale;
7224 animations[a].keyframePoses[i][j].rotation.x = m3d->vertex[pose[j].ori].x;
7225 animations[a].keyframePoses[i][j].rotation.y = m3d->vertex[pose[j].ori].y;
7226 animations[a].keyframePoses[i][j].rotation.z = m3d->vertex[pose[j].ori].z;
7227 animations[a].keyframePoses[i][j].rotation.w = m3d->vertex[pose[j].ori].w;
7228 animations[a].keyframePoses[i][j].rotation = QuaternionNormalize(animations[a].keyframePoses[i][j].rotation);
7229 animations[a].keyframePoses[i][j].scale.x = animations[a].keyframePoses[i][j].scale.y = animations[a].keyframePoses[i][j].scale.z = 1.0f;
7230
7231 // Child bones are stored in parent bone relative space, convert that into model space
7232 if (bones[j].parent >= 0)
7233 {
7234 animations[a].keyframePoses[i][j].rotation = QuaternionMultiply(animations[a].keyframePoses[i][bones[j].parent].rotation, animations[a].keyframePoses[i][j].rotation);
7235 animations[a].keyframePoses[i][j].translation = Vector3RotateByQuaternion(animations[a].keyframePoses[i][j].translation, animations[a].keyframePoses[i][bones[j].parent].rotation);
7236 animations[a].keyframePoses[i][j].translation = Vector3Add(animations[a].keyframePoses[i][j].translation, animations[a].keyframePoses[i][bones[j].parent].translation);
7237 animations[a].keyframePoses[i][j].scale = Vector3Multiply(animations[a].keyframePoses[i][j].scale, animations[a].keyframePoses[i][bones[j].parent].scale);
7238 }
7239 }
7240
7241 // Default transform for the "no bone" bone
7242 animations[a].keyframePoses[i][j].translation.x = 0.0f;
7243 animations[a].keyframePoses[i][j].translation.y = 0.0f;
7244 animations[a].keyframePoses[i][j].translation.z = 0.0f;
7245 animations[a].keyframePoses[i][j].rotation.x = 0.0f;
7246 animations[a].keyframePoses[i][j].rotation.y = 0.0f;
7247 animations[a].keyframePoses[i][j].rotation.z = 0.0f;
7248 animations[a].keyframePoses[i][j].rotation.w = 1.0f;
7249 animations[a].keyframePoses[i][j].scale.x = 1.0f;
7250 animations[a].keyframePoses[i][j].scale.y = 1.0f;
7251 animations[a].keyframePoses[i][j].scale.z = 1.0f;
7252
7253 RL_FREE(pose);
7254 }
7255 }
7256
7257 RL_FREE(bones);
7258 }
7259
7260 m3d_free(m3d);
7261 UnloadFileData(fileData);
7262 }
7263
7264 return animations;
7265 }
7266 #endif
7267
7268 #endif // SUPPORT_MODULE_RMODELS