Unify pipeline generation

This commit is contained in:
John Alanbrook 2024-05-08 11:07:19 -05:00
parent 4caea247a6
commit 22c38fe481
52 changed files with 303 additions and 2431 deletions

View file

@ -145,7 +145,7 @@ OBJS := $(patsubst %.m, %$(INFO).o, $(OBJS))
engineincs != find source/engine -maxdepth 1 -type d engineincs != find source/engine -maxdepth 1 -type d
includeflag != find source -type d -name include includeflag != find source -type d -name include
includeflag += $(engineincs) source/shaders source/engine/thirdparty/sokol source/engine/thirdparty/stb source/engine/thirdparty/cgltf source/engine/thirdparty/TinySoundFont source/engine/thirdparty/dr_libs includeflag += $(engineincs) source/engine/thirdparty/sokol source/engine/thirdparty/stb source/engine/thirdparty/cgltf source/engine/thirdparty/TinySoundFont source/engine/thirdparty/dr_libs
includeflag += $(STEAM)/public includeflag += $(STEAM)/public
includeflag += source includeflag += source
includeflag := $(addprefix -I, $(includeflag)) includeflag := $(addprefix -I, $(includeflag))
@ -172,10 +172,7 @@ DEPENDS = $(OBJS:.o=.d)
all: $(NAME) all: $(NAME)
cp -f $(NAME) $(APP)$(EXT) cp -f $(NAME) $(APP)$(EXT)
SHADERS = $(shell ls source/shaders/*.sglsl) prereqs: source/engine/core.cdb.h
SHADERS := $(patsubst %.sglsl, %.sglsl.h, $(SHADERS))
prereqs: $(SHADERS) source/engine/core.cdb.h
DESTDIR ?= ~/.bin DESTDIR ?= ~/.bin
install: $(NAME) install: $(NAME)
@ -199,13 +196,6 @@ $(NAME): $(OBJS) $(DEPS)
@echo Making Objective-C object $@ @echo Making Objective-C object $@
$(CROSS)$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ $(CROSS)$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@
shaders: $(SHADERS)
@echo Making shaders
%.sglsl.h:%.sglsl
@echo Creating shader $^
./sokol-shdc -r --ifdef -i $^ --slang=glsl330:hlsl5:metal_macos:metal_ios:metal_sim:glsl300es -o $@
SCRIPTS := $(shell ls scripts/*.js*) SCRIPTS := $(shell ls scripts/*.js*)
CORE != (ls icons/* fonts/*) CORE != (ls icons/* fonts/*)
CORE := $(CORE) $(SCRIPTS) CORE := $(CORE) $(SCRIPTS)
@ -266,7 +256,7 @@ crossweb:
clean: clean:
@echo Cleaning project @echo Cleaning project
rm -f source/shaders/*.h core.cdb jso cdb packer TAGS source/engine/core.cdb.h tools/libcdb.a $(APP)* *.icns *.ico rm -f core.cdb jso cdb packer TAGS source/engine/core.cdb.h tools/libcdb.a $(APP)* *.icns *.ico
find . -type f -name "*.[oad]" -delete find . -type f -name "*.[oad]" -delete
rm -rf Prosperon.app rm -rf Prosperon.app

View file

@ -76,7 +76,7 @@ function json_from_whitelist(whitelist)
} }
} }
Object.mixin(os.sprite(true), { var sprite = {
loop: true, loop: true,
toJSON:json_from_whitelist([ toJSON:json_from_whitelist([
"path", "path",
@ -175,11 +175,10 @@ Object.mixin(os.sprite(true), {
}, },
width() { return this.dimensions().x; }, width() { return this.dimensions().x; },
height() { return this.dimensions().y; }, height() { return this.dimensions().y; },
}); };
globalThis.allsprites = {}; globalThis.allsprites = {};
os.sprite().make = function(go) sprite.make = function(go)
{ {
var sp = os.sprite();
sp.go = go; sp.go = go;
sp.gameobject = go; sp.gameobject = go;
sp.guid = prosperon.guid(); sp.guid = prosperon.guid();
@ -187,10 +186,6 @@ os.sprite().make = function(go)
return sp; return sp;
} }
component.sprite = os.sprite(true);
var sprite = component.sprite;
sprite.doc = { sprite.doc = {
path: "Path to the texture.", path: "Path to the texture.",
color: "Color to mix with the sprite.", color: "Color to mix with the sprite.",
@ -225,6 +220,8 @@ sprite.inputs.kp3 = function() { this.setanchor("ur"); }
sprite.inputs.kp2 = function() { this.setanchor("um"); } sprite.inputs.kp2 = function() { this.setanchor("um"); }
sprite.inputs.kp1 = function() { this.setanchor("ul"); } sprite.inputs.kp1 = function() { this.setanchor("ul"); }
component.sprite = sprite;
Object.seal(sprite); Object.seal(sprite);
/* sprite anim returns a data structure for the given file path /* sprite anim returns a data structure for the given file path

View file

@ -8,7 +8,6 @@ game.loadurs();
console.info(`window size: ${window.size}, render size: ${window.rendersize}`); console.info(`window size: ${window.size}, render size: ${window.rendersize}`);
player[0].control(debug); player[0].control(debug);
render.clear_color([35,60,92,255].map(x => x/255));
var show_frame = true; var show_frame = true;

View file

@ -343,18 +343,14 @@ function process()
render.sprite_flush();*/ render.sprite_flush();*/
prosperon.draw(); // draw calls prosperon.draw(); // draw calls
debug.draw(); // calls needed debugs debug.draw(); // calls needed debugs
render.flush();
prosperon.hook3d?.(); prosperon.hook3d?.();
render.hud_res(window.rendersize);
prosperon.gui(); prosperon.gui();
render.flush();
render.hud_res(window.size);
prosperon.screengui(); prosperon.screengui();
render.flush();
render.end_pass(); prosperon.hookend?.();
//render.end_pass();
profile.addreport(profcache, "render frame", st); profile.addreport(profcache, "render frame", st);
frames.push(profile.secs(profile.now()-startframe)); frames.push(profile.secs(profile.now()-startframe));
if (frames.length > 20) frames.shift(); if (frames.length > 20) frames.shift();

View file

@ -139,12 +139,9 @@ render.set_font = function(path, size) {
} }
render.doc = "Draw shapes in screen space."; render.doc = "Draw shapes in screen space.";
render.circle.doc = "Draw a circle at pos, with a given radius and color."; //render.circle.doc = "Draw a circle at pos, with a given radius and color.";
render.cross.doc = "Draw a cross centered at pos, with arm length size."; render.cross.doc = "Draw a cross centered at pos, with arm length size.";
render.arrow.doc = "Draw an arrow from start to end, with wings of length wingspan at angle wingangle."; render.arrow.doc = "Draw an arrow from start to end, with wings of length wingspan at angle wingangle.";
render.poly.doc = "Draw a concave polygon from a set of points.";
render.rectangle.doc = "Draw a rectangle, with its corners at lowerleft and upperright."; render.rectangle.doc = "Draw a rectangle, with its corners at lowerleft and upperright.";
render.box.doc = "Draw a box centered at pos, with width and height in the tuple wh.";
render.line.doc = "Draw a line from a set of points, and a given thickness.";
return {render}; return {render};

View file

@ -3,7 +3,6 @@
#include "gameobject.h" #include "gameobject.h"
#include <string.h> #include <string.h>
#include "debugdraw.h"
#include "stb_ds.h" #include "stb_ds.h"
#include <assert.h> #include <assert.h>
#include <chipmunk/chipmunk_unsafe.h> #include <chipmunk/chipmunk_unsafe.h>
@ -225,9 +224,9 @@ void phys2d_dbgdrawcpcirc(cpShape *c) {
float radius = cpCircleShapeGetRadius(c); float radius = cpCircleShapeGetRadius(c);
struct rgba color = shape_color(c); struct rgba color = shape_color(c);
float seglen = cpShapeGetSensor(c) ? 5 : -1; float seglen = cpShapeGetSensor(c) ? 5 : -1;
draw_circle(pos, radius, 1, color, seglen); //draw_circle(pos, radius, 1, color, seglen);
color.a = col_alpha; color.a = col_alpha;
draw_circle(pos,radius,radius,color,-1); //draw_circle(pos,radius,radius,color,-1);
} }
void phys2d_shape_apply(struct phys2d_shape *s) void phys2d_shape_apply(struct phys2d_shape *s)
@ -347,9 +346,9 @@ void phys2d_dbgdrawpoly(struct phys2d_poly *poly) {
points[n] = points[0]; points[n] = points[0];
draw_poly(points, n, color); //draw_poly(points, n, color);
float seglen = cpShapeGetSensor(poly->shape.shape) ? sensor_seg : 0; float seglen = cpShapeGetSensor(poly->shape.shape) ? sensor_seg : 0;
draw_line(points, n, line_color, seglen, 0); //draw_line(points, n, line_color, seglen, 0);
} }
} }
/****************** EDGE 2D**************/ /****************** EDGE 2D**************/
@ -492,8 +491,8 @@ void phys2d_dbgdrawedge(struct phys2d_edge *edge) {
struct rgba color = shape_color(edge->shapes[0]); struct rgba color = shape_color(edge->shapes[0]);
struct rgba line_color = color; struct rgba line_color = color;
color.a = col_alpha; color.a = col_alpha;
draw_edge(drawpoints, arrlen(edge->points), color, edge->thickness * 2, 0, line_color, seglen); // draw_edge(drawpoints, arrlen(edge->points), color, edge->thickness * 2, 0, line_color, seglen);
draw_points(drawpoints, arrlen(edge->points), 2, kinematic_color); //draw_points(drawpoints, arrlen(edge->points), 2, kinematic_color);
} }
/************ COLLIDER ****************/ /************ COLLIDER ****************/

View file

@ -83,7 +83,6 @@ sg_buffer texcoord_floats(float *f, int n)
if (v < 0) v = 0; if (v < 0) v = 0;
if (v > 1) v = 1; if (v > 1) v = 1;
packed[i] = pack_short_tex(v); packed[i] = pack_short_tex(v);
printf("val: %g, packed: %u\n", v, packed[i]);
} }
return sg_make_buffer(&(sg_buffer_desc){ return sg_make_buffer(&(sg_buffer_desc){
@ -544,6 +543,7 @@ int mat2type(int mat)
{ {
switch(mat) { switch(mat) {
case MAT_POS: case MAT_POS:
return SG_VERTEXFORMAT_FLOAT3;
case MAT_WH: case MAT_WH:
case MAT_ST: case MAT_ST:
return SG_VERTEXFORMAT_FLOAT2; return SG_VERTEXFORMAT_FLOAT2;

View file

@ -1,4 +1,4 @@
#include "render.h" #include "config.h"
#define SOKOL_TRACE_HOOKS #define SOKOL_TRACE_HOOKS
#define SOKOL_IMPL #define SOKOL_IMPL
@ -7,7 +7,6 @@
#include "sokol/sokol_args.h" #include "sokol/sokol_args.h"
#include "sokol/sokol_gfx.h" #include "sokol/sokol_gfx.h"
#include "sokol/sokol_app.h" #include "sokol/sokol_app.h"
#include "sokol_gfx_ext.h"
#define MSF_GIF_IMPL #define MSF_GIF_IMPL
#include "msf_gif.h" #include "msf_gif.h"
@ -25,11 +24,11 @@
#define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_IMPLEMENTATION
#define STBI_FAILURE_USERMSG #define STBI_FAILURE_USERMSG
#define STBI_NO_STDIO #define STBI_NO_STDIO
#ifdef __TINYC__
#define STBI_NO_SIMD
#endif
#include "stb_image.h" #include "stb_image.h"
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#include "stb_image_resize2.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION
#define STBIR_DEFAULT_FILTER_DOWNSAMPLE STBIR_FILTER_BOX #define STBIR_DEFAULT_FILTER_DOWNSAMPLE STBIR_FILTER_BOX
#include "stb_image_write.h" #include "stb_image_write.h"
@ -44,3 +43,12 @@
#define CGLTF_IMPLEMENTATION #define CGLTF_IMPLEMENTATION
#include "cgltf.h" #include "cgltf.h"
#define PAR_SHAPES_IMPLEMENTATION
#include "par/par_shapes.h"
#define PAR_STREAMLINES_IMPLEMENTATION
#include "par/par_streamlines.h"
#define QOI_IMPLEMENTATION
#include "qoi.h"

View file

@ -4,12 +4,19 @@
#define MAXPATH 256 /* 255 chars + null */ #define MAXPATH 256 /* 255 chars + null */
#define MAXNAME 50 #define MAXNAME 50
#define SCREEN_WIDTH 1280
#define SCREEN_HEIGHT 720
#define PI 3.14159265358979323846264338327950288f #define PI 3.14159265358979323846264338327950288f
#define DEG2RADS 0.0174532925199432957692369076848861271344287188854172545609719144f #define DEG2RADS 0.0174532925199432957692369076848861271344287188854172545609719144f
#define RAD2DEGS 57.2958f #define RAD2DEGS 57.2958f
#define CONFIG_H
#if defined __linux__
#define SOKOL_GLCORE33
#elif __EMSCRIPTEN__
#define SOKOL_GLES3
#elif __WIN32
#define SOKOL_D3D11
#elif __APPLE__
#define SOKOL_METAL
#endif
#endif #endif

View file

@ -13,8 +13,6 @@
#include "font.h" #include "font.h"
#include "render.h" #include "render.h"
#include "mpeg2.sglsl.h"
#include "cbuf.h" #include "cbuf.h"
#include "sokol/sokol_gfx.h" #include "sokol/sokol_gfx.h"
@ -91,10 +89,6 @@ struct datastream *ds_openvideo(const char *path)
return ds; return ds;
} }
void MakeDatastream() {
vid_shader = sg_make_shader(mpeg2_shader_desc(sg_query_backend()));
}
void ds_advance(struct datastream *ds, double s) { void ds_advance(struct datastream *ds, double s) {
if (ds->playing) plm_decode(ds->plm, s); if (ds->playing) plm_decode(ds->plm, s);
} }

View file

@ -21,7 +21,6 @@ struct datastream {
struct texture; struct texture;
void MakeDatastream();
struct datastream *ds_openvideo(const char *path); struct datastream *ds_openvideo(const char *path);
struct texture *ds_maketexture(struct datastream *); struct texture *ds_maketexture(struct datastream *);
void ds_advance(struct datastream *ds, double); void ds_advance(struct datastream *ds, double);

View file

@ -1,645 +0,0 @@
#include "debugdraw.h"
#include "render.h"
#include "yugine.h"
#include "log.h"
#include <assert.h>
#include "window.h"
#include "2dphysics.h"
#include "stb_ds.h"
#include "sokol/sokol_gfx.h"
#include "point.sglsl.h"
#include "poly.sglsl.h"
#include "circle.sglsl.h"
#include "line.sglsl.h"
#include "grid.sglsl.h"
#include "grid3d.sglsl.h"
#define PAR_STREAMLINES_IMPLEMENTATION
#include "par/par_streamlines.h"
#include "font.h"
#define v_amt 500000
struct flush {
sg_shader shader;
sg_pipeline pipe;
sg_bindings bind;
void *verts;
int c;
int v;
int sc;
int sv;
};
typedef struct flush flush;
static flush fpoint;
static flush circle;
void flushview(flush *f, HMM_Mat4 *view)
{
sg_apply_pipeline(f->pipe);
sg_apply_bindings(&f->bind);
sg_apply_uniforms(SG_SHADERSTAGE_VS, 0, SG_RANGE_REF(*view));
sg_draw(f->sc, f->c, 1);
}
void flushpass(flush *f)
{
f->sc = f->c;
f->c = 0;
f->sv = f->v;
f->v = 0;
}
static sg_shader point_shader;
static sg_pipeline point_pipe;
static sg_bindings point_bind;
struct point_vertex {
struct draw_p3 pos;
struct rgba color;
float radius;
};
static int point_c = 0;
static int point_sc = 0;
static sg_shader line_shader;
static sg_pipeline line_pipe;
static sg_bindings line_bind;
struct line_vert {
struct draw_p pos;
float dist;
struct rgba color;
float seg_len;
float seg_speed;
};
static int line_c = 0;
static int line_v = 0;
static int line_sc = 0;
static int line_sv = 0;
static sg_pipeline grid_pipe;
static sg_bindings grid_bind;
static sg_shader grid_shader;
static int grid_c = 0;
static sg_pipeline poly_pipe;
static sg_bindings poly_bind;
static sg_shader poly_shader;
static int poly_c = 0;
static int poly_v = 0;
static int poly_sc = 0;
static int poly_sv = 0;
struct poly_vertex {
struct draw_p pos;
float uv[2];
struct rgba color;
};
static sg_pipeline circle_pipe;
static sg_bindings circle_bind;
static sg_shader csg;
static int circle_count = 0;
static int circle_sc = 0;
struct circle_vertex {
struct draw_p pos;
float radius;
struct rgba color;
float segsize;
float fill;
};
void debug_nextpass()
{
point_sc = point_c;
point_c = 0;
circle_sc = circle_count;
circle_count = 0;
line_sv = line_v;
line_v = 0;
line_sc = line_c;
line_c = 0;
poly_sc = poly_c;
poly_c = 0;
poly_sv = poly_v;
poly_v = 0;
}
/* Writes debug data to buffers, and draws */
void debug_flush(HMM_Mat4 *view)
{
if (poly_c != 0) {
sg_apply_pipeline(poly_pipe);
sg_apply_bindings(&poly_bind);
sg_apply_uniforms(SG_SHADERSTAGE_VS,0,SG_RANGE_REF(*view));
sg_draw(poly_sc,poly_c,1);
}
if (point_c != 0) {
sg_apply_pipeline(point_pipe);
sg_apply_bindings(&point_bind);
sg_apply_uniforms(SG_SHADERSTAGE_VS,0,SG_RANGE_REF(*view));
sg_draw(point_sc,point_c,1);
}
if (line_c != 0) {
sg_apply_pipeline(line_pipe);
sg_apply_bindings(&line_bind);
sg_apply_uniforms(SG_SHADERSTAGE_VS,0,SG_RANGE_REF(*view));
lfs_params_t lt;
lt.time = apptime();
sg_apply_uniforms(SG_SHADERSTAGE_FS,0,SG_RANGE_REF(lt));
sg_draw(line_sc,line_c,1);
}
if (circle_count != 0) {
sg_apply_pipeline(circle_pipe);
sg_apply_bindings(&circle_bind);
sg_apply_uniforms(SG_SHADERSTAGE_VS, 0, SG_RANGE_REF(*view));
sg_draw(circle_sc,4,circle_count);
}
debug_nextpass();
}
void debug_newframe()
{
point_sc = 0;
point_c = 0;
circle_sc = circle_count = line_sv = line_v = line_sc = line_c = poly_sc = poly_c = 0;
poly_sv = poly_v = 0;
}
static sg_shader_uniform_block_desc projection_ubo = {
.size = sizeof(useproj),
.uniforms = {
[0] = { .name = "proj", .type = SG_UNIFORMTYPE_MAT4 },
}
};
static sg_shader_uniform_block_desc time_ubo = {
.size = sizeof(float),
.uniforms = {
[0] = { .name = "time", .type = SG_UNIFORMTYPE_FLOAT },
}
};
void debugdraw_init()
{
point_shader = sg_make_shader(point_shader_desc(sg_query_backend()));
point_pipe = sg_make_pipeline(&(sg_pipeline_desc){
.shader = point_shader,
.layout = {
.attrs = {
[0].format = SG_VERTEXFORMAT_FLOAT2, /* pos */
[1].format = SG_VERTEXFORMAT_UBYTE4N, /* color */
[2].format = SG_VERTEXFORMAT_FLOAT /* radius */
}
},
.primitive_type = SG_PRIMITIVETYPE_POINTS,
.colors[0].blend = blend_trans,
.label = "dbg point",
});
point_bind.vertex_buffers[0] = sg_make_buffer(&(sg_buffer_desc){
.size = sizeof(struct point_vertex)*v_amt,
.usage = SG_USAGE_STREAM,
.label = "point vertex buffer"
});
line_shader = sg_make_shader(line_shader_desc(sg_query_backend()));
line_pipe = sg_make_pipeline(&(sg_pipeline_desc){
.shader = line_shader,
.layout = {
.attrs = {
[0].format = SG_VERTEXFORMAT_FLOAT3, /* pos */
[1].format = SG_VERTEXFORMAT_FLOAT, /* dist */
[2].format = SG_VERTEXFORMAT_UBYTE4N, /* color */
[3].format = SG_VERTEXFORMAT_FLOAT, /* seg length */
[4].format = SG_VERTEXFORMAT_FLOAT /* dashed line speed */
}
},
.primitive_type = SG_PRIMITIVETYPE_LINES,
.index_type = SG_INDEXTYPE_UINT16,
.colors[0].blend = blend_trans,
.label = "dbg line",
});
line_bind.vertex_buffers[0] = sg_make_buffer(&(sg_buffer_desc){
.size = sizeof(struct line_vert)*v_amt,
.usage = SG_USAGE_STREAM,
.label = "line vertex buffer",
});
line_bind.index_buffer = sg_make_buffer(&(sg_buffer_desc){
.size = sizeof(uint16_t)*v_amt,
.usage = SG_USAGE_STREAM,
.type = SG_BUFFERTYPE_INDEXBUFFER,
.label = "line index buffer",
});
csg = sg_make_shader(circle_shader_desc(sg_query_backend()));
circle_pipe = sg_make_pipeline(&(sg_pipeline_desc){
.shader = csg,
.layout = {
.attrs = {
[0].format = SG_VERTEXFORMAT_FLOAT2,
[0].buffer_index = 1,
[1].format = SG_VERTEXFORMAT_FLOAT2,
[2].format = SG_VERTEXFORMAT_FLOAT,
[3].format = SG_VERTEXFORMAT_UBYTE4N,
[4].format = SG_VERTEXFORMAT_FLOAT,
[5].format = SG_VERTEXFORMAT_FLOAT
},
.buffers[0].step_func = SG_VERTEXSTEP_PER_INSTANCE,
},
.primitive_type = SG_PRIMITIVETYPE_TRIANGLE_STRIP,
.cull_mode = SG_CULLMODE_BACK,
.colors[0].blend = blend_trans,
.label = "circle pipeline"
});
circle_bind.vertex_buffers[0] = sg_make_buffer(&(sg_buffer_desc){
.size = sizeof(struct circle_vertex)*v_amt,
.usage = SG_USAGE_STREAM,
.label = "circle vert buffer",
});
float circleverts[] = {
-1,-1,
-1,1,
1,-1,
1,1
};
circle_bind.vertex_buffers[1] = sg_make_buffer(&(sg_buffer_desc){
.data = (sg_range){.ptr = circleverts, .size = sizeof(circleverts)},
.usage = SG_USAGE_IMMUTABLE,
.label = "circle quarter buffer",
});
grid_shader = sg_make_shader(grid_shader_desc(sg_query_backend()));
grid_pipe = sg_make_pipeline(&(sg_pipeline_desc){
.shader = grid_shader,
.layout = {
.attrs = {
[0].format = SG_VERTEXFORMAT_FLOAT2, /* pos */
}
},
.primitive_type = SG_PRIMITIVETYPE_TRIANGLE_STRIP,
.cull_mode = SG_CULLMODE_BACK,
.label = "grid pipeline",
.colors[0].blend = blend_trans,
});
grid_bind.vertex_buffers[0] = circle_bind.vertex_buffers[1];
poly_shader = sg_make_shader(poly_shader_desc(sg_query_backend()));
poly_pipe = sg_make_pipeline(&(sg_pipeline_desc){
.shader = poly_shader,
.layout = {
.attrs = { [0].format = SG_VERTEXFORMAT_FLOAT2, /* pos */
[1].format = SG_VERTEXFORMAT_FLOAT2, /* uv */
[2].format = SG_VERTEXFORMAT_UBYTE4N /* color rgba */
}
},
.index_type = SG_INDEXTYPE_UINT32,
.colors[0].blend = blend_trans,
// .cull_mode = SG_CULLMODE_FRONT,
.label = "dbg poly",
});
poly_bind.vertex_buffers[0] = sg_make_buffer(&(sg_buffer_desc){
.size = sizeof(struct poly_vertex)*v_amt,
.usage = SG_USAGE_STREAM,
.type = SG_BUFFERTYPE_VERTEXBUFFER,
.label = "poly vert buffer",
});
poly_bind.index_buffer = sg_make_buffer(&(sg_buffer_desc){
.size = sizeof(uint32_t)*6*v_amt,
.usage = SG_USAGE_STREAM,
.type = SG_BUFFERTYPE_INDEXBUFFER,
.label = "poly index buffer"
});
}
void draw_line3d(HMM_Vec3 *points, int n, struct rgba color, float seg_len, float seg_speed)
{
if (n < 2) return;
seg_speed = 1;
struct line_vert v[n];
float dist = 0;
for (int i = 0; i < n; i++) {
v[i].pos.x = points[i].x;
v[i].pos.y = points[i].y;
v[i].color = color;
v[i].seg_len = seg_len;
v[i].seg_speed = seg_speed;
}
v[0].dist = 0;
for (int i = 1; i < n; i++) {
dist += HMM_DistV3(points[i-1], points[i]);
v[i].dist = dist;
}
int i_c = (n-1)*2;
uint16_t idxs[i_c];
for (int i = 0, d = 0; i < n-1; i++, d+=2) {
idxs[d] = i + line_v + line_sv;
idxs[d+1] = idxs[d]+1;
}
sg_range vr = {
.ptr = v,
.size = sizeof(struct line_vert)*n
};
sg_range ir = {
.ptr = idxs,
.size = sizeof(uint16_t)*i_c
};
if (sg_query_buffer_will_overflow(line_bind.vertex_buffers[0], vr.size) || sg_query_buffer_will_overflow(line_bind.index_buffer, ir.size)) return;
sg_append_buffer(line_bind.vertex_buffers[0], &vr);
sg_append_buffer(line_bind.index_buffer, &ir);
line_c += i_c;
line_v += n;
}
void draw_line(HMM_Vec2 *points, int n, struct rgba color, float seg_len, float seg_speed)
{
if (n < 2) return;
HMM_Vec3 points3[n];
for (int i = 0; i < n; i++)
points3[i].xy = points[i];
draw_line3d(points3, n, color, seg_len, seg_speed);
}
HMM_Vec2 center_of_vects(HMM_Vec2 *v, int n)
{
HMM_Vec2 c;
for (int i = 0; i < n; i++) {
c.x += v[i].x;
c.y += v[i].y;
}
c.x /= n;
c.y /= n;
return c;
}
/* Given a series of points p, computes a new series with them expanded on either side by d */
HMM_Vec2 *inflatepoints(HMM_Vec2 *p, float d, int n)
{
if (d == 0) {
HMM_Vec2 *ret = NULL;
arraddn(ret,n);
for (int i = 0; i < n; i++)
ret[i] = p[i];
return ret;
}
parsl_position par_v[n];
uint16_t spine_lens[] = {n};
for (int i = 0; i < n; i++) {
par_v[i].x = p[i].x;
par_v[i].y = p[i].y;
};
parsl_context *par_ctx = parsl_create_context((parsl_config){
.thickness = d,
.flags= PARSL_FLAG_ANNOTATIONS,
.u_mode = PAR_U_MODE_DISTANCE
});
parsl_mesh *mesh = parsl_mesh_from_lines(par_ctx, (parsl_spine_list){
.num_vertices = n,
.num_spines = 1,
.vertices = par_v,
.spine_lengths = spine_lens,
.closed = 0,
});
HMM_Vec2 *ret = NULL;
arraddn(ret,mesh->num_vertices);
for (int i = 0; i < mesh->num_vertices; i++) {
ret[i].x = mesh->positions[i].x;
ret[i].y = mesh->positions[i].y;
};
return ret;
}
/* Given a strip of points, draws them as segments. So 5 points is 4 segments, and ultimately 8 vertices */
void draw_edge(HMM_Vec2 *points, int n, struct rgba color, float thickness, int flags, struct rgba line_color, float line_seg)
{
int closed = 0;
if (thickness <= 0) {
draw_line(points,n,line_color,0,0);
return;
}
/* todo: should be dashed, and filled. use a texture. */
/* draw polygon outline */
if (HMM_EqV2(points[0], points[n-1])) {
closed = true;
n--;
}
parsl_position par_v[n];
for (int i = 0; i < n; i++) {
par_v[i].x = points[i].x;
par_v[i].y = points[i].y;
}
uint16_t spine_lens[] = {n};
parsl_context *par_ctx = parsl_create_context((parsl_config){
.thickness = thickness,
.flags = PARSL_FLAG_ANNOTATIONS,
});
parsl_mesh *mesh = parsl_mesh_from_lines(par_ctx, (parsl_spine_list){
.num_vertices = n,
.num_spines = 1,
.vertices = par_v,
.spine_lengths = spine_lens,
.closed = closed
});
for (int i = 0; i < mesh->num_triangles*3; i++)
mesh->triangle_indices[i] += (poly_v+poly_sv);
struct poly_vertex vertices[mesh->num_vertices];
for (int i = 0; i < mesh->num_vertices; i++) {
vertices[i].pos = (struct draw_p){ .x = mesh->positions[i].x, .y = mesh->positions[i].y };
vertices[i].uv[0] = mesh->annotations[i].u_along_curve;
vertices[i].uv[1] = mesh->annotations[i].v_across_curve;
vertices[i].color = color;
}
sg_append_buffer(poly_bind.vertex_buffers[0], &(sg_range){.ptr = vertices, .size = sizeof(struct poly_vertex)*mesh->num_vertices});
sg_append_buffer(poly_bind.index_buffer, &(sg_range){.ptr = mesh->triangle_indices, sizeof(uint32_t)*mesh->num_triangles*3});
poly_c += mesh->num_triangles*3;
poly_v += mesh->num_vertices;
parsl_destroy_context(par_ctx);
/* Now drawing the line outlines */
if (thickness == 1) {
draw_line(points,n,line_color,line_seg, 0);
} else {
HMM_Vec2 in_p[n];
HMM_Vec2 out_p[n];
for (int i = 1, v = 0; i < n*2+1; i+=2, v++) {
in_p[v].x = vertices[i].pos.x;
in_p[v].y = vertices[i].pos.y;
}
for (int i = 0, v = 0; i < n*2; i+=2,v++) {
out_p[v].x = vertices[i].pos.x;
out_p[v].y = vertices[i].pos.y;
}
if (!closed) {
HMM_Vec2 p[n*2];
for (int i = 0; i < n; i++)
p[i] = in_p[i];
for (int i = n-1, v = n; i >= 0; i--,v++)
p[v] = out_p[i];
draw_line(p,n*2,line_color,line_seg,0);
return;
}
draw_line(in_p,n,line_color,line_seg,0);
draw_line(out_p,n,line_color,line_seg,0);
}
}
void draw_circle(HMM_Vec2 pos, float radius, float pixels, struct rgba color, float seg)
{
struct circle_vertex cv;
cv.pos.x = pos.x;
cv.pos.y = pos.y;
cv.radius = radius;
cv.color = color;
cv.segsize = seg/radius;
cv.fill = pixels/radius;
sg_append_buffer(circle_bind.vertex_buffers[0], &(sg_range){.ptr = &cv, .size = sizeof(struct circle_vertex)});
circle_count++;
}
void draw_box(HMM_Vec2 c, HMM_Vec2 wh, struct rgba color)
{
float hw = wh.x / 2.f;
float hh = wh.y / 2.f;
HMM_Vec2 verts[4] = {
{ .x = c.x-hw, .y = c.y-hh },
{ .x = c.x+hw, .y = c.y-hh },
{ .x = c.x+hw, .y = c.y+hh },
{ .x = c.x-hw, .y = c.y+hh }
};
draw_poly(verts, 4, color);
}
void draw_grid(float width, float span, struct rgba color)
{
HMM_Vec2 offset = campos;
offset = HMM_MulV2F(offset, 1/camzoom);
float ubo[4];
ubo[0] = offset.x;
ubo[1] = offset.y;
ubo[2] = mainwin.size.x;
ubo[3] = mainwin.size.y;
sg_apply_pipeline(grid_pipe);
sg_apply_bindings(&grid_bind);
float col[4];
rgba2floats(col,color);
fs_params_t pt;
pt.thickness = (float)width;
pt.span = span/camzoom;
memcpy(&pt.color, col, sizeof(float)*4);
sg_apply_uniforms(SG_SHADERSTAGE_VS, 0, SG_RANGE_REF(ubo));
sg_apply_uniforms(SG_SHADERSTAGE_FS, 0, SG_RANGE_REF(pt));
sg_draw(0,4,1);
}
void draw_cppoint(HMM_Vec2 point, float r, struct rgba color)
{
struct point_vertex p = {
.color = color,
.radius = r
};
p.pos.x = point.X;
p.pos.y = point.Y;
sg_append_buffer(point_bind.vertex_buffers[0], &(sg_range){.ptr = &p, .size = sizeof(struct point_vertex)});
point_c++;
}
void draw_points(HMM_Vec2 *points, int n, float size, struct rgba color)
{
for (int i = 0; i < n; i++)
draw_cppoint(points[i], size, color);
}
void draw_poly(HMM_Vec2 *points, int n, struct rgba color)
{
/* Find polygon mesh */
int tric = n - 2;
if (tric < 1) return;
uint32_t tridxs[tric*3];
for (int i = 2, ti = 0; i < n; i++, ti+=3) {
tridxs[ti] = 0;
tridxs[ti+1] = i-1;
tridxs[ti+2] = i;
}
for (int i = 0; i < tric*3; i++)
tridxs[i] += poly_v+poly_sv;
struct poly_vertex polyverts[n];
for (int i = 0; i < n; i++) {
polyverts[i].pos = (struct draw_p) { .x = points[i].x, .y = points[i].y};
polyverts[i].uv[0] = 0.0;
polyverts[i].uv[1] = 0.0;
polyverts[i].color = color;
}
sg_append_buffer(poly_bind.vertex_buffers[0], &(sg_range){.ptr = polyverts, .size = sizeof(struct poly_vertex)*n});
sg_append_buffer(poly_bind.index_buffer, &(sg_range){.ptr = tridxs, sizeof(uint32_t)*3*tric});
poly_c += tric*3;
poly_v += n;
}

View file

@ -1,27 +0,0 @@
#ifndef DEBUGDRAW_H
#define DEBUGDRAW_H
#include "HandmadeMath.h"
struct rgba;
void debugdraw_init();
void draw_cppoint(HMM_Vec2 point, float r, struct rgba color);
void draw_points(HMM_Vec2 *points, int n, float size, struct rgba color);
void draw_line(HMM_Vec2 *points, int n, struct rgba color, float seg_len, float seg_speed);
void draw_line3d(HMM_Vec3 *points, int n, struct rgba color, float seg_len, float seg_speed);
void draw_edge(HMM_Vec2 *points, int n, struct rgba color, float thickness, int flags, struct rgba line_color, float line_seg);
/* pixels - how many pixels thick, segsize - dashed line seg len */
void draw_circle(HMM_Vec2 c, float radius, float pixels, struct rgba color, float seg);
void draw_box(HMM_Vec2 c, HMM_Vec2 wh, struct rgba color);
void draw_poly(HMM_Vec2 *points, int n, struct rgba color);
void draw_grid(float width, float span, struct rgba color);
void debug_flush(HMM_Mat4 *view);
void debug_newframe();
HMM_Vec2 *inflatepoints(HMM_Vec2 *p, float d, int n);
#endif

View file

@ -10,7 +10,6 @@
#include <string.h> #include <string.h>
#include <window.h> #include <window.h>
#include "resources.h" #include "resources.h"
#include "debugdraw.h"
#include "render.h" #include "render.h"
#include "stb_image_write.h" #include "stb_image_write.h"
@ -172,8 +171,6 @@ void draw_char_box(struct Character c, HMM_Vec2 cursor, float scale, struct rgba
HMM_Vec2 b; HMM_Vec2 b;
b.x = cursor.X + wh.x/2; b.x = cursor.X + wh.x/2;
b.y = cursor.Y + wh.y/2; b.y = cursor.Y + wh.y/2;
draw_box(b, wh, color);
} }
void text_flush() { void text_flush() {

View file

@ -2,7 +2,6 @@
#include "2dphysics.h" #include "2dphysics.h"
#include <string.h> #include <string.h>
#include "debugdraw.h"
#include "log.h" #include "log.h"
#include "math.h" #include "math.h"

View file

@ -1,7 +1,6 @@
#include "jsffi.h" #include "jsffi.h"
#include "script.h" #include "script.h"
#include "debugdraw.h"
#include "font.h" #include "font.h"
#include "gameobject.h" #include "gameobject.h"
#include "input.h" #include "input.h"
@ -11,7 +10,6 @@
#include "2dphysics.h" #include "2dphysics.h"
#include "datastream.h" #include "datastream.h"
#include "sound.h" #include "sound.h"
#include "sprite.h"
#include "stb_ds.h" #include "stb_ds.h"
#include "string.h" #include "string.h"
#include "window.h" #include "window.h"
@ -33,6 +31,8 @@
#include "model.h" #include "model.h"
#include "HandmadeMath.h" #include "HandmadeMath.h"
#include "par/par_streamlines.h" #include "par/par_streamlines.h"
#include "par/par_shapes.h"
#include "sokol_glue.h"
#if (defined(_WIN32) || defined(__WIN32__)) #if (defined(_WIN32) || defined(__WIN32__))
#include <direct.h> #include <direct.h>
@ -75,7 +75,6 @@ QJSCLASS(emitter)
QJSCLASS(dsp_node) QJSCLASS(dsp_node)
QJSCLASS(texture) QJSCLASS(texture)
QJSCLASS(font) QJSCLASS(font)
QJSCLASS(sprite)
QJSCLASS(warp_gravity) QJSCLASS(warp_gravity)
QJSCLASS(warp_damp) QJSCLASS(warp_damp)
QJSCLASS(material) QJSCLASS(material)
@ -627,49 +626,56 @@ JSC_CCALL(emitter_emit, emitter_emit(js2emitter(this), js2number(argv[0]), js2tr
JSC_CCALL(emitter_step, emitter_step(js2emitter(this), js2number(argv[0]), js2transform2d(argv[1]))) JSC_CCALL(emitter_step, emitter_step(js2emitter(this), js2number(argv[0]), js2transform2d(argv[1])))
JSC_CCALL(emitter_draw, emitter_draw(js2emitter(this), js2bind(argv[0], argv[1]))) JSC_CCALL(emitter_draw, emitter_draw(js2emitter(this), js2bind(argv[0], argv[1])))
JSC_CCALL(render_grid, draw_grid(js2number(argv[0]), js2number(argv[1]), js2color(argv[2]));)
JSC_CCALL(render_point, draw_cppoint(js2vec2(argv[0]), js2number(argv[1]), js2color(argv[2])))
JSC_CCALL(render_circle, draw_circle(js2vec2(argv[0]), js2number(argv[1]), js2number(argv[2]), js2color(argv[3]), -1);)
JSC_CCALL(render_poly,
int n = js_arrlen(argv[0]);
HMM_Vec2 points[n];
for (int i = 0; i < n; i++)
points[i] = js2vec2(js_getpropidx(argv[0], i));
draw_poly(points, n, js2color(argv[1]));
)
JSC_CCALL(render_line,
void *v1 = js2cpvec2arr(argv[0]);
draw_edge(v1, js_arrlen(argv[0]), js2color(argv[1]), js2number(argv[2]), 0, js2color(argv[1]), 10);
arrfree(v1);
)
JSC_CCALL(render_line3d,
void *v1 = js2cpvec3arr(argv[0]);
draw_line3d(v1, js_arrlen(argv[0]), js2color(argv[1]), 0, 0);
arrfree(v1);
);
JSC_CCALL(render_flush, debug_flush(&useproj); )
JSC_CCALL(render_flushtext, text_flush()) JSC_CCALL(render_flushtext, text_flush())
JSC_CCALL(render_end_pass, JSC_CCALL(render_end_pass,
sg_end_pass();
sg_begin_pass(&(sg_pass){
.swapchain = sglue_swapchain(),
.action = (sg_pass_action){
.colors[0] = {
.load_action = SG_LOADACTION_CLEAR,
.clear_value = (sg_color){0,0,0,1}
}
}
});
sg_pipeline p = {0};
switch(mainwin.mode) {
case MODE_STRETCH:
sg_apply_viewportf(0,0,mainwin.size.x,mainwin.size.y,1);
break;
case MODE_WIDTH:
sg_apply_viewportf(0, mainwin.top, mainwin.size.x, mainwin.psize.y,1); // keep width
break;
case MODE_HEIGHT:
sg_apply_viewportf(mainwin.left,0,mainwin.psize.x, mainwin.size.y,1); // keep height
break;
case MODE_KEEP:
sg_apply_viewportf(0,0,mainwin.rendersize.x, mainwin.rendersize.y, 1); // no scaling
break;
case MODE_EXPAND:
if (mainwin.aspect < mainwin.raspect)
sg_apply_viewportf(0, mainwin.top, mainwin.size.x, mainwin.psize.y,1); // keep width
else
sg_apply_viewportf(mainwin.left,0,mainwin.psize.x, mainwin.size.y,1); // keep height
break;
}
p.id = js2number(argv[0]);
sg_apply_pipeline(p);
sg_bindings bind = js2bind(argv[1], argv[2]);
bind.fs.images[0] = screencolor;
bind.fs.samplers[0] = std_sampler;
sg_apply_bindings(&bind);
int c = js2number(js_getpropstr(argv[2], "count"));
sg_draw(0,c,1);
sg_end_pass(); sg_end_pass();
sg_commit(); sg_commit();
debug_newframe();
) )
JSC_SCALL(render_text_size, ret = bb2js(text_bb(str, js2number(argv[1]), js2number(argv[2]), 1))) JSC_SCALL(render_text_size, ret = bb2js(text_bb(str, js2number(argv[1]), js2number(argv[2]), 1)))
JSC_CCALL(render_set_camera, useproj = projection) JSC_CCALL(render_set_camera, useproj = projection)
JSC_CCALL(render_hud_res,
HMM_Vec2 xy = js2vec2(argv[0]);
useproj = HMM_Orthographic_RH_ZO(0, xy.x, 0, xy.y, -1, 1);
)
JSC_CCALL(render_clear_color,
sg_color c;
rgba2floats(&c, js2color(argv[0]));
pass_action.colors[0].clear_value = c;
)
sg_shader js2shader(JSValue v) sg_shader js2shader(JSValue v)
{ {
@ -739,32 +745,6 @@ sg_shader js2shader(JSValue v)
return sh; return sh;
} }
JSC_CCALL(render_pipeline3d,
sg_shader sgshader = js2shader(argv[0]);
sg_pipeline_desc p = {0};
p.shader = sgshader;
sg_vertex_layout_state st = {0};
st.attrs[MAT_POS].format = SG_VERTEXFORMAT_FLOAT3;
st.attrs[MAT_UV].format = SG_VERTEXFORMAT_USHORT2N;
st.attrs[MAT_UV].buffer_index = MAT_UV;
st.attrs[MAT_NORM].format = SG_VERTEXFORMAT_UINT10_N2;
st.attrs[MAT_NORM].buffer_index = MAT_NORM;
st.attrs[MAT_WEIGHT].format = SG_VERTEXFORMAT_UBYTE4N;
st.attrs[MAT_WEIGHT].buffer_index = MAT_WEIGHT;
st.attrs[MAT_BONE].format = SG_VERTEXFORMAT_UBYTE4;
st.attrs[MAT_BONE].buffer_index = MAT_BONE;
st.attrs[MAT_COLOR].format = SG_VERTEXFORMAT_UBYTE4N;
st.attrs[MAT_COLOR].buffer_index = MAT_COLOR;
p.layout = st;
p.index_type = SG_INDEXTYPE_UINT16;
p.depth.write_enabled = true;
p.depth.compare = SG_COMPAREFUNC_LESS_EQUAL;
p.cull_mode = SG_CULLMODE_FRONT;
sg_pipeline pipe = sg_make_pipeline(&p);
return number2js(pipe.id);
)
sg_vertex_layout_state js2layout(JSValue v) sg_vertex_layout_state js2layout(JSValue v)
{ {
sg_vertex_layout_state st = {0}; sg_vertex_layout_state st = {0};
@ -780,40 +760,18 @@ sg_vertex_layout_state js2layout(JSValue v)
return st; return st;
} }
JSC_CCALL(render_pipelineparticle,
sg_pipeline_desc p = {0};
p.shader = js2shader(argv[0]);
p.layout = js2layout(argv[0]);
p.primitive_type = SG_PRIMITIVETYPE_TRIANGLE_STRIP;
p.index_type = SG_INDEXTYPE_UINT16;
//p.cull_mode = SG_CULLMODE_BACK;
//p.colors[0].blend = blend_trans;
//p.depth.write_enabled = true;
//p.depth.compare = SG_COMPAREFUNC_LESS_EQUAL;
sg_pipeline pipe = sg_make_pipeline(&p);
return number2js(pipe.id);
)
JSC_CCALL(render_pipelinetext,
sg_pipeline_desc p = {0};
p.shader = js2shader(argv[0]);
p.layout = js2layout(argv[0]);
p.primitive_type = SG_PRIMITIVETYPE_TRIANGLE_STRIP;
p.colors[0].blend = blend_trans;
sg_pipeline pipe = sg_make_pipeline(&p);
return number2js(pipe.id);
)
JSC_CCALL(render_pipeline, JSC_CCALL(render_pipeline,
sg_pipeline_desc p = {0}; sg_pipeline_desc p = {0};
p.shader = js2shader(argv[0]); p.shader = js2shader(argv[0]);
p.layout = js2layout(argv[0]); p.layout = js2layout(argv[0]);
//p.cull_mode = SG_CULLMODE_FRONT; p.cull_mode = js2number(js_getpropstr(argv[0], "cull"));
p.primitive_type = js2number(js_getpropstr(argv[0], "primitive"));
p.index_type = SG_INDEXTYPE_UINT16; p.index_type = SG_INDEXTYPE_UINT16;
if (js2boolean(js_getpropstr(argv[0], "blend"))) if (js2boolean(js_getpropstr(argv[0], "blend")))
p.colors[0].blend = blend_trans; p.colors[0].blend = blend_trans;
//p.depth.write_enabled = true;
//p.depth.compare = SG_COMPAREFUNC_LESS_EQUAL;
sg_pipeline pipe = sg_make_pipeline(&p); sg_pipeline pipe = sg_make_pipeline(&p);
@ -841,7 +799,7 @@ JSC_CCALL(render_setuniv4,
) )
JSC_CCALL(render_setuniproj, JSC_CCALL(render_setuniproj,
sg_apply_uniforms(js2number(argv[0]), js2number(argv[1]), SG_RANGE_REF(useproj)); sg_apply_uniforms(js2number(argv[0]), js2number(argv[1]), SG_RANGE_REF(projection));
) )
JSC_CCALL(render_setunim4, JSC_CCALL(render_setunim4,
@ -877,23 +835,11 @@ JSC_CCALL(render_setpipeline,
) )
static const JSCFunctionListEntry js_render_funcs[] = { static const JSCFunctionListEntry js_render_funcs[] = {
MIST_FUNC_DEF(render, grid, 3),
MIST_FUNC_DEF(render, point, 3),
MIST_FUNC_DEF(render, circle, 3),
MIST_FUNC_DEF(render, poly, 2),
MIST_FUNC_DEF(render, line, 3),
MIST_FUNC_DEF(render, line3d, 2),
MIST_FUNC_DEF(render, flushtext, 0), MIST_FUNC_DEF(render, flushtext, 0),
MIST_FUNC_DEF(render, flush, 0),
MIST_FUNC_DEF(render, end_pass, 0), MIST_FUNC_DEF(render, end_pass, 0),
MIST_FUNC_DEF(render, text_size, 3), MIST_FUNC_DEF(render, text_size, 3),
MIST_FUNC_DEF(render, set_camera, 0), MIST_FUNC_DEF(render, set_camera, 0),
MIST_FUNC_DEF(render, hud_res, 1),
MIST_FUNC_DEF(render, clear_color, 1),
MIST_FUNC_DEF(render, pipeline, 1), MIST_FUNC_DEF(render, pipeline, 1),
MIST_FUNC_DEF(render, pipeline3d, 1),
MIST_FUNC_DEF(render, pipelinetext, 1),
MIST_FUNC_DEF(render, pipelineparticle, 1),
MIST_FUNC_DEF(render, setuniv3, 2), MIST_FUNC_DEF(render, setuniv3, 2),
MIST_FUNC_DEF(render, setuniv, 2), MIST_FUNC_DEF(render, setuniv, 2),
MIST_FUNC_DEF(render, spdraw, 1), MIST_FUNC_DEF(render, spdraw, 1),
@ -959,6 +905,49 @@ JSValue js_vector_dot(JSContext *js, JSValue this, int argc, JSValue *argv) { re
JSC_CCALL(vector_project, return vec22js(HMM_ProjV2(js2vec2(argv[0]), js2vec2(argv[1])))) JSC_CCALL(vector_project, return vec22js(HMM_ProjV2(js2vec2(argv[0]), js2vec2(argv[1]))))
/* Given a series of points p, computes a new series with them expanded on either side by d */
HMM_Vec2 *inflatepoints(HMM_Vec2 *p, float d, int n)
{
if (d == 0) {
HMM_Vec2 *ret = NULL;
arraddn(ret,n);
for (int i = 0; i < n; i++)
ret[i] = p[i];
return ret;
}
parsl_position par_v[n];
uint16_t spine_lens[] = {n};
for (int i = 0; i < n; i++) {
par_v[i].x = p[i].x;
par_v[i].y = p[i].y;
};
parsl_context *par_ctx = parsl_create_context((parsl_config){
.thickness = d,
.flags= PARSL_FLAG_ANNOTATIONS,
.u_mode = PAR_U_MODE_DISTANCE
});
parsl_mesh *mesh = parsl_mesh_from_lines(par_ctx, (parsl_spine_list){
.num_vertices = n,
.num_spines = 1,
.vertices = par_v,
.spine_lengths = spine_lens,
.closed = 0,
});
HMM_Vec2 *ret = NULL;
arraddn(ret,mesh->num_vertices);
for (int i = 0; i < mesh->num_vertices; i++) {
ret[i].x = mesh->positions[i].x;
ret[i].y = mesh->positions[i].y;
};
return ret;
}
JSC_CCALL(vector_inflate, JSC_CCALL(vector_inflate,
HMM_Vec2 *p = js2cpvec2arr(argv[0]); HMM_Vec2 *p = js2cpvec2arr(argv[0]);
double d = js2number(argv[1]); double d = js2number(argv[1]);
@ -1572,16 +1561,6 @@ static const JSCFunctionListEntry js_pshape_funcs[] = {
MIST_FUNC_DEF(pshape, get_enabled, 1) MIST_FUNC_DEF(pshape, get_enabled, 1)
}; };
JSC_GETSET(sprite, color, color)
JSC_GETSET(sprite, emissive, color)
JSC_GETSET(sprite, spriteoffset, vec2)
static const JSCFunctionListEntry js_sprite_funcs[] = {
CGETSET_ADD(sprite,color),
CGETSET_ADD(sprite,emissive),
CGETSET_ADD(sprite, spriteoffset),
};
JSC_GET(texture, width, number) JSC_GET(texture, width, number)
JSC_GET(texture, height, number) JSC_GET(texture, height, number)
JSC_GET(texture, frames, number) JSC_GET(texture, frames, number)
@ -1731,11 +1710,6 @@ JSC_CCALL(os_exit, exit(js2number(argv[0]));)
JSC_CCALL(os_reindex_static, cpSpaceReindexStatic(space)); JSC_CCALL(os_reindex_static, cpSpaceReindexStatic(space));
JSC_CCALL(os_gc, script_gc()); JSC_CCALL(os_gc, script_gc());
JSC_SSCALL(os_eval, ret = script_eval(str, str2)) JSC_SSCALL(os_eval, ret = script_eval(str, str2))
JSC_SCALL(os_capture, capture_screen(js2number(argv[1]), js2number(argv[2]), js2number(argv[4]), js2number(argv[5]), str))
JSC_CCALL(os_sprite,
return sprite2js(sprite_make());
)
JSC_CCALL(os_make_gameobject, JSC_CCALL(os_make_gameobject,
ret = gameobject2js(MakeGameobject()); ret = gameobject2js(MakeGameobject());
@ -1800,7 +1774,6 @@ JSC_CCALL(os_make_transform2d,
) )
JSC_SCALL(os_system, return number2js(system(str)); ) JSC_SCALL(os_system, return number2js(system(str)); )
JSC_SCALL(os_make_model, ret = model2js(model_make(str))) JSC_SCALL(os_make_model, ret = model2js(model_make(str)))
JSC_CCALL(os_make_emitter, ret = emitter2js(make_emitter())) JSC_CCALL(os_make_emitter, ret = emitter2js(make_emitter()))
@ -1843,7 +1816,7 @@ JSC_CCALL(os_make_line_prim,
parsl_context *par_ctx = parsl_create_context((parsl_config){ parsl_context *par_ctx = parsl_create_context((parsl_config){
.thickness = js2number(argv[1]), .thickness = js2number(argv[1]),
.flags= PARSL_FLAG_ANNOTATIONS, .flags= PARSL_FLAG_ANNOTATIONS,
.u_mode = PAR_U_MODE_NORMALIZED_DISTANCE .u_mode = js2number(argv[2])
}); });
uint16_t spine_lens[] = {arrlen(v)}; uint16_t spine_lens[] = {arrlen(v)};
@ -1852,15 +1825,20 @@ JSC_CCALL(os_make_line_prim,
.num_vertices = arrlen(v), .num_vertices = arrlen(v),
.num_spines = 1, .num_spines = 1,
.vertices = par_v, .vertices = par_v,
.spine_lengths = spine_lens .spine_lengths = spine_lens,
.closed = js2boolean(argv[3])
}); });
HMM_Vec3 a_pos[m->num_vertices];
for (int i = 0; i < m->num_vertices; i++) {
a_pos[i].x = m->positions[i].x;
a_pos[i].y = m->positions[i].y;
a_pos[i].z = 0;
}
sg_buffer *pos = malloc(sizeof(*pos)); sg_buffer *pos = malloc(sizeof(*pos));
*pos = sg_make_buffer(&(sg_buffer_desc){ *pos = sg_make_buffer(&(sg_buffer_desc){
.data = (sg_range){ .data = SG_RANGE(a_pos),
.ptr = m->positions,
.size = sizeof(parsl_position)*m->num_vertices
}
}); });
js_setpropstr(prim, "pos", sg_buffer2js(pos)); js_setpropstr(prim, "pos", sg_buffer2js(pos));
js_setpropstr(prim, "count", number2js(m->num_triangles*3)); js_setpropstr(prim, "count", number2js(m->num_triangles*3));
@ -1873,18 +1851,86 @@ JSC_CCALL(os_make_line_prim,
for (int i = 0; i < m->num_vertices; i++) { for (int i = 0; i < m->num_vertices; i++) {
uv[i*2] = m->annotations[i].u_along_curve; uv[i*2] = m->annotations[i].u_along_curve;
uv[i*2+1] = m->annotations[i].v_across_curve; uv[i*2+1] = m->annotations[i].v_across_curve;
printf("uv is %g,%g\n", uv[i*2], uv[i*2+1]);
} }
sg_buffer *buv = malloc(sizeof(*buv)); sg_buffer *buv = malloc(sizeof(*buv));
*buv = texcoord_floats(uv, m->num_vertices*2); *buv = texcoord_floats(uv, m->num_vertices*2);
//*buv = float_buffer(uv, m->num_vertices*2);
js_setpropstr(prim, "uv", sg_buffer2js(buv)); js_setpropstr(prim, "uv", sg_buffer2js(buv));
return prim; return prim;
) )
JSValue parmesh2js(par_shapes_mesh *m)
{
JSValue obj = JS_NewObject(js);
sg_buffer *pos = malloc(sizeof(*pos));
*pos = float_buffer(m->points, 3*m->npoints);
js_setpropstr(obj, "pos", sg_buffer2js(pos));
if (m->tcoords) {
sg_buffer *uv = malloc(sizeof(*uv));
*uv = texcoord_floats(m->tcoords, 2*m->npoints);
js_setpropstr(obj, "uv", sg_buffer2js(uv));
}
if (m->normals) {
sg_buffer *norm = malloc(sizeof(*norm));
*norm = normal_floats(m->normals, 3*m->npoints);
js_setpropstr(obj, "norm", sg_buffer2js(norm));
}
sg_buffer *index = malloc(sizeof(*index));
*index = sg_make_buffer(&(sg_buffer_desc){
.data = {
.ptr = m->triangles,
.size = sizeof(*m->triangles)*3*m->ntriangles
},
.type = SG_BUFFERTYPE_INDEXBUFFER
});
js_setpropstr(obj, "index", sg_buffer2js(index));
js_setpropstr(obj, "count", number2js(3*m->ntriangles));
par_shapes_free_mesh(m);
return obj;
}
JSC_CCALL(os_make_cylinder,
return parmesh2js(par_shapes_create_cylinder(js2number(argv[0]), js2number(argv[1])));
)
JSC_CCALL(os_make_cone,
return parmesh2js(par_shapes_create_cone(js2number(argv[0]), js2number(argv[1])));
)
JSC_CCALL(os_make_disk,
return parmesh2js(par_shapes_create_parametric_disk(js2number(argv[0]), js2number(argv[1])));
)
JSC_CCALL(os_make_torus,
return parmesh2js(par_shapes_create_torus(js2number(argv[0]), js2number(argv[1]), js2number(argv[2])));
)
JSC_CCALL(os_make_sphere,
return parmesh2js(par_shapes_create_parametric_sphere(js2number(argv[0]), js2number(argv[1])));
)
JSC_CCALL(os_make_klein_bottle,
return parmesh2js(par_shapes_create_klein_bottle(js2number(argv[0]), js2number(argv[1])));
)
JSC_CCALL(os_make_trefoil_knot,
return parmesh2js(par_shapes_create_trefoil_knot(js2number(argv[0]), js2number(argv[1]), js2number(argv[2])));
)
JSC_CCALL(os_make_hemisphere,
return parmesh2js(par_shapes_create_hemisphere(js2number(argv[0]), js2number(argv[1])));
)
JSC_CCALL(os_make_plane,
return parmesh2js(par_shapes_create_plane(js2number(argv[0]), js2number(argv[1])));
)
static const JSCFunctionListEntry js_os_funcs[] = { static const JSCFunctionListEntry js_os_funcs[] = {
MIST_FUNC_DEF(os,sprite,0),
MIST_FUNC_DEF(os, cwd, 0), MIST_FUNC_DEF(os, cwd, 0),
MIST_FUNC_DEF(os, env, 1), MIST_FUNC_DEF(os, env, 1),
MIST_FUNC_DEF(os, sys, 0), MIST_FUNC_DEF(os, sys, 0),
@ -1893,7 +1939,6 @@ static const JSCFunctionListEntry js_os_funcs[] = {
MIST_FUNC_DEF(os, exit, 1), MIST_FUNC_DEF(os, exit, 1),
MIST_FUNC_DEF(os, reindex_static, 0), MIST_FUNC_DEF(os, reindex_static, 0),
MIST_FUNC_DEF(os, gc, 0), MIST_FUNC_DEF(os, gc, 0),
MIST_FUNC_DEF(os, capture, 5),
MIST_FUNC_DEF(os, eval, 2), MIST_FUNC_DEF(os, eval, 2),
MIST_FUNC_DEF(os, make_gameobject, 0), MIST_FUNC_DEF(os, make_gameobject, 0),
MIST_FUNC_DEF(os, make_circle2d, 2), MIST_FUNC_DEF(os, make_circle2d, 2),
@ -1906,6 +1951,15 @@ static const JSCFunctionListEntry js_os_funcs[] = {
MIST_FUNC_DEF(os, make_emitter, 0), MIST_FUNC_DEF(os, make_emitter, 0),
MIST_FUNC_DEF(os, make_buffer, 1), MIST_FUNC_DEF(os, make_buffer, 1),
MIST_FUNC_DEF(os, make_line_prim, 2), MIST_FUNC_DEF(os, make_line_prim, 2),
MIST_FUNC_DEF(os, make_cylinder, 2),
MIST_FUNC_DEF(os, make_cone, 2),
MIST_FUNC_DEF(os, make_disk, 2),
MIST_FUNC_DEF(os, make_torus, 3),
MIST_FUNC_DEF(os, make_sphere, 2),
MIST_FUNC_DEF(os, make_klein_bottle, 2),
MIST_FUNC_DEF(os, make_trefoil_knot, 3),
MIST_FUNC_DEF(os, make_hemisphere, 2),
MIST_FUNC_DEF(os, make_plane, 2)
}; };
#include "steam.h" #include "steam.h"
@ -1916,7 +1970,6 @@ void ffi_load() {
QJSCLASSPREP(ptr); QJSCLASSPREP(ptr);
QJSCLASSPREP(transform3d); QJSCLASSPREP(transform3d);
QJSGLOBALCLASS(os); QJSGLOBALCLASS(os);
QJSCLASSPREP_FUNCS(gameobject); QJSCLASSPREP_FUNCS(gameobject);
@ -1925,7 +1978,6 @@ void ffi_load() {
QJSCLASSPREP_FUNCS(emitter); QJSCLASSPREP_FUNCS(emitter);
QJSCLASSPREP_FUNCS(warp_gravity); QJSCLASSPREP_FUNCS(warp_gravity);
QJSCLASSPREP_FUNCS(warp_damp); QJSCLASSPREP_FUNCS(warp_damp);
QJSCLASSPREP_FUNCS(sprite);
QJSCLASSPREP_FUNCS(texture); QJSCLASSPREP_FUNCS(texture);
QJSCLASSPREP_FUNCS(font); QJSCLASSPREP_FUNCS(font);
QJSCLASSPREP_FUNCS(constraint); QJSCLASSPREP_FUNCS(constraint);

View file

@ -2,11 +2,9 @@
#include "config.h" #include "config.h"
#include "datastream.h" #include "datastream.h"
#include "debugdraw.h"
#include "font.h" #include "font.h"
#include "gameobject.h" #include "gameobject.h"
#include "log.h" #include "log.h"
#include "sprite.h"
#include "particle.h" #include "particle.h"
#include "window.h" #include "window.h"
#include "model.h" #include "model.h"
@ -19,109 +17,26 @@
#include "stb_image_write.h" #include "stb_image_write.h"
#include "sokol/sokol_gfx.h" #include "sokol/sokol_gfx.h"
#include "sokol_gfx_ext.h"
#include "crt.sglsl.h" static HMM_Vec2 lastuse = {0};
#include "msf_gif.h"
HMM_Vec2 campos = {0,0}; HMM_Vec2 campos = {0,0};
float camzoom = 1; float camzoom = 1;
sg_sampler std_sampler; sg_sampler std_sampler;
sg_sampler nofilter_sampler;
sg_sampler tex_sampler; sg_sampler tex_sampler;
static struct { sg_pass offscreen;
sg_swapchain swap;
sg_pipeline pipe;
sg_bindings bind;
sg_shader shader;
sg_image img;
sg_image depth;
} sg_gif;
static struct {
sg_pipeline pipe;
sg_bindings bind;
sg_shader shader;
} sg_crt;
static struct {
int w;
int h;
int cpf;
int depth;
double timer;
double spf;
int rec;
uint8_t *buffer;
} gif;
MsfGifState gif_state = {};
void gif_rec_start(int w, int h, int cpf, int bitdepth)
{
gif.w = w;
gif.h = h;
gif.depth = bitdepth;
msf_gif_begin(&gif_state, gif.w, gif.h);
gif.cpf = cpf;
gif.spf = cpf/100.0;
gif.rec = 1;
gif.timer = apptime();
if (gif.buffer) free(gif.buffer);
gif.buffer = malloc(gif.w*gif.h*4);
sg_destroy_image(sg_gif.img);
sg_destroy_image(sg_gif.depth);
sg_gif.img = sg_make_image(&(sg_image_desc){
.render_target = true,
.width = gif.w,
.height = gif.h,
.pixel_format = SG_PIXELFORMAT_RGBA8,
.label = "gif rt",
});
sg_gif.depth = sg_make_image(&(sg_image_desc){
.render_target = true,
.width = gif.w,
.height = gif.h,
.label = "gif depth",
});
sg_gif.swap = sglue_swapchain();
}
void gif_rec_end(const char *path)
{
if (!gif.rec) return;
MsfGifResult gif_res = msf_gif_end(&gif_state);
if (gif_res.data) {
FILE *f = fopen(path, "wb");
fwrite(gif_res.data, gif_res.dataSize, 1, f);
fclose(f);
}
msf_gif_free(gif_res);
gif.rec = 0;
}
void capture_screen(int x, int y, int w, int h, const char *path)
{
int n = 4;
void *data = malloc(w*h*n);
sg_query_pixels(0,0,w,h,1,data,w*h*sizeof(char)*n);
// sg_query_image_pixels(crt_post.img, crt_post.bind.fs.samplers[0], data, w*h*4);
stbi_write_png("cap.png", w, h, n, data, n*w);
// stbi_write_bmp("cap.bmp", w, h, n, data);
free(data);
}
#include "sokol/sokol_app.h" #include "sokol/sokol_app.h"
#include "HandmadeMath.h" #include "HandmadeMath.h"
sg_pass_action pass_action = {0}; sg_pass_action pass_action = {0};
sg_pass_action off_action = {0};
sg_image screencolor = {0};
sg_image screendepth = {0};
void trace_apply_pipeline(sg_pipeline pip, void *data) void trace_apply_pipeline(sg_pipeline pip, void *data)
{ {
@ -230,58 +145,81 @@ void render_init() {
#endif #endif
font_init(); font_init();
debugdraw_init();
sg_color c = (sg_color){0,0,0,1}; sg_color c = (sg_color){0,0,0,1};
pass_action = (sg_pass_action){ pass_action = (sg_pass_action){
.colors[0] = {.load_action = SG_LOADACTION_CLEAR, .clear_value = c}, .colors[0] = {.load_action = SG_LOADACTION_CLEAR, .clear_value = c},
}; };
sg_color oc = (sg_color){35.0/255,60.0/255,92.0/255,1};
off_action = (sg_pass_action){
.colors[0] = {.load_action = SG_LOADACTION_CLEAR, .clear_value = oc}
};
screencolor = sg_make_image(&(sg_image_desc){
.render_target = true,
.width = 500,
.height = 500,
.pixel_format = sapp_color_format(),
.sample_count = 1,
});
screendepth = sg_make_image(&(sg_image_desc){
.render_target = true,
.width =500,
.height=500,
.pixel_format = sapp_depth_format(),
.sample_count = 1
});
offscreen = (sg_pass){
.attachments = sg_make_attachments(&(sg_attachments_desc){
.colors[0].image = screencolor,
.depth_stencil.image = screendepth
}),
.action = off_action,
};
} }
HMM_Mat4 projection = {0.f}; HMM_Mat4 projection = {0.f};
HMM_Mat4 hudproj = {0.f}; HMM_Mat4 hudproj = {0.f};
HMM_Mat4 useproj = {0}; HMM_Mat4 useproj = {0};
#define MODE_STRETCH 0
#define MODE_KEEP 1
#define MODE_WIDTH 2
#define MODE_HEIGHT 3
#define MODE_EXPAND 4
#define MODE_FULL 5
void openglRender(struct window *window, transform2d *cam, float zoom) { void openglRender(struct window *window, transform2d *cam, float zoom) {
sg_swapchain sch = sglue_swapchain(); HMM_Vec2 usesize = mainwin.rendersize;
sg_begin_pass(&(sg_pass){ if (mainwin.mode == MODE_FULL)
.action = pass_action, usesize = mainwin.size;
.swapchain = sglue_swapchain(), //sg_apply_viewportf(0,0,usesize.x,usesize.y,1);
.label = "window pass" if (usesize.x != lastuse.x || usesize.y != lastuse.y) {
printf("Redoing to %g,%g\n", usesize.x, usesize.y);
sg_destroy_image(screencolor);
sg_destroy_image(screendepth);
sg_destroy_attachments(offscreen.attachments);
screencolor = sg_make_image(&(sg_image_desc){
.render_target = true,
.width = usesize.x,
.height = usesize.y,
.pixel_format = sapp_color_format(),
.sample_count = 1,
}); });
screendepth = sg_make_image(&(sg_image_desc){
HMM_Vec2 usesize = window->rendersize; .render_target = true,
.width =usesize.x,
switch(window->mode) { .height=usesize.y,
case MODE_STRETCH: .pixel_format = sapp_depth_format(),
sg_apply_viewportf(0,0,window->size.x,window->size.y,1); .sample_count = 1
break; });
case MODE_WIDTH: offscreen = (sg_pass){
sg_apply_viewportf(0, window->top, window->size.x, window->psize.y,1); // keep width .attachments = sg_make_attachments(&(sg_attachments_desc){
break; .colors[0].image = screencolor,
case MODE_HEIGHT: .depth_stencil.image = screendepth
sg_apply_viewportf(window->left,0,window->psize.x, window->size.y,1); // keep height }),
break; .action = off_action,
case MODE_KEEP: };
sg_apply_viewportf(0,0,window->rendersize.x, window->rendersize.y, 1); // no scaling }
break; lastuse = usesize;
case MODE_EXPAND: sg_begin_pass(&offscreen);
if (window->aspect < window->raspect)
sg_apply_viewportf(0, window->top, window->size.x, window->psize.y,1); // keep width
else
sg_apply_viewportf(window->left,0,window->psize.x, window->size.y,1); // keep height
break;
case MODE_FULL:
usesize = window->size;
break;
}
// 2D projection // 2D projection
campos = cam->pos; campos = cam->pos;
@ -292,22 +230,6 @@ void openglRender(struct window *window, transform2d *cam, float zoom) {
campos.x + camzoom * usesize.x / 2, campos.x + camzoom * usesize.x / 2,
campos.y - camzoom * usesize.y / 2, campos.y - camzoom * usesize.y / 2,
campos.y + camzoom * usesize.y / 2, -10000.f, 10000.f); campos.y + camzoom * usesize.y / 2, -10000.f, 10000.f);
/* if (gif.rec && (apptime() - gif.timer) > gif.spf) {
sg_begin_pass(&(sg_pass){
.action = pass_action,
.swapchain = sg_gif.swap
});
sg_apply_pipeline(sg_gif.pipe);
sg_apply_bindings(&sg_gif.bind);
sg_draw(0,6,1);
sg_end_pass();
gif.timer = apptime();
sg_query_image_pixels(sg_gif.img, crt_post.bind.fs.samplers[0], gif.buffer, gif.w*gif.h*4);
msf_gif_frame(&gif_state, gif.buffer, gif.cpf, gif.depth, gif.w * -4);
}
*/
} }
struct boundingbox cwh2bb(HMM_Vec2 c, HMM_Vec2 wh) { struct boundingbox cwh2bb(HMM_Vec2 c, HMM_Vec2 wh) {

View file

@ -1,15 +1,7 @@
#ifndef OPENGL_RENDER_H #ifndef OPENGL_RENDER_H
#define OPENGL_RENDER_H #define OPENGL_RENDER_H
#if defined __linux__ #include "config.h"
#define SOKOL_GLCORE33
#elif __EMSCRIPTEN__
#define SOKOL_GLES3
#elif __WIN32
#define SOKOL_D3D11
#elif __APPLE__
#define SOKOL_METAL
#endif
#include "sokol/sokol_gfx.h" #include "sokol/sokol_gfx.h"
#include "HandmadeMath.h" #include "HandmadeMath.h"
@ -17,6 +9,13 @@
#include "transform.h" #include "transform.h"
#include "model.h" #include "model.h"
#define MODE_STRETCH 0
#define MODE_KEEP 1
#define MODE_WIDTH 2
#define MODE_HEIGHT 3
#define MODE_EXPAND 4
#define MODE_FULL 5
#define RGBA_MAX 255 #define RGBA_MAX 255
#include "window.h" #include "window.h"
@ -36,6 +35,8 @@ extern sg_pass_action pass_action;
extern sg_sampler std_sampler; extern sg_sampler std_sampler;
extern sg_sampler tex_sampler; extern sg_sampler tex_sampler;
extern sg_image screencolor;
extern sg_image screendepth;
struct draw_p { struct draw_p {
float x; float x;

View file

@ -1,306 +0,0 @@
/*
sokol_gfx_ext.h - extensions for sokol_gfx
https://github.com/edubart/sokol_gp
*/
#if defined(SOKOL_IMPL) && !defined(SOKOL_GFX_EXT_IMPL)
#define SOKOL_GFX_EXT_IMPL
#endif
#ifndef SOKOL_GFX_EXT_INCLUDED
#define SOKOL_GFX_EXT_INCLUDED
#ifndef SOKOL_GFX_INCLUDED
#error "Please include sokol_gfx.h before sokol_gfx_ext.h"
#endif
#include <stdbool.h>
#include <stdint.h>
SOKOL_GFX_API_DECL void sg_query_image_pixels(sg_image img_id, sg_sampler smp_id, void* pixels, int size);
SOKOL_GFX_API_DECL void sg_query_pixels(int x, int y, int w, int h, bool origin_top_left, void *pixels, int size);
#endif // SOKOL_GFX_EXT_INCLUDED
#ifdef SOKOL_GFX_EXT_IMPL
#ifndef SOKOL_GFX_EXT_IMPL_INCLUDED
#define SOKOL_GFX_EXT_IMPL_INCLUDED
#ifndef SOKOL_GFX_IMPL_INCLUDED
#error "Please include sokol_gfx.h implementation before sokol_gp.h implementation"
#endif
#if defined(_SOKOL_ANY_GL)
static void _sg_gl_query_image_pixels(_sg_image_t* img, _sg_sampler_t *smp, void* pixels) {
SOKOL_ASSERT(img->gl.target == GL_TEXTURE_2D);
SOKOL_ASSERT(0 != img->gl.tex[img->cmn.active_slot]);
#if defined(SOKOL_GLCORE33)
_sg_gl_cache_store_texture_sampler_binding(0);
_sg_gl_cache_bind_texture_sampler(0, img->gl.target, img->gl.tex[img->cmn.active_slot], smp->gl.smp);
glGetTexImage(img->gl.target, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
_SG_GL_CHECK_ERROR();
_sg_gl_cache_restore_texture_sampler_binding(0);
#else
static GLuint newFbo = 0;
GLuint oldFbo = 0;
if(newFbo == 0) {
glGenFramebuffers(1, &newFbo);
}
glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&oldFbo);
glBindFramebuffer(GL_FRAMEBUFFER, newFbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, img->gl.tex[img->cmn.active_slot], 0);
glReadPixels(0, 0, img->cmn.width, img->cmn.height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
glBindFramebuffer(GL_FRAMEBUFFER, oldFbo);
//glDeleteFramebuffers(1, &newFbo);
_SG_GL_CHECK_ERROR();
#endif
}
static void _sg_gl_query_pixels(int x, int y, int w, int h, bool origin_top_left, void *pixels) {
SOKOL_ASSERT(pixels);
GLuint gl_fb;
GLint dims[4];
glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&gl_fb);
_SG_GL_CHECK_ERROR();
glGetIntegerv(GL_VIEWPORT, dims);
int cur_height = dims[3];
y = origin_top_left ? (cur_height - (y+h)) : y;
_SG_GL_CHECK_ERROR();
#if defined(SOKOL_GLES2) // use NV extension instead
glReadBufferNV(gl_fb == 0 ? GL_BACK : GL_COLOR_ATTACHMENT0);
#else
glReadBuffer(gl_fb == 0 ? GL_BACK : GL_COLOR_ATTACHMENT0);
#endif
_SG_GL_CHECK_ERROR();
glReadPixels(x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
_SG_GL_CHECK_ERROR();
}
#elif defined(SOKOL_D3D11)
static inline void _sgext_d3d11_Texture2D_GetDesc(ID3D11Texture2D* self, D3D11_TEXTURE2D_DESC* pDesc) {
self->lpVtbl->GetDesc(self, pDesc);
}
static inline void _sgext_d3d11_SamplerState_GetDesc(ID3D11SamplerState* self, D3D11_SAMPLER_DESC* pDesc) {
self->lpVtbl->GetDesc(self, pDesc);
}
static inline void _sgext_d3d11_CopySubresourceRegion(ID3D11DeviceContext* self, ID3D11Resource *pDstResource, UINT DstSubresource, UINT DstX, UINT DstY, UINT DstZ, ID3D11Resource *pSrcResource, UINT SrcSubresource, const D3D11_BOX *pSrcBox) {
self->lpVtbl->CopySubresourceRegion(self, pDstResource, DstSubresource, DstX, DstY, DstZ, pSrcResource, SrcSubresource, pSrcBox);
}
static inline void _sgext_d3d11_OMGetRenderTargets(ID3D11DeviceContext* self, UINT NumViews, ID3D11RenderTargetView **ppRenderTargetViews, ID3D11DepthStencilView **ppDepthStencilView) {
self->lpVtbl->OMGetRenderTargets(self, NumViews, ppRenderTargetViews, ppDepthStencilView);
}
static inline void _sgext_d3d11_RenderTargetView_GetResource(ID3D11RenderTargetView* self, ID3D11Resource** ppResource) {
self->lpVtbl->GetResource(self, ppResource);
}
static void _sg_d3d11_query_image_pixels(_sg_image_t* img, void* pixels) {
SOKOL_ASSERT(_sg.d3d11.ctx);
SOKOL_ASSERT(img->d3d11.tex2d);
HRESULT hr;
_SOKOL_UNUSED(hr);
// create staging texture
ID3D11Texture2D* staging_tex = NULL;
D3D11_TEXTURE2D_DESC staging_desc = {
.Width = (UINT)img->cmn.width,
.Height = (UINT)img->cmn.height,
.MipLevels = 1,
.ArraySize = 1,
.Format = img->d3d11.format,
.SampleDesc = {
.Count = 1,
.Quality = 0,
},
.Usage = D3D11_USAGE_STAGING,
.BindFlags = 0,
.CPUAccessFlags = D3D11_CPU_ACCESS_READ,
.MiscFlags = 0
};
hr = _sg_d3d11_CreateTexture2D(_sg.d3d11.dev, &staging_desc, NULL, &staging_tex);
SOKOL_ASSERT(SUCCEEDED(hr));
// copy pixels to staging texture
_sgext_d3d11_CopySubresourceRegion(_sg.d3d11.ctx,
(ID3D11Resource*)staging_tex,
0, 0, 0, 0,
(ID3D11Resource*)img->d3d11.tex2d,
0, NULL);
// map the staging texture's data to CPU-accessible memory
D3D11_MAPPED_SUBRESOURCE msr = {.pData = NULL};
hr = _sg_d3d11_Map(_sg.d3d11.ctx, (ID3D11Resource*)staging_tex, 0, D3D11_MAP_READ, 0, &msr);
SOKOL_ASSERT(SUCCEEDED(hr));
memcpy(pixels, msr.pData, img->cmn.width * img->cmn.height * 4);
// unmap the texture
_sg_d3d11_Unmap(_sg.d3d11.ctx, (ID3D11Resource*)staging_tex, 0);
if(staging_tex) _sg_d3d11_Release(staging_tex);
}
static void _sg_d3d11_query_pixels(int x, int y, int w, int h, bool origin_top_left, void *pixels) {
// get current render target
ID3D11RenderTargetView* render_target_view = NULL;
_sgext_d3d11_OMGetRenderTargets(_sg.d3d11.ctx, 1, &render_target_view, NULL);
// fallback to window render target
if(!render_target_view)
render_target_view = (ID3D11RenderTargetView*)_sg.d3d11.cur_pass.render_view;
SOKOL_ASSERT(render_target_view);
// get the back buffer texture
ID3D11Texture2D *back_buffer = NULL;
_sgext_d3d11_RenderTargetView_GetResource(render_target_view, (ID3D11Resource**)&back_buffer);
SOKOL_ASSERT(back_buffer);
// create a staging texture to copy the screen's data to
D3D11_TEXTURE2D_DESC staging_desc;
_sgext_d3d11_Texture2D_GetDesc(back_buffer, &staging_desc);
staging_desc.Width = w;
staging_desc.Height = h;
staging_desc.BindFlags = 0;
staging_desc.MiscFlags = 0;
staging_desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
staging_desc.Usage = D3D11_USAGE_STAGING;
ID3D11Texture2D *staging_tex = NULL;
HRESULT hr = _sg_d3d11_CreateTexture2D(_sg.d3d11.dev, &staging_desc, NULL, &staging_tex);
SOKOL_ASSERT(SUCCEEDED(hr));
_SOKOL_UNUSED(hr);
// copy the desired portion of the back buffer to the staging texture
// y = (origin_top_left ? y : (_sg.d3d11.cur_height - (y + h)));
D3D11_BOX src_box = {
.left = (UINT)x,
.top = (UINT)y,
.front = 0,
.right = (UINT)(x + w),
.bottom = (UINT)(y + w),
.back = 1,
};
_sgext_d3d11_CopySubresourceRegion(_sg.d3d11.ctx,
(ID3D11Resource*)staging_tex,
0, 0, 0, 0,
(ID3D11Resource*)back_buffer,
0, &src_box);
// map the staging texture's data to CPU-accessible memory
D3D11_MAPPED_SUBRESOURCE msr = {.pData = NULL};
hr = _sg_d3d11_Map(_sg.d3d11.ctx, (ID3D11Resource*)staging_tex, 0, D3D11_MAP_READ, 0, &msr);
SOKOL_ASSERT(SUCCEEDED(hr));
memcpy(pixels, msr.pData, w * h * 4);
// unmap the texture
_sg_d3d11_Unmap(_sg.d3d11.ctx, (ID3D11Resource*)staging_tex, 0);
if(back_buffer) _sg_d3d11_Release(back_buffer);
if(staging_tex) _sg_d3d11_Release(staging_tex);
}
#elif defined(SOKOL_METAL)
#ifdef TARGET_OS_IPHONE
static void _sg_metal_commit_command_buffer(){};
static void _sg_metal_encode_texture_pixels(int x, int y, int w, int h, bool origin_top_left, id<MTLTexture> mtl_src_texture, void* pixels) {};
static void _sg_metal_query_image_pixels(_sg_image_t* img, void* pixels) {};
static void _sg_metal_query_pixels(int x, int y, int w, int h, bool origin_top_left, void *pixels) {};
#else
#import <Metal/Metal.h>
#import <QuartzCore/CAMetalLayer.h>
static void _sg_metal_commit_command_buffer() {
SOKOL_ASSERT(!_sg.mtl.in_pass);
if(_sg.mtl.cmd_buffer) {
#if defined(_SG_TARGET_MACOS)
[_sg.mtl.uniform_buffers[_sg.mtl.cur_frame_rotate_index] didModifyRange:NSMakeRange(0, _sg.mtl.cur_ub_offset)];
#endif
[_sg.mtl.cmd_buffer commit];
[_sg.mtl.cmd_buffer waitUntilCompleted];
_sg.mtl.cmd_buffer = [_sg.mtl.cmd_queue commandBufferWithUnretainedReferences];
}
}
static void _sg_metal_encode_texture_pixels(int x, int y, int w, int h, bool origin_top_left, id<MTLTexture> mtl_src_texture, void* pixels) {
SOKOL_ASSERT(!_sg.mtl.in_pass);
_sg_metal_commit_command_buffer();
MTLTextureDescriptor* mtl_dst_texture_desc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:mtl_src_texture.pixelFormat width:w height:h mipmapped:NO];
mtl_dst_texture_desc.storageMode = MTLStorageModeManaged;
mtl_dst_texture_desc.resourceOptions = MTLResourceStorageModeManaged;
mtl_dst_texture_desc.usage = MTLTextureUsageShaderRead + MTLTextureUsageShaderWrite;
id<MTLTexture> mtl_dst_texture = [mtl_src_texture.device newTextureWithDescriptor:mtl_dst_texture_desc];
id<MTLCommandBuffer> cmd_buffer = [_sg.mtl.cmd_queue commandBuffer];
id<MTLBlitCommandEncoder> blit_encoder = [cmd_buffer blitCommandEncoder];
[blit_encoder copyFromTexture:mtl_src_texture
sourceSlice:0
sourceLevel:0
sourceOrigin:MTLOriginMake(x,(origin_top_left ? y : (mtl_src_texture.height - (y + h))),0)
sourceSize:MTLSizeMake(w,h,1)
toTexture:mtl_dst_texture
destinationSlice:0
destinationLevel:0
destinationOrigin:MTLOriginMake(0,0,0)
];
[blit_encoder synchronizeTexture:mtl_dst_texture slice:0 level:0];
[blit_encoder endEncoding];
[cmd_buffer commit];
[cmd_buffer waitUntilCompleted];
MTLRegion mtl_region = MTLRegionMake2D(0, 0, w, h);
[mtl_dst_texture getBytes:pixels bytesPerRow:w * 4 fromRegion:mtl_region mipmapLevel:0];
}
static void _sg_metal_query_image_pixels(_sg_image_t* img, void* pixels) {
id<MTLTexture> mtl_src_texture = _sg.mtl.idpool.pool[img->mtl.tex[0]];
_sg_metal_encode_texture_pixels(0, 0, mtl_src_texture.width, mtl_src_texture.height, true, mtl_src_texture, pixels);
}
static void _sg_metal_query_pixels(int x, int y, int w, int h, bool origin_top_left, void *pixels) {
id<CAMetalDrawable> mtl_drawable = (__bridge id<CAMetalDrawable>)_sg.mtl.drawable_cb();
_sg_metal_encode_texture_pixels(x, y, w, h, origin_top_left, mtl_drawable.texture, pixels);
}
#endif
#endif
void sg_query_image_pixels(sg_image img_id, sg_sampler smp_id, void* pixels, int size) {
SOKOL_ASSERT(pixels);
SOKOL_ASSERT(img_id.id != SG_INVALID_ID);
_sg_image_t* img = _sg_lookup_image(&_sg.pools, img_id.id);
_sg_sampler_t *smp = _sg_lookup_sampler(&_sg.pools, smp_id.id);
SOKOL_ASSERT(img);
SOKOL_ASSERT(size >= (img->cmn.width * img->cmn.height * 4));
_SOKOL_UNUSED(size);
#if defined(_SOKOL_ANY_GL)
_sg_gl_query_image_pixels(img, smp, pixels);
#elif defined(SOKOL_D3D11)
_sg_d3d11_query_image_pixels(img, pixels);
#elif defined(SOKOL_METAL)
_sg_metal_query_image_pixels(img, pixels);
#endif
}
void sg_query_pixels(int x, int y, int w, int h, bool origin_top_left, void *pixels, int size) {
SOKOL_ASSERT(pixels);
SOKOL_ASSERT(size >= w*h);
_SOKOL_UNUSED(size);
#if defined(_SOKOL_ANY_GL)
_sg_gl_query_pixels(x, y, w, h, origin_top_left, pixels);
#elif defined(SOKOL_D3D11)
_sg_d3d11_query_pixels(x, y, w, h, origin_top_left, pixels);
#elif defined(SOKOL_METAL)
_sg_metal_query_pixels(x, y, w, h, origin_top_left, pixels);
#endif
}
#endif // SOKOL_GFX_EXT_IMPL_INCLUDED
#endif // SOKOL_GFX_EXT_IMPL

View file

@ -1,19 +0,0 @@
#include "sprite.h"
#include "gameobject.h"
#include "log.h"
#include "render.h"
#include "stb_ds.h"
#include "texture.h"
#include "HandmadeMath.h"
sprite *sprite_make()
{
sprite *sp = calloc(sizeof(*sp), 1);
sp->color = color_white;
sp->emissive = color_clear;
sp->rect = (HMM_Vec4){0,0,1,1};
return sp;
}
void sprite_free(sprite *sprite) { free(sprite); }

View file

@ -1,20 +0,0 @@
#ifndef SPRITE_H
#define SPRITE_H
#include "texture.h"
#include "HandmadeMath.h"
#include "render.h"
#include "transform.h"
#include "gameobject.h"
typedef struct sprite {
struct rgba color;
struct rgba emissive;
HMM_Vec4 rect;
HMM_Vec2 spriteoffset;
} sprite;
sprite *sprite_make();
void sprite_free(sprite *sprite);
#endif

View file

@ -8,12 +8,10 @@
#include "resources.h" #include "resources.h"
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#include "stb_image_resize2.h" #include "stb_image_resize2.h"
#include <stdio.h> #include <stdio.h>
#define QOI_IMPLEMENTATION
#include "qoi.h" #include "qoi.h"
#ifndef NSVG #ifndef NSVG

View file

@ -103,7 +103,6 @@ void seghandle()
void c_clean() { void c_clean() {
JS_FreeValue(js, c_process_fn); JS_FreeValue(js, c_process_fn);
cleanup(); cleanup();
gif_rec_end("out.gif");
saudio_shutdown(); saudio_shutdown();
sg_shutdown(); sg_shutdown();
}; };

View file

@ -1,12 +0,0 @@
#version 330 core
out vec4 FragColor;
in vec3 FragPos;
in vec2 TexCoords;
uniform sampler2D texture_diffuse1;
void main()
{
FragColor = texture(texture_diffuse1, TexCoords);
}

View file

@ -1,99 +0,0 @@
#version 330 core
out vec4 FragColor;
struct Light {
vec3 direction;
vec3 color;
};
struct PLight {
vec3 position;
vec3 color;
float constant;
float linear;
float quadratic;
};
struct SLight {
vec3 position;
vec3 direction;
float cutOff;
float outerCutOff;
};
uniform vec3 objectColor;
uniform vec3 lightColor;
uniform vec3 lightPos;
uniform vec3 viewPos;
uniform sampler2D diffuseTex;
uniform sampler2D specTex;
uniform float shininess;
uniform Light light;
uniform PLight plight;
uniform SLight slight;
in vec3 Normal;
in vec3 FragPos;
in vec2 TexCoords;
float near = 0.1;
float far = 100.0;
float LinearizeDepth(float depth)
{
float z = depth * 2.0 - 1.0; // back to NDC
return (2.0 * near * far) / (far + near - z * (far - near));
}
// void main()
// {
// float depth = LinearizeDepth(gl_FragCoord.z) / far; // divide by far for demonstration
// FragColor = vec4(vec3(depth), 1.0);
// }
void main()
{
//vec3 dirDir = normalize(-Directional.direction);
float ambientStrength = 1.f;
vec3 ambient = ambientStrength * vec3(texture(diffuseTex, TexCoords));
// vec3 norm = normalize(Normal);
// vec3 diffuse;
// Directional
//vec3 lightDir = normalize(-light.direction);
// Point
// float distance = length(plight.position - FragPos);
// float attenuation = 1.f / (plight.constant + plight.linear * distance + plight.quadratic * (distance * distance));
// vec3 lightDir = normalize(lightPos - FragPos);
// float diff = max(dot(norm, lightDir), 0.f);
//diffuse = diff * lightColor * vec3(texture(diffuseTex, TexCoords)) * attenuation;
// Spot
// lightDir = normalize(slight.position - FragPos);
// float theta = dot(lightDir, normalize(-slight.direction));
// float epsilon = slight.cutOff - slight.outerCutOff;
// float intensity = clamp((theta - slight.outerCutOff) / epsilon, 0.f, 1.f);
// diffuse = lightColor * diff * vec3(texture(diffuseTex, TexCoords)) * intensity;
// float specularStrength = 0.5f;
// vec3 viewDir = normalize(viewPos - FragPos);
// vec3 reflectDir = reflect(-lightDir, norm);
// float spec = pow(max(dot(viewDir, reflectDir), 0.f), 32);
// vec3 specular = specularStrength * spec * lightColor * texture(specTex, TexCoords).rgb;
// if(texture(specTex, TexCoords).r < 0.1f)
// discard;
//vec3 result = (ambient + diffuse + specular) * objectColor;
FragColor = vec4(ambient, 1.f);
}

View file

@ -1,11 +0,0 @@
#version 330 core
layout (location = 0) out vec4 color;
in vec3 vcolor;
in vec3 FragPos;
void main(void)
{
color = vec4(vcolor, 1.f);
}

View file

@ -1,21 +0,0 @@
#version 330 core
layout (location = 0) in vec3 aPos;
layout (std140) uniform Matrices {
mat4 projection;
mat4 view;
};
out vec3 vcolor;
uniform mat4 model;
void main()
{
vec3 m = aPos;
vcolor.r = m.r / 1.f;
vcolor.g = m.g / 1.f;
vcolor.b = m.b / 1.f;
gl_Position = projection * view * model * (vec4(m, 1.f));
}

View file

@ -1,7 +0,0 @@
#version 330 core
out vec4 FragColor;
void main()
{
FragColor = vec4(1.0f); // set alle 4 vector values to 1.0
}

View file

@ -1,11 +0,0 @@
#version 330 core
layout (location = 0) in vec3 aPos;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main()
{
gl_Position = projection * view * model * vec4(aPos, 1.0);
}

View file

@ -1,185 +0,0 @@
#version 330 core
out vec4 FragColor;
struct Light {
vec3 direction;
vec3 color;
float strength;
};
struct PLight {
vec3 position;
float constant;
float linear;
float quadratic;
vec3 color;
float strength;
};
struct SpotLight {
vec3 position;
vec3 direction;
vec3 color;
float strength;
float cutoff;
float outerCutoff;
float distance;
float constant;
float linear;
float quadratic;
};
in vec3 FragPos;
in vec2 TexCoords;
in vec4 FragPosLightSpace;
in mat3 TBN;
//in vec3 TangentLightPos;
in vec3 TangentViewPos;
in vec3 TangentFragPos;
uniform sampler2D texture_diffuse1;
uniform sampler2D texture_normal1;
uniform sampler2D shadowMap;
uniform Light dirLight;
uniform vec3 viewPos;
vec3 norm;
vec3 viewDir;
#define NR_POINT_LIGHTS 1
uniform PLight pointLights[NR_POINT_LIGHTS];
uniform SpotLight spotLight;
float ShadowCalculation(vec4 fragPosLightSpace, vec3 normal, vec3 lightDir) {
// perform perspective divide
vec3 projCoords = fragPosLightSpace.xyz / fragPosLightSpace.w;
// transform to [0,1] range
projCoords = projCoords * 0.5 + 0.5;
// get closest depth value from light's perspective (using [0,1] range fragPosLight as coords)
float closestDepth = texture(shadowMap, projCoords.xy).r;
// get depth of current fragment from light's perspective
float currentDepth = projCoords.z;
// calculate bias (based on depth map resolution and slope)
float bias = max(0.05 * (1.0 - dot(normal, lightDir)), 0.005);
// check whether current frag pos is in shadow
// float shadow = currentDepth - bias > closest Depth ? 1.0 : 0.0;
// PCF
float shadow = 0.0;
vec2 texelSize = 1.0 / textureSize(shadowMap, 0);
for(int x = -1; x <= 1; ++x)
{
for(int y = -1; y <= 1; ++y)
{
float pcfDepth = texture(shadowMap, projCoords.xy + vec2(x, y) * texelSize).r;
shadow += currentDepth - bias > pcfDepth ? 1.0 : 0.0;
}
}
shadow /= 9.0;
// keep the shadow at 0.0 when outside the far_plane region of the light's frustum.
if(projCoords.z > 1.0)
shadow = 0.0;
return shadow;
}
vec3 CalcDirLight(Light light) {
vec3 lightDir = TBN * normalize(-light.direction);
float lightStrength = 3.f;
vec3 lightColor = vec3(1.f);
// diffuse shading
float diff = max(dot(norm, lightDir), 0.f);
// specular shading
float specularStrength = 0.5f;
vec3 reflectDir = reflect(-lightDir, norm);
vec3 halfwayDir = normalize(lightDir + viewDir); // Use this instead of reflectDir?
float spec = pow(max(dot(viewDir, halfwayDir), 0.0), 32.f) * specularStrength; // 32.f is "shininess"
float shadow = ShadowCalculation(FragPosLightSpace, norm, lightDir);
// combine results
return light.strength * (diff + spec) * (1.f-shadow) * light.color;
}
vec3 CalcPointLight(PLight light) {
vec3 tbnPos = TBN * light.position;
vec3 lightDir = normalize(tbnPos - TangentFragPos);
// Diffuse
float diff = max(dot(norm, lightDir), 0.f);
// specular
vec3 reflectDir = reflect(-lightDir, norm);
vec3 halfwayDir = normalize(lightDir + viewDir);
float spec = pow(max(dot(viewDir, halfwayDir), 0.f), 32.f);
// Attenuation
float distance = length(light.position - TangentFragPos);
float attenuation = 1.f / (light.constant + light.linear * distance + light.quadratic * (distance * distance));
return light.color * attenuation * light.strength * (diff + spec);
}
vec3 CalcSpotLight(SpotLight light) {
vec3 tbnPos = TBN * light.position;
vec3 tbnDir = TBN * light.direction;
vec3 lightDir = normalize(tbnPos - TangentFragPos);
float diff = max(dot(norm, lightDir), 0.f);
vec3 reflectDir = reflect(-lightDir, norm);
vec3 halfwayDir = normalize(lightDir + viewDir);
float spec = pow(max(dot(viewDir, halfwayDir), 0.f), 32.f);
float theta = dot(lightDir, normalize(-tbnDir));
float epsilon = light.cutoff - light.outerCutoff;
float intensity = clamp((theta - light.outerCutoff) / epsilon, 0.f, 1.f);
float distance = length(light.position - FragPos);
float attenuation = 1.f / (light.constant + light.linear * distance + light.quadratic * (distance * distance));
return light.color * light.strength * (diff + spec) * intensity * attenuation;
}
void main()
{
vec4 model = texture(texture_diffuse1, TexCoords);
if (model.a <= 0.1f)
discard;
vec3 albedo = model.rgb;
norm = texture(texture_normal1, TexCoords).rgb;
norm = normalize(norm * 2.f - 1.f);
//vec3 norm = normalize(TangentViewPos);
viewDir = normalize(TangentViewPos - TangentFragPos);
// Ambient doesn't change
float ambientStrength = 0.3f;
vec3 ambientColor = vec3(1.f);
vec3 ambient = ambientStrength * ambientColor;
// Per light calculation
// Directional
vec3 result = CalcDirLight(dirLight);
result += ambient;
// Point
for (int i = 0; i < NR_POINT_LIGHTS; i++)
result += CalcPointLight(pointLights[i]);
result += CalcSpotLight(spotLight);
FragColor = vec4(result * model.rgb, 1.f);
}

View file

@ -1,68 +0,0 @@
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;
layout (location = 2) in vec2 aTexCoords;
layout (location = 3) in vec3 aTangent;
layout (location = 4) in vec3 aBitangent;
layout (location = 5) in ivec4 boneIds;
layout (location = 6) in vec4 weights;
layout (std140) uniform Matrices {
mat4 projection;
mat4 view;
};
//out vec3 Normal;
out vec3 FragPos;
out vec2 TexCoords;
//out vec3 TangentLightPos;
out vec3 TangentViewPos;
out vec3 TangentFragPos;
out vec4 FragPosLightSpace;
out mat3 TBN;
uniform mat4 model;
uniform mat4 lightSpaceMatrix;
uniform vec3 viewPos;
const int MAX_BONES = 100;
const int MAX_BONE_INFLUENCE = 4;
uniform mat4 finalBonesMatrices[MAX_BONES];
void main()
{
vec4 totalPosition = vec4(0.f);
for (int i = 0; i < MAX_BONE_INFLUENCE; i++) {
if (boneIds[i] == -1)
continue;
if (boneIds[i] >= 4) {
totalPosition = vec4(aPos, 1.f);
break;
}
vec4 localPosition = finalBonesMatrices[boneIds[i]] * vec4(aPos, 1.f);
totalPosition += localPosition * weights[i];
vec3 localNormal = mat3(finalBonesMatrices[boneIds[i]]) * aNormal;
}
FragPos = vec3(model * vec4(aPos, 1.f));
TexCoords = aTexCoords;
mat3 normalMatrix = transpose(inverse(mat3(model)));
vec3 T = normalize(normalMatrix * aTangent);
vec3 N = normalize(normalMatrix * aNormal);
T = normalize(T - dot(T, N) * N);
vec3 B = cross(N, T);
TBN = transpose(mat3(T, B, N));
// TangentLightPos = TBN * lightPos;
TangentViewPos = TBN * viewPos;
TangentFragPos = TBN * FragPos;
FragPosLightSpace = lightSpaceMatrix * vec4(FragPos, 1.f);
gl_Position = projection * view * model * totalPosition;
}

View file

@ -1,7 +0,0 @@
#version 330 core
out vec4 FragColor;
void main()
{
FragColor = vec4(0.92f, 0.86f, 0.68f, 1.0f);
}

View file

@ -1,15 +0,0 @@
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;
layout (std140) uniform Matrices {
mat4 projection;
mat4 view;
};
uniform mat4 model;
void main()
{
gl_Position = projection * view * model * vec4(aPos + (aNormal * 2.f), 1.f);
}

View file

@ -1,19 +0,0 @@
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 2) in vec2 aTexCoords;
layout (std140) uniform Matrices {
mat4 projection;
mat4 view;
};
out vec2 TexCoords;
uniform mat4 model;
void main()
{
TexCoords = aTexCoords;
gl_Position = projection * view * model * vec4(aPos, 1.f);
}

View file

@ -1,11 +0,0 @@
#version 330 core
out vec4 FragColor;
in vec3 TexCoords;
uniform samplerCube skybox;
void main()
{
FragColor = texture(skybox, TexCoords);
}

View file

@ -1,18 +0,0 @@
#version 330 core
layout (location = 0) in vec3 aPos;
out vec3 TexCoords;
layout (std140) uniform Matrices {
mat4 projection;
mat4 view;
};
uniform mat4 skyview;
void main()
{
TexCoords = aPos;
vec4 pos = projection * skyview * vec4(aPos, 1.0);
gl_Position = pos.xyww;
}

View file

@ -1,22 +0,0 @@
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;
layout (location = 2) in vec2 aTexCoords;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
out vec3 Normal;
out vec3 FragPos;
out vec2 TexCoords;
void main()
{
FragPos = vec3(model * vec4(aPos, 1.f));
Normal = mat3(transpose(inverse(model))) * aNormal;
TexCoords = aTexCoords;
gl_Position = projection * view * model * vec4(aPos, 1.0f); // see how we directly give a vec3 to vec4's constructor
}

View file

@ -1,27 +0,0 @@
@vs bvs
in vec2 aPos;
in vec2 aTexCoords;
out vec2 TexCoords;
void main()
{
gl_Position = vec4(aPos.x, aPos.y, 0.0, 1.0);
TexCoords = aTexCoords;
}
@end
@fs bfs
in vec2 TexCoords;
out vec4 frag_color;
uniform texture2D diffuse;
uniform sampler smp;
void main()
{
frag_color = texture(sampler2D(diffuse,smp), TexCoords);
}
@end
@program box bvs bfs

View file

@ -1,64 +0,0 @@
@vs circle_vs
in vec2 vertex;
in vec2 apos;
in float aradius;
in vec4 acolor;
in float asegsize;
in float afill;
out vec2 coords;
out vec4 fcolor;
out float segsize;
out float fill;
out float radius;
uniform cvs_params { mat4 proj; };
void main()
{
gl_Position = proj * vec4((vertex * aradius) + apos, 0.0, 1.0);
coords = vertex;
fcolor = acolor;
segsize = asegsize;
fill = afill;
radius = aradius;
}
@end
@fs circle_fs
out vec4 color;
in vec2 coords;
in vec4 fcolor;
in float segsize;
in float fill;
in float radius;
#define PI 3.14
void main()
{
float px = 1/radius;
float R1 = 1.f;
float R2 = 1.0 - fill;
float dist = sqrt(pow(coords.x,2) + pow(coords.y,2));
color = fcolor;
float sm = 1 - smoothstep(R1-px,R1,dist);
float sm2 = smoothstep(R2-px,R2,dist);
float a = sm*sm2;
color = mix(vec4(0,0,0,0), fcolor, a);
if (segsize<0)
return;
float f = atan(coords.y, coords.x) + PI;
if (mod(f, segsize) < segsize/2)
discard;
}
@end
@program circle circle_vs circle_fs

View file

@ -1,45 +0,0 @@
@vs vs
in vec2 aPos;
in vec2 aTexCoords;
out vec2 TexCoords;
void main()
{
gl_Position = vec4(aPos.x, aPos.y, 0.0, 1.0);
TexCoords = aTexCoords;
}
@end
@fs fs
in vec2 TexCoords;
out vec4 frag_color;
uniform texture2D diffuse;
uniform sampler smp;
uniform mpara {
uniform vec2 screensize;
};
void main()
{
vec4 color = texture(sampler2D(diffuse,smp), TexCoords);
float avg = 0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b;
frag_color = vec4(avg,avg,avg,1.0);
float lc = screensize.y/2.0;
float line = TexCoords.y * lc;
float line_intensity = mod(float(line),2);
float off = line_intensity * 0.0005;
vec4 shift = vec4(off,0,0,0);
vec4 color_shift = vec4(0.001,0,0,0);
float r = color.r + color_shift.r + shift.r;
float g = color.g - color_shift.g + shift.g;
float b = color.b;
frag_color = vec4(r, g*0.99, b, 1.0) * clamp(line_intensity, 0.85, 1.0);
}
@end
@program crt vs fs

View file

@ -1,9 +0,0 @@
#version 330 core
out vec4 FragColor;
uniform vec3 PickingColor;
void main()
{
FragColor = vec4(PickingColor, 1.0); // orthographic
}

View file

@ -1,22 +0,0 @@
#version 330 core
out vec4 FragColor;
in vec2 TexCoords;
uniform sampler2D depthMap;
uniform float near_plane;
uniform float far_plane;
// required when using a perspective projection matrix
float LinearizeDepth(float depth)
{
float z = depth * 2.0 - 1.0; // Back to NDC
return (2.0 * near_plane * far_plane) / (far_plane + near_plane - z * (far_plane - near_plane));
}
void main()
{
float depthValue = texture(depthMap, TexCoords).r;
//FragColor = vec4(vec3(LinearizeDepth(depthValue) / far_plane), 1.0); // perspective
FragColor = texture(depthMap, TexCoords); // orthographic
}

View file

@ -1,49 +0,0 @@
@vs vs
in vec2 pos;
out vec2 apos;
uniform mpara {
uniform vec2 offset;
uniform vec2 dimen;
};
void main()
{
apos = ((pos*0.5)*dimen) + offset;
gl_Position = vec4(pos, 0.f, 1.f);
}
@end
@fs fs
out vec4 frag_color;
in vec2 apos;
uniform fs_params {
uniform float thickness;
uniform float span;
uniform vec4 color;
};
void main()
{
float t = thickness / span;
t /= 2.0;
vec2 bpos;
bpos.x = mod(apos.x, span) / span;
bpos.y = mod(apos.y, span) / span;
bpos.x -= t;
bpos.y -= t;
float comp = min(bpos.x, bpos.y);
if (comp > t)
discard;
comp += t;
frag_color = color;
}
@end
@program grid vs fs

View file

@ -1,87 +0,0 @@
@vs vsg3
// Shared set between most vertex shaders
uniform ViewUniforms {
uniform mat4 view;
uniform mat4 proj;
};
out vec3 nearPoint;
out vec3 farPoint;
out mat4 fragView;
out mat4 fragProj;
// Grid position are in xy clipped space
vec3 gridPlane[6] = vec3[](
vec3(1, 1, 0), vec3(-1, -1, 0), vec3(-1, 1, 0),
vec3(-1, -1, 0), vec3(1, 1, 0), vec3(1, -1, 0)
);
// normal vertice projection
vec3 UnprojectPoint(float x, float y, float z, mat4 view, mat4 projection) {
mat4 viewInv = inverse(view);
mat4 projInv = inverse(projection);
vec4 unprojectedPoint = viewInv * projInv * vec4(x, y, z, 1.0);
return unprojectedPoint.xyz / unprojectedPoint.w;
}
void main() {
vec3 p = gridPlane[gl_VertexIndex].xyz;
nearPoint = UnprojectPoint(p.x, p.y, 0.0, view, proj).xyz; // unprojecting on the near plane
farPoint = UnprojectPoint(p.x, p.y, 1.0, view, proj).xyz; // unprojecting on the far plane
fragView = view;
fragProj = proj;
gl_Position = vec4(p, 1.0); // using directly the clipped coordinates
}
@end
@fs fsg3
float near = 0.01;
float far = 100;
in vec3 nearPoint;
in vec3 farPoint;
in mat4 fragView;
in mat4 fragProj;
out vec4 outColor;
vec4 grid(vec3 fragPos3D, float scale, bool drawAxis) {
vec2 coord = fragPos3D.xz * scale;
vec2 derivative = fwidth(coord);
vec2 grid = abs(fract(coord - 0.5) - 0.5) / derivative;
float line = min(grid.x, grid.y);
float minimumz = min(derivative.y, 1);
float minimumx = min(derivative.x, 1);
vec4 color = vec4(0.2, 0.2, 0.2, 1.0 - min(line, 1.0));
// z axis
if(fragPos3D.x > -0.1 * minimumx && fragPos3D.x < 0.1 * minimumx)
color.z = 1.0;
// x axis
if(fragPos3D.z > -0.1 * minimumz && fragPos3D.z < 0.1 * minimumz)
color.x = 1.0;
return color;
}
float computeDepth(vec3 pos) {
vec4 clip_space_pos = fragProj * fragView * vec4(pos.xyz, 1.0);
return (clip_space_pos.z / clip_space_pos.w);
}
float computeLinearDepth(vec3 pos) {
vec4 clip_space_pos = fragProj * fragView * vec4(pos.xyz, 1.0);
float clip_space_depth = (clip_space_pos.z / clip_space_pos.w) * 2.0 - 1.0; // put back between -1 and 1
float linearDepth = (2.0 * near * far) / (far + near - clip_space_depth * (far - near)); // get linear value between 0.01 and 100
return linearDepth / far; // normalize
}
void main() {
float t = -nearPoint.y / (farPoint.y - nearPoint.y);
vec3 fragPos3D = nearPoint + t * (farPoint - nearPoint);
gl_FragDepth = computeDepth(fragPos3D);
float linearDepth = computeLinearDepth(fragPos3D);
float fading = max(0, (0.5 - linearDepth));
outColor = (grid(fragPos3D, 10, true) + grid(fragPos3D, 1, true))* float(t > 0); // adding multiple resolution for the grid
outColor.a *= fading;
}
@end
@program grid3d vsg3 fsg3

View file

@ -1,63 +0,0 @@
@vs lvs
in vec3 apos;
in float adist;
in vec4 acolor;
in float aseglen;
in float asegspeed;
out float dist;
out vec4 fcolor;
out float seg_len;
out float seg_speed;
uniform lvs_params { mat4 proj; };
void main()
{
gl_Position = proj * vec4(apos, 1.0);
fcolor = acolor;
dist = adist;
seg_len = aseglen;
seg_speed = asegspeed;
}
@end
@fs lfs
out vec4 color;
in float dist;
in vec4 fcolor;
in float seg_len;
in float seg_speed;
float pat = 0.5;
int pp = 0x0C24;
uniform lfs_params { uniform float time; };
void main()
{
color = fcolor;
if (seg_len == 0) return;
if (mod(dist+(time*seg_speed)*seg_len,seg_len)/seg_len < 0.5)
discard;
/*
int d = int(dist);
if (pp * mod((d / 20), 16) == 0)
discard;
*/
/*
float patrn = 16 * mod(dist,seg_len)/seg_len;
if (patrn < 8)
discard;
*/
}
@end
@program line lvs lfs

View file

@ -1,40 +0,0 @@
@vs vs
in vec4 vertex;
out vec2 TexCoords;
uniform vs_p { mat4 model; mat4 projection; };
void main()
{
TexCoords = vec2(vertex.x, 1.0 - vertex.y);
gl_Position = projection * model * vec4(vertex.xy, 0.0, 1.0);
}
@end
@fs fs
in vec2 TexCoords;
out vec4 color;
uniform texture2D texture_y;
uniform texture2D texture_cb;
uniform texture2D texture_cr;
uniform sampler smp;
mat4 rec601 = mat4(
1.16438, 0.00000, 1.59603, -0.87079,
1.16438, -0.39176, -0.81297, 0.52959,
1.16438, 2.01723, 0.00000, -1.08139,
0, 0, 0, 1
);
void main()
{
float y = texture(sampler2D(texture_y,smp), TexCoords).r;
float cb = texture(sampler2D(texture_cb,smp), TexCoords).r;
float cr = texture(sampler2D(texture_cr,smp), TexCoords).r;
color = vec4(y, cb, cr, 1.f) * rec601;
}
@end
@program mpeg2 vs fs

View file

@ -1,34 +0,0 @@
@vs pointvs
in vec2 apos;
in vec4 acolor;
in float aradius;
uniform pvs_p { mat4 proj; };
out vec4 fcolor;
void main()
{
gl_Position = proj * vec4(apos, 0.0, 1.0);
fcolor = acolor;
gl_PointSize = 1.0;
}
@end
@fs pointfs
out vec4 color;
in vec4 fcolor;
void main()
{
float d = length(gl_FragCoord.xy - vec2(0.5,0.5)); /* Should really pointcoord, normalized */
if (d >= 0.1)
discard;
color = fcolor;
}
@end
@program point pointvs pointfs

View file

@ -1,31 +0,0 @@
@vs polyvs
in vec2 apos;
in vec2 vuv;
in vec4 acolor;
out vec4 color;
out vec2 uv;
uniform polyvs_params { mat4 proj; };
void main()
{
color = acolor;
uv = vuv;
gl_Position = proj * vec4(apos, 0.0, 1.0);
}
@end
@fs polyfs
in vec4 color;
in vec2 uv;
out vec4 fcolor;
void main()
{
fcolor = color;
fcolor.x *= (1 + uv.x/100.0); /* Temp dbg fix so vuv compiles */
}
@end
@program poly polyvs polyfs

View file

@ -1,25 +0,0 @@
@vs svs
in vec3 aPos;
uniform vs_p {
mat4 lightSpaceMatrix;
mat4 model;
};
void main()
{
gl_Position = lightSpaceMatrix * model * vec4(aPos, 1.0);
}
@end
@fs sfs
out float frag_color;
void main()
{
// frag_color = encode_depth(gl_FragCoord.z);
frag_color = gl_FragCoord.z;
}
@end
@program shadow svs sfs

View file

@ -1,63 +0,0 @@
@block vptr
in vec3 a_pos;
in vec2 a_uv;
in vec4 a_norm;
out vec2 tex_coords;
out vec3 normal;
uniform vs_p { uniform mat4 vp; };
uniform vmodel { uniform mat4 model; };
@end
@vs vs
@include_block vptr
in vec4 a_bone;
in vec4 a_weight;
uniform skinv { uniform mat4 bones[50]; };
void main() {
mat4 tt = vp;
mat4 mm = model;
mat4 skin = bones[int(a_bone.x)] * a_weight.x;
skin += bones[int(a_bone.y)] * a_weight.y;
skin += bones[int(a_bone.z)] * a_weight.z;
skin += bones[int(a_bone.w)] * a_weight.w;
mat4 skinm = mm * skin;
gl_Position = tt * skinm * vec4(a_pos,1.0);
tex_coords = a_uv;
normal = (skinm * vec4(a_norm.xyz*2-1,0)).xyz;
}
@end
@vs vs_st
@include_block vptr
void main() {
gl_Position = vp * model * vec4(a_pos,1.0);
tex_coords = a_uv;
normal = (model * vec4(a_norm.xyz*2-1,0)).xyz;
}
@end
@fs fs
in vec2 tex_coords;
in vec3 normal;
out vec4 color;
uniform texture2D diffuse;
uniform sampler smp;
uniform lightf {
vec4 ambient;
};
void main() {
vec3 lightDir = normalize(vec3(0.5f, 0.5f, 1.0f));
float diff = max(dot(normal, lightDir), 0.0f);
color = texture(sampler2D(diffuse,smp),tex_coords) * ambient;
}
@end
@program unlit vs fs
@program unlit_st vs_st fs