I compiled a GTK program in MinGW environment. It worked perfect. Recently, I updated MinGW and recompiled the GTK program, then the program always stopped with Segmentation fault. I have tried to use gdb to look for errors but I couldn't. The config of GTK is exactly same in the old and new MinGW. Therefore, I am suspicious of MinGW environment that influences compilation. I found the version of gcc is different in two environment:
old MinGW new MinGW
gcc 3.4.5 4.7.2
Any idea? Does anybody meet the situation?
Another clue is about GTK itself. I found the program stopped here:
g_signal_emit_by_name(G_OBJECT(g_object_get_data(G_OBJECT(window), "plat_GA_canvas")), "expose-event", G_TYPE_NONE);
It is a canvas to draw a image according to different situation. Here it just sends a signal to expose the canvas. The curious thing is that it worked in the old MinGW. So I don't doubt it is the point of the problem. Just maybe a clue. By the way, I compiled the GTK program in a pure Linux environment at home. It also worked perfect.
Any idea? Please help.
#duskast, below is the part of the code. It is a little lengthy.
+++++++++++++++++++++++++++++++++++++++++++++++++++
The problem maybe happened -- g_signal_emit_by_name:
void ACC_platform_unit_num_changed (GtkWidget *box, GtkWidget *window)
{
int kind;
kind = gtk_option_menu_get_history((GtkOptionMenu *)box) + 1;
if(plat.unit_num != kind)
{
plat_GA_canvas_refresh (window);
g_signal_emit_by_name(G_OBJECT(g_object_get_data(G_OBJECT(window), "plat_GA_canvas")), "expose-event", G_TYPE_NONE);
plat.unit_num = kind;
if(plat.unit_num == 1)
{
gtk_widget_set_sensitive(g_object_get_data(G_OBJECT(window), "ACC_platform_if_gap"), FALSE);
gtk_widget_set_sensitive(g_object_get_data(G_OBJECT(window), "ACC_platform_if_big_gap"), FALSE);
gtk_widget_set_sensitive(g_object_get_data(G_OBJECT(window), "ACC_platform_gap_w"), FALSE);
gtk_widget_set_sensitive(g_object_get_data(G_OBJECT(window), "ACC_platform_live_load_gap"), FALSE);
}
else
{
gtk_widget_set_sensitive(g_object_get_data(G_OBJECT(window), "ACC_platform_if_gap"), TRUE);
if(plat.has_gap)
{
gtk_widget_set_sensitive(g_object_get_data(G_OBJECT(window), "ACC_platform_if_big_gap"), TRUE);
gtk_widget_set_sensitive(g_object_get_data(G_OBJECT(window), "ACC_platform_gap_w"), TRUE);
gtk_widget_set_sensitive(g_object_get_data(G_OBJECT(window), "ACC_platform_live_load_gap"), TRUE);
}
else
{
gtk_widget_set_sensitive(g_object_get_data(G_OBJECT(window), "ACC_platform_if_big_gap"), FALSE);
gtk_widget_set_sensitive(g_object_get_data(G_OBJECT(window), "ACC_platform_gap_w"), FALSE);
gtk_widget_set_sensitive(g_object_get_data(G_OBJECT(window), "ACC_platform_live_load_gap"), FALSE);
}
}
gap_span_show (g_object_get_data(G_OBJECT(window), "ACC_platform_gap_span_store"));
}
}
The core drawing function:
void ACC_GA_draw (cairo_t *cr, int width, int height)
{
/* #define X_MARGIN 30
#define Y_MARGIN 30 */
#define COLUMN_RADIUS_ASSUME 1.6
#define COLUMN_SQUARE_LEN_ASSUME 2.0
double x, y, x1, y1, x2, y2, scale, x_base, y_base, X_MARGIN, Y_MARGIN;
double x3, y3, downward_height = 0, downward_width = 0;
double x_one_unit, y_one_unit, x_total, y_total, gap_value;
double alpha = 60.0, arrow_side_length = 20.0, arrow_tail_length = 10.0;
ACC_AXIS *x_axis, *y_axis;
int i, j, unit_num, downward;
char *AX, *AY, *Wx_left, *Wx_right, *Wy_top, *Wy_bottom, *gap, *axis;
cairo_text_extents_t te;
AX = g_strdup_printf("%.0f", plat.fan_section_AX * 1000);
AY = g_strdup_printf("%.0f", plat.fan_section_AY * 1000);
Wx_left = g_strdup_printf("%.0f", plat.walkway_Wx_left * 1000);
Wx_right = g_strdup_printf("%.0f", plat.walkway_Wx_right * 1000);
Wy_bottom = g_strdup_printf("%.0f", plat.walkway_Wy_bottom * 1000);
Wy_top = g_strdup_printf("%.0f", plat.walkway_Wy_top * 1000);
x_one_unit = plat.fan_section_AX * plat.SDD_num;
x_total = x_one_unit * plat.unit_num + plat.gap_total + plat.walkway_Wx_left + plat.walkway_Wx_right;
y_one_unit = plat.fan_section_AY * plat.row_num;
y_total = y_one_unit + plat.walkway_Wy_bottom + plat.walkway_Wy_top;
scale = calcu_scale (width, height, x_total, y_total, Wx_left, Wy_top, cr, &X_MARGIN, &Y_MARGIN);
cairo_set_line_width (cr, NORMAL_LINE_WIDTH * 0.7);
for(unit_num = 1; unit_num <= plat.unit_num; unit_num++)
{
if(unit_num == 1)
x_base = X_MARGIN;
else
{
double total_gap = 0;
for(i = 0; i < unit_num - 1; i++)
total_gap += strtod(g_list_nth(plat.gap_w, i)->data, NULL);
x_base = X_MARGIN + (x_one_unit * (unit_num - 1) + total_gap) * scale;
}
y_base = Y_MARGIN;
for(i = 0, x_axis = plat.X_axis; x_axis; x_axis = x_axis->next, i++)
{
if(i == 0)
x = x_base;
else
x += plat.fan_section_AX * scale;
y = y_base;
cairo_move_to(cr, x, y);
y += y_one_unit * scale;
cairo_line_to(cr, x, y); /* vertical grid */
cairo_stroke(cr);
/* SDD */
if(i != plat.SDD_num)
{
cairo_arrow (cr, x + plat.fan_section_AX / 2 * scale, y + plat.walkway_Wy_bottom * scale, alpha, arrow_side_length, 1, arrow_tail_length);
cairo_save(cr);
cairo_set_line_width (cr, BOLD_LINE_WIDTH);
cairo_set_line_cap(cr, CAIRO_LINE_CAP_SQUARE);
cairo_move_to(cr, x_base + plat.fan_section_AX / 2 * scale, y + plat.walkway_Wy_bottom * scale + arrow_side_length + arrow_tail_length);
cairo_rel_line_to(cr, (x_one_unit - plat.fan_section_AX) * scale, 0);
cairo_stroke(cr);
cairo_restore(cr);
}
/* dim line for A1, A2 ... */
cairo_move_to(cr, x, y + plat.walkway_Wy_bottom * scale + arrow_side_length + arrow_tail_length + 10);
cairo_rel_line_to(cr, 0, 20);
cairo_get_current_point(cr, &x3, &y3);
if(i != plat.SDD_num)
{
cairo_text_align_horizontal_center (cr, AX, 0, 1, plat.fan_section_AX / 2 * scale, -10);
}
else
{
if(plat.unit_num > 1 && plat.has_gap && unit_num != plat.unit_num)
{
gap_value = strtod(g_list_nth(plat.gap_w, unit_num - 1)->data, NULL);
gap = g_strdup_printf("%.0f", 1000 * gap_value);
cairo_text_extents(cr, gap, &te);
if(gap_value * scale < te.x_bearing + te.width)
{
downward = 1;
downward_height = 11;
downward_width = gap_value * scale;
cairo_rel_move_to(cr, gap_value / 2 * scale - (te.x_bearing + te.width / 2), 10);
}
else
{
downward = 0;
cairo_rel_move_to(cr, gap_value / 2 * scale - (te.x_bearing + te.width / 2), -10);
}
cairo_show_text(cr, gap);
g_free(gap);
}
else
downward = 0;
}
if(unit_num == 1 && i == 0)
{
cairo_move_to(cr, x - plat.walkway_Wx_left * scale, y + plat.walkway_Wy_bottom * scale + arrow_side_length + arrow_tail_length + 10);
cairo_rel_line_to(cr, 0, 20);
cairo_rel_move_to(cr, -25, -10);
cairo_show_text(cr, Wx_left);
}
if(unit_num == plat.unit_num && i == plat.SDD_num)
{
cairo_move_to(cr, x + plat.walkway_Wx_right * scale, y + plat.walkway_Wy_bottom * scale + arrow_side_length + arrow_tail_length + 10);
cairo_rel_line_to(cr, 0, 20);
cairo_rel_move_to(cr, 3, -10);
cairo_show_text(cr, Wx_right);
}
if(plat.axis_style_SDD == 0) /* 递增 */
axis = g_strdup_printf("A%d", plat.start_axis_SDD + (unit_num - 1) * (plat.SDD_num + 1) + i);
else
axis = g_strdup_printf("A%d", plat.start_axis_SDD + (unit_num - 1) * (plat.SDD_num + 1) - i);
cairo_text_extents(cr, axis, &te);
if(!downward || ((i != plat.SDD_num) && (unit_num != 1 && i != 0)))
cairo_move_to(cr, x3 - te.width / 2, y3 + te.height + 2);
else
{
if(te.width < downward_width)
cairo_move_to(cr, x3 - te.width / 2, y3 + te.height + downward_height);
else
{
if(i == plat.SDD_num)
cairo_move_to(cr, x3 - te.width, y3 + te.height + downward_height);
else
cairo_move_to(cr, x3, y3 + te.height + downward_height);
}
}
cairo_show_text(cr, axis);
g_free(axis);
cairo_stroke(cr);
for(j = 0, y_axis = plat.Y_axis; y_axis; y_axis = y_axis->next, j++)
{
x1 = x_base;
if(j == 0)
y1 = y_base + y_one_unit * scale;
else
y1 -= plat.fan_section_AY * scale;
if(i == 0)
{
cairo_move_to(cr, x1, y1);
x1 += x_one_unit * scale;
cairo_line_to(cr, x1, y1); /* horizontal grid */
cairo_stroke(cr);
}
if(i != plat.SDD_num && j != plat.row_num) /* fan ring */
{
cairo_arc(cr, x + plat.fan_section_AX / 2 * scale, y1 - plat.fan_section_AY / 2 * scale, plat.fan_ring_opening_D / 2 * scale, 0, 2 * PI);
cairo_stroke(cr);
}
/* columns */
if(plat.col_type == 0) /* 砼悬臂住 */
{
if(plat.SDD_num % 2 == 0)
{
if((i + 1) % 2 == plat.SDD_col_first && (j + 1) % 2 == plat.row_col_first)
{
cairo_arc(cr, x, y1, COLUMN_RADIUS_ASSUME * scale, 0, 2 * PI);
cairo_fill(cr);
cairo_stroke(cr);
}
}
else
{
if(!plat.if_unit_symmetry || unit_num % 2 == 1)
{
if((i + 1) % 2 == plat.SDD_col_first && (j + 1) % 2 == plat.row_col_first)
{
cairo_arc(cr, x, y1, COLUMN_RADIUS_ASSUME * scale, 0, 2 * PI);
cairo_fill(cr);
cairo_stroke(cr);
}
}
else
{
if((i) % 2 == plat.SDD_col_first && (j + 1) % 2 == plat.row_col_first)
{
cairo_arc(cr, x, y1, COLUMN_RADIUS_ASSUME * scale, 0, 2 * PI);
cairo_fill(cr);
cairo_stroke(cr);
}
}
}
}
else if(plat.col_type == 1) /* 钢柱 */
{
cairo_save(cr);
cairo_set_line_width (cr, 2 * NORMAL_LINE_WIDTH);
cairo_move_to(cr, x, y1 - COLUMN_SQUARE_LEN_ASSUME / 2 * scale);
cairo_rel_line_to(cr, 0, COLUMN_SQUARE_LEN_ASSUME * scale);
cairo_move_to(cr, x - COLUMN_SQUARE_LEN_ASSUME / 2 * scale, y1 - COLUMN_SQUARE_LEN_ASSUME / 2 * scale);
cairo_rel_line_to(cr, COLUMN_SQUARE_LEN_ASSUME * scale, 0);
cairo_move_to(cr, x - COLUMN_SQUARE_LEN_ASSUME / 2 * scale, y1 + COLUMN_SQUARE_LEN_ASSUME / 2 * scale);
cairo_rel_line_to(cr, COLUMN_SQUARE_LEN_ASSUME * scale, 0);
cairo_stroke(cr);
cairo_restore(cr);
}
else if(plat.col_type == 2) /* 砼框架柱 */
{
cairo_rectangle(cr, x - COLUMN_SQUARE_LEN_ASSUME / 2 * scale, y1 - COLUMN_SQUARE_LEN_ASSUME / 2 * scale, COLUMN_SQUARE_LEN_ASSUME * scale, COLUMN_SQUARE_LEN_ASSUME * scale);
cairo_fill(cr);
cairo_stroke(cr);
}
/* dim line of AA, AB ... */
if(unit_num == plat.unit_num && i == 0)
{
cairo_move_to(cr, x1 + plat.walkway_Wx_right * scale + 10, y1);
cairo_rel_line_to(cr, 20, 0);
if(j != plat.row_num)
{
cairo_text_align_horizontal_center (cr, AY, 1, 1, -10, -plat.fan_section_AY / 2 * scale);
}
if(j == 0)
{
x2 = x1 + plat.walkway_Wx_right * scale + 10 + 20 - 5;
y2 = y1 + plat.walkway_Wy_bottom * scale;
cairo_move_to(cr, x1 + plat.walkway_Wx_right * scale + 10, y1);
cairo_rel_move_to(cr, 0, plat.walkway_Wy_bottom * scale);
cairo_rel_line_to(cr, 20, 0);
cairo_rel_move_to(cr, -10, 25);
cairo_save(cr);
cairo_rotate(cr, - PI / 2.0);
cairo_show_text(cr, Wy_bottom);
cairo_restore(cr);
}
if(j == plat.row_num)
{
cairo_move_to(cr, x1 + plat.walkway_Wx_right * scale + 10, y1);
cairo_rel_move_to(cr, 0, -plat.walkway_Wy_top * scale);
cairo_rel_line_to(cr, 20, 0);
cairo_rel_move_to(cr, -10, -1);
cairo_save(cr);
cairo_rotate(cr, - PI / 2.0);
cairo_show_text(cr, Wy_top);
cairo_restore(cr);
}
cairo_stroke(cr);
}
else if(unit_num == 1 && i == 0)
{
if(plat.axis_style_row == 0) /* 递增 */
axis = g_strdup_printf("A%c", plat.start_axis_row + j);
else
axis = g_strdup_printf("A%c", plat.start_axis_row - j);
cairo_text_extents(cr, axis, &te);
cairo_move_to(cr, x_base - plat.walkway_Wx_left * scale - 20, y1 + te.height / 2);
cairo_show_text(cr, axis);
g_free(axis);
cairo_stroke(cr);
}
}
}
}
/* walkway line */
x = X_MARGIN - plat.walkway_Wx_left * scale;
y = Y_MARGIN - plat.walkway_Wy_top * scale;
cairo_move_to(cr, x, y);
cairo_rel_line_to(cr, x_total * scale, 0);
cairo_rel_line_to(cr, 0, y_total * scale);
cairo_rel_line_to(cr, -x_total * scale, 0);
cairo_rel_line_to(cr, 0, -y_total * scale);
cairo_stroke(cr);
/* dim total line for A1, A2 ... */
cairo_move_to(cr, X_MARGIN - plat.walkway_Wx_left * scale, Y_MARGIN + (y_one_unit + plat.walkway_Wy_bottom) * scale + arrow_side_length + arrow_tail_length + 10 + 20 - 5);
cairo_rel_line_to(cr, x_total * scale, 0);
cairo_stroke(cr);
/* dim total line for AA, AB ... */
cairo_move_to(cr, x2, y2);
cairo_rel_line_to(cr, 0, -y_total * scale);
cairo_stroke(cr);
g_free(AX);
g_free(AY);
g_free(Wx_left);
g_free(Wx_right);
g_free(Wy_bottom);
g_free(Wy_top);
}
The expose-event signal:
static gboolean ACC_GA_expose (GtkWidget *canvas, GdkEventExpose *event, gpointer user_data)
{
cairo_t *cr;
cr = gdk_cairo_create (canvas->window);
if(plat.if_GA_draw)
{
ACC_GA_draw (cr, canvas->allocation.width, canvas->allocation.height);
}
else
{
char *local = char_to_utf8 ("Press button \"生成GA\" to update!!");
cairo_select_font_face(cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
cairo_set_font_size(cr, 0.35);
cairo_move_to(cr, 200, 200);
cairo_show_text(cr, local);
g_free(local);
}
cairo_destroy (cr);
return FALSE;
}
In main() function:
.
.
.
canvas = gtk_drawing_area_new();
g_object_set_data(G_OBJECT(window), "plat_GA_canvas", canvas);
plat.if_GA_draw = 0;
gtk_widget_show(canvas);
gtk_box_pack_start(GTK_BOX(sub_main_box), canvas, TRUE, TRUE, 0);
g_signal_connect(G_OBJECT(canvas), "expose-event", G_CALLBACK(ACC_GA_expose), window);
.
.
.
+++++++++++++++++++++++++++++++++++++++++++++++++++
GCC 3.4.5 and GCC 4.7.2 are ABI incompatible. You need to rebuild all your code.
I found a bug in my program. The bug is that expose-event for a canvas is exposed more than once and it crashed for the second time. But I don't know why the bug didn't come up in gcc3.4.5 or in a pure Linux environment. After I revised my program, it worked for mingw-gcc4.7.2, mingw-gcc3.4.5 and a pure Linux environment.
On the other hand, gcc4.7.2 works for pre-compiled gtk2.10.11 but fails for pre-compiled gtk2.24.10 in my situation. This is maybe due to ABI issue.
I have posted 2 other posts: gtk window moved then crash and compile GTK+ in MinGW, but failed. They are more or less related with this post.
Related
I’m working on some of Tim Rodenbrökers code involving a copy() function (https://timrodenbroeker.de/processing-tutorial-kinetic-typography-1/), expanding it and making it ready for web.
This involves replacing the copy() function with drawingContext.drawImage() for performance increase (found here: https://discourse.processing.org/t/p5-js-copy-function-slow-performance-since-version-0-10-0/30007).
Doing this works great for desktop; on mobile, however, the pgraphics element (centered on the canvas, usually), moves position.
Using the regular copy() function centeres it correctly.
The positioning varies according to mobile screen size, I can’t seem to figure out the exact behavior to fix. It's not the font size, I've tried adapting the position to screen.size and document.documentElement.clientWidth, no luck.
let font;
let pg;
function setup() {
font = loadFont("./assets/FGrotesk-Regular.otf");
createCanvas(innerWidth, innerHeight);
pg = createGraphics(innerWidth, innerHeight, P2D);
frameRate(60);
pixelDensity(1);
}
function draw() {
background(0);
pg.background(0);
pg.fill(255);
pg.textFont(font);
pg.textSize(380);
pg.push();
pg.translate(innerWidth / 2, innerHeight / 2);
pg.textAlign(CENTER, CENTER);
pg.text("Enrico", 0, -50);
pg.text("Gisana", 0, 50);
pg.pop();
let tilesX = 400;
let tilesY = 20;
let tileW = int(width / tilesX);
let tileH = int(height / tilesY);
for (y = 0; y < tilesY; y++) {
for (x = 0; x < tilesX; x++) {
// WARP
let wave_x = int(sin(frameCount * 0.02 + (x * y) * 0.07) * 100) - (mouseY / 2);
let wave_y = int(sin(frameCount * 0.02 + (x * y) * 0.07) * 100) - (mouseY / 2);
if (mouseX - (width / 2) >= 0) {
wave_x = int(sin(frameCount * 0.02 + ((x / 0.8) * (y/0.2)) * 0.04) * (-1 * (mouseX - (width / 2)) / 30));
} else {
wave_x = int(sin(frameCount * 0.02 + ((x / 0.8) * (y/0.2)) * 0.04) * (-1 * (mouseX - (width / 2)) / 30));
}
if (mouseY - (height / 2) >= 0) {
wave_y = int(sin(frameCount * 0.02 + ((x / 0.2) * (y/0.8)) * 0.04) * ((mouseY - (height / 2)) / 30));
} else {
wave_y = int(sin(frameCount * 0.02 + ((x / 0.2) * (y/0.8)) * 0.04) * ((mouseY - (height / 2)) / 30));
}
// SOURCE
let sx = x * tileW + wave_x;
// + wave should be added here
let sy = y * tileH - wave_y;
let sw = tileW;
let sh = tileH;
// DESTINATION
let dx = x * tileW;
let dy = y * tileH;
let dw = tileW;
let dh = tileH;
drawingContext.drawImage(pg.elt, sx, sy, sw, sh, dx, dy, dw, dh);
}
}
}
so, as an assaignment i want to make an analog clock, and i am pretty far. I only need the numbers around the clock, but i cant figure out how to make these. I have made some dots right now, but i want to replace theese with the numbers 1-12.. does any1 know an easy and fast way of doing this? my code is as following:
let cx, cy;
let secondsRadius;
let minutesRadius;
let hoursRadius;
let clockDiameter;
function setup() {
createCanvas(800, 800);
let radius= min(width,height)/2;
secondsRadius=radius*0.71;
minutesRadius = radius*0.6;
hoursRadius = radius*0.5;
clockDiameter = radius*1.7;
cx = width/2;
cy = height/2;
}
function draw() {
background("pink");
noStroke();
fill(244, 122, 158);
ellipse(cx, cy, clockDiameter + 25, clockDiameter + 25);
fill("green");
ellipse(cx,cy,clockDiameter, clockDiameter);
let s = map(second(), 0, 60, 0, TWO_PI) - HALF_PI;
let m = map(minute() + norm(second(), 0, 60), 0, 60, 0, TWO_PI) - HALF_PI;
let h = map(hour() + norm(minute(), 0, 60), 0, 24, 0, TWO_PI *2) - HALF_PI;
stroke(255);
strokeWeight(1);
line(cx, cy, cx + cos(s) * secondsRadius, cy + sin(s) * secondsRadius);
strokeWeight(2);
line(cx, cy, cx + cos(m) * minutesRadius, cy + sin(m) * minutesRadius);
strokeWeight(4);
line(cx, cy, cx + cos(h) * hoursRadius, cy + sin(h) * hoursRadius);
strokeWeight(2);
beginShape(POINTS);
for (let a = 0; a < 360; a += 6) {
let angle = radians(a);
let x = cx + cos(angle) * secondsRadius;
let y = cy + sin(angle) * secondsRadius;
vertex(x, y);
}
endShape();
}```
As a quick and dirty:) answer - just add something like that before the last brace:
textSize(36);
fill("white");
noStroke()
for (i = 0; i < 12; i++) {
v = p5.Vector.fromAngle((i + 1) / 12.0 * TAU - HALF_PI);
v.mult(310);
text(i + 1, 382 + v.x, 416 + v.y);
}
My live working demo (your code + this addition) is on ReplIt
I am doing the collision test for the programme, and I tried to insert the test into draw() and I'm expecting it to display "GameOver" and no further events will result any change.
float x;
float y;
float w;
float h;
float xPed;
float yPed;
float yPedc;
float objectX;
float objectY;
float objectWidth;
float objectHeight;
float triangleWidth;
float triangleHeight;
float dia;
int speed = 2;
boolean gameOver;
int N_LANES = 1;
void setup() {
size(1200, 400);
background(255);
x = width / 60;
y = height / 40;
w = width / 80;
xPed = width / 2;
triangleWidth = height / 4;
triangleHeight = 2.5 * w;
yPed = height - 3 * w;
yPedc = 2.5 * w / 2;
dia = w / 2;
h = w / 2;
objectX = x + 2 * w;
objectY = y + 5 * h;
objectWidth = 4 * w;
objectHeight = 10 * h;
gameOver = false;
}
void draw() {
//reset background
background(255);
line(0, height/4, width, height/4);
vehicle();
pedestrian();
// collision detect
if (gameOver == true) {
textSize(100);
fill(255, 0, 0);
text("Game Over", width / 3, height / 2);
}
}
void vehicle() {
//moving vehicle
x += speed;
// reset vehicle
noFill();
if (x > width) {
x = 0;
} else if (x < 0) {
x = width;
}
for (int i = 0; i < N_LANES; i++) {
//head of vehicle
fill(0, 194, 0, 50);
rect(x, y, w, h);
rect(x + 3 * w, y, w, h);
rect(x, y + h, 4 * w, 4 *h);
//eyes of vehicle
fill(0);
rect(x + w, 3 * y, w * 0.85, h);
rect(x + 3 * w, 3 * y, w * 0.85, h);
//body of vehicle
fill(0, 240, 0, 80);
rect(x + 1.5 * w, 6.3 * h, 1.5 * w, 3 *h );
//left arm
line(x + 1.5 *w, 6.3 * h, x + 0.5 * w, 7.3 * h);
//right arm
line(x + 3 * w, 6.3 * h, x + 4 * w, 7.3 * h);
//left leg
line(x + 1.5 * w, 9.3 * h, x + w, 11.3 * h);
//right leg
line(x + 3 * w, 9.3 * h, x + 3.5 * w, 11.3 * h);
}
}
// draw pedestrian
void pedestrian() {
fill(255, 140, 0, 70);
//body of pedestrian
triangle(xPed, yPed, xPed - triangleWidth / 2, yPed + 2.5 * w, xPed + triangleWidth / 2, yPed + 2.5 * w);
fill(0);
circle(xPed + triangleWidth / 4, yPed, dia);
circle(xPed - triangleWidth / 4, yPed, dia);
fill(255, 165, 0);
ellipse(xPed, yPed + w, 1.5 * dia, 3 * dia);
}
// arrow key moving
void keyPressed() {
if (gameOver != true) {
if (key == CODED) {
if (keyCode == UP) {
yPed -= height / 4;
if (yPed <= 0) {
yPed = height - 3 * w;
}
}
if (keyCode == DOWN) {
yPed += height / 4;
if (yPed > height) {
yPed = height - 3 * w;
}
}
if (keyCode==LEFT) {
xPed -= height / 4;
if (xPed < 0 + triangleWidth / 2) {
xPed = width / 2;
}
}
if (keyCode==RIGHT) {
xPed += height / 4;
if (xPed > width - triangleWidth / 2) {
xPed = width / 2;
}
}
}
}
}
boolean gameOver() {
// optional visualise collision objects
rect(objectX, objectY, objectWidth, objectHeight);
rect(xPed, yPed, triangleWidth, triangleHeight);
// x axis
float distX = abs( (objectX + objectWidth / 2) - (xPed + triangleWidth / 2) );
// y axis
float distY = abs( (objectY + objectHeight / 2) - (yPedc + triangleHeight / 2) );
// half combined x distance
float combinedHalfWidth = ( (objectWidth / 2) + (triangleWidth / 2) );
// half combined y distance
float combinedHalfHeight = ( (objectHeight / 2) + (triangleHeight / 2) );
// check collision
if (distX < combinedHalfWidth) {
if (distY < combinedHalfHeight) {
return true;
}
}
return false;
}
I tried to insert the gameOver boolean into draw and it returns the same value everytime.
Just wondering what the logical problem or the coding problem is.
As Rabbid76 mentions, you should format the code correctly first.
Let's assume the code been copied from a pdf with code snippets and that's how formatting got messed up.
The code still has a few glaring bugs:
confusingly you're using both a boolean variable gameOver and a boolean function gameOver() and the variable isn't always updated. (In fact gameOver is only set once in setup() and gameOver() which actually does the collision detection is never called). I recommend either update the boolean variable, or simpler yet, just call gameOver() to compute the collision as needed. This is one of the reasons your code won't behave as you expect.
You're checking collisions between two objects: the vehicle and the pedestrian. However, there are 3 sets of coordinates: x, y, xPed, objectX, objectY. When rendering in draw, the vehicle uses x,y, however, when checking for collisions, gameOver() uses objectX, objectY (which don't match and aren't updated). This is the other reason you're collisions don't behave as expected.
aside from the question you've asked, N_LANES is used in a for loop, but never declared. Even if I declare it, the for loop uses the exact same x,y coordinates, making the for loop redundant.
Here's a formatted version of your code with extra bounding boxes highlighting what the collision function is checking against (and commenting a few unused variables):
float x;
float y;
float w;
float h;
float xPed;
float yPed;
//float yPedc;
float objectX;
float objectY;
float objectWidth;
float objectHeight;
float triangleWidth;
float triangleHeight;
float dia;
int speed = 2;
//boolean gameOver;
int N_LANES = 1;
void setup() {
size(1200, 400);
background(255);
x = width / 60;
y = height / 40;
w = width / 80;
xPed = width / 2;
triangleWidth = height / 4;
triangleHeight = 2.5 * w;
yPed = height - 3 * w;
//yPedc = 2.5 * w / 2;
dia = w / 2;
h = w / 2;
objectX = x + 2 * w;
objectY = y + 5 * h;
objectWidth = 4 * w;
objectHeight = 10 * h;
//gameOver = false;
}
void draw() {
//reset background
background(255);
line(0, height/4, width, height/4);
vehicle();
pedestrian();
// collision detect
if (gameOver() == true) {
textSize(100);
fill(255, 0, 0);
text("Game Over", width / 3, height / 2);
}
}
void vehicle() {
//moving vehicle
x += speed;
// reset vehicle
noFill();
if (x > width) {
x = 0;
} else if (x < 0) {
x = width;
}
for (int i = 0; i < N_LANES; i++) {
//head of vehicle
fill(0, 194, 0, 50);
rect(x, y, w, h);
rect(x + 3 * w, y, w, h);
rect(x, y + h, 4 * w, 4 *h);
//eyes of vehicle
fill(0);
rect(x + w, 3 * y, w * 0.85, h);
rect(x + 3 * w, 3 * y, w * 0.85, h);
//body of vehicle
fill(0, 240, 0, 80);
rect(x + 1.5 * w, 6.3 * h, 1.5 * w, 3 *h );
//left arm
line(x + 1.5 *w, 6.3 * h, x + 0.5 * w, 7.3 * h);
//right arm
line(x + 3 * w, 6.3 * h, x + 4 * w, 7.3 * h);
//left leg
line(x + 1.5 * w, 9.3 * h, x + w, 11.3 * h);
//right leg
line(x + 3 * w, 9.3 * h, x + 3.5 * w, 11.3 * h);
}
}
// draw pedestrian
void pedestrian() {
fill(255, 140, 0, 70);
//body of pedestrian
triangle(xPed, yPed, xPed - triangleWidth / 2, yPed + 2.5 * w, xPed + triangleWidth / 2, yPed + 2.5 * w);
fill(0);
circle(xPed + triangleWidth / 4, yPed, dia);
circle(xPed - triangleWidth / 4, yPed, dia);
fill(255, 165, 0);
ellipse(xPed, yPed + w, 1.5 * dia, 3 * dia);
// visualise bounding box
//fill(255, 140, 0, 70);
//rect(xPed - triangleWidth / 2, yPed, triangleWidth, triangleHeight);
}
// arrow key moving
void keyPressed() {
if (gameOver() != true) {
if (key == CODED) {
if (keyCode == UP) {
yPed -= height / 4;
if (yPed <= 0) {
yPed = height - 3 * w;
}
}
if (keyCode == DOWN) {
yPed += height / 4;
if (yPed > height) {
yPed = height - 3 * w;
}
}
if (keyCode==LEFT) {
xPed -= height / 4;
if (xPed < 0 + triangleWidth / 2) {
xPed = width / 2;
}
}
if (keyCode==RIGHT) {
xPed += height / 4;
if (xPed > width - triangleWidth / 2) {
xPed = width / 2;
}
}
}
}
}
boolean gameOver() {
// optional visualise collision objects
rect(objectX, objectY, objectWidth, objectHeight);
rect(xPed, yPed, triangleWidth, triangleHeight);
// x axis
float distX = abs( (objectX + objectWidth / 2) - (xPed + triangleWidth / 2) );
// y axis
float distY = abs( (objectY + objectHeight / 2) - (yPed + triangleHeight / 2) );
// half combined x distance
float combinedHalfWidth = ( (objectWidth / 2) + (triangleWidth / 2) );
// half combined y distance
float combinedHalfHeight = ( (objectHeight / 2) + (triangleHeight / 2) );
// check collision
if (distX < combinedHalfWidth) {
if (distY < combinedHalfHeight) {
return true;
}
}
return false;
}
Here's a version of the code with a few of the 3 notes above applied, somewhat resolving the collision and gameOver state issue:
float x;
float y;
float w;
float h;
float xPed;
float yPed;
float objectWidth;
float objectHeight;
float triangleWidth;
float triangleHeight;
float dia;
int speed = 2;
void setup() {
size(1200, 400);
background(255);
x = width / 60;
y = height / 40;
w = width / 80;
xPed = width / 2;
triangleWidth = height / 4;
triangleHeight = 2.5 * w;
yPed = height - 3 * w;
dia = w / 2;
h = w / 2;
objectWidth = 4 * w;
objectHeight = 10 * h;
}
void draw() {
//reset background
background(255);
line(0, height/4, width, height/4);
vehicle();
pedestrian();
// collision detect
if (gameOver()) {
textSize(100);
fill(255, 0, 0);
text("Game Over", width / 3, height / 2);
}
}
void vehicle() {
//moving vehicle
x += speed;
// reset vehicle
noFill();
if (x > width) {
x = 0;
} else if (x < 0) {
x = width;
}
//head of vehicle
fill(0, 194, 0, 50);
rect(x, y, w, h);
rect(x + 3 * w, y, w, h);
rect(x, y + h, 4 * w, 4 *h);
//eyes of vehicle
fill(0);
rect(x + w, 3 * y, w * 0.85, h);
rect(x + 3 * w, 3 * y, w * 0.85, h);
//body of vehicle
fill(0, 240, 0, 80);
rect(x + 1.5 * w, 6.3 * h, 1.5 * w, 3 *h );
//left arm
line(x + 1.5 *w, 6.3 * h, x + 0.5 * w, 7.3 * h);
//right arm
line(x + 3 * w, 6.3 * h, x + 4 * w, 7.3 * h);
//left leg
line(x + 1.5 * w, 9.3 * h, x + w, 11.3 * h);
//right leg
line(x + 3 * w, 9.3 * h, x + 3.5 * w, 11.3 * h);
}
// draw pedestrian
void pedestrian() {
fill(255, 140, 0, 70);
//body of pedestrian
triangle(xPed, yPed, xPed - triangleWidth / 2, yPed + 2.5 * w, xPed + triangleWidth / 2, yPed + 2.5 * w);
fill(0);
circle(xPed + triangleWidth / 4, yPed, dia);
circle(xPed - triangleWidth / 4, yPed, dia);
fill(255, 165, 0);
ellipse(xPed, yPed + w, 1.5 * dia, 3 * dia);
// visualise bounding box
//fill(255, 140, 0, 70);
//rect(xPed - triangleWidth / 2, yPed, triangleWidth, triangleHeight);
}
// arrow key moving
void keyPressed() {
if (!gameOver()) {
if (key == CODED) {
if (keyCode == UP) {
yPed -= height / 4;
if (yPed <= 0) {
yPed = height - 3 * w;
}
}
if (keyCode == DOWN) {
yPed += height / 4;
if (yPed > height) {
yPed = height - 3 * w;
}
}
if (keyCode==LEFT) {
xPed -= height / 4;
if (xPed < 0 + triangleWidth / 2) {
xPed = width / 2;
}
}
if (keyCode==RIGHT) {
xPed += height / 4;
if (xPed > width - triangleWidth / 2) {
xPed = width / 2;
}
}
}
}
}
boolean gameOver() {
// optional visualise collision objects
rect(x, y, objectWidth, objectHeight);
rect(xPed, yPed, triangleWidth, triangleHeight);
// x axis
float distX = abs( (x + objectWidth / 2) - (xPed + triangleWidth / 2) );
// y axis
float distY = abs( (y + objectHeight / 2) - (yPed + triangleHeight / 2) );
// half combined x distance
float combinedHalfWidth = ( (objectWidth / 2) + (triangleWidth / 2) );
// half combined y distance
float combinedHalfHeight = ( (objectHeight / 2) + (triangleHeight / 2) );
// check collision
if (distX < combinedHalfWidth) {
if (distY < combinedHalfHeight) {
return true;
}
}
return false;
}
Notice that the triangle bounding box needs to be moved to the left by half the triangle width ideally.
I'd also like to point you to java.awt.Rectangle which has an intersects() that could be useful:
import java.awt.Rectangle;
float x;
float y;
float w;
float h;
float xPed;
float yPed;
float objectWidth;
float objectHeight;
float triangleWidth;
float triangleHeight;
float dia;
int speed = 2;
Rectangle vehicleBoundingBox;
Rectangle pedestrianBoundingBox;
void setup() {
size(1200, 400);
background(255);
x = width / 60;
y = height / 40;
w = width / 80;
xPed = width / 2;
triangleWidth = height / 4;
triangleHeight = 2.5 * w;
yPed = height - 3 * w;
dia = w / 2;
h = w / 2;
objectWidth = 4 * w;
objectHeight = 10 * h;
vehicleBoundingBox = new Rectangle((int)x, (int)y, (int)objectWidth, (int)objectHeight);
pedestrianBoundingBox = new Rectangle((int)xPed, (int)yPed, (int)triangleWidth, (int)triangleHeight);
}
void draw() {
//reset background
background(255);
line(0, height/4, width, height/4);
vehicle();
pedestrian();
// collision detect
if (gameOver()) {
textSize(100);
fill(255, 0, 0);
text("Game Over", width / 3, height / 2);
}
}
void vehicle() {
//moving vehicle
x += speed;
// reset vehicle
noFill();
if (x > width) {
x = 0;
} else if (x < 0) {
x = width;
}
//head of vehicle
fill(0, 194, 0, 50);
rect(x, y, w, h);
rect(x + 3 * w, y, w, h);
rect(x, y + h, 4 * w, 4 *h);
//eyes of vehicle
fill(0);
rect(x + w, 3 * y, w * 0.85, h);
rect(x + 3 * w, 3 * y, w * 0.85, h);
//body of vehicle
fill(0, 240, 0, 80);
rect(x + 1.5 * w, 6.3 * h, 1.5 * w, 3 *h );
//left arm
line(x + 1.5 *w, 6.3 * h, x + 0.5 * w, 7.3 * h);
//right arm
line(x + 3 * w, 6.3 * h, x + 4 * w, 7.3 * h);
//left leg
line(x + 1.5 * w, 9.3 * h, x + w, 11.3 * h);
//right leg
line(x + 3 * w, 9.3 * h, x + 3.5 * w, 11.3 * h);
}
// draw pedestrian
void pedestrian() {
fill(255, 140, 0, 70);
//body of pedestrian
triangle(xPed, yPed, xPed - triangleWidth / 2, yPed + 2.5 * w, xPed + triangleWidth / 2, yPed + 2.5 * w);
fill(0);
circle(xPed + triangleWidth / 4, yPed, dia);
circle(xPed - triangleWidth / 4, yPed, dia);
fill(255, 165, 0);
ellipse(xPed, yPed + w, 1.5 * dia, 3 * dia);
}
// arrow key moving
void keyPressed() {
if (!gameOver()) {
if (key == CODED) {
if (keyCode == UP) {
yPed -= height / 4;
if (yPed <= 0) {
yPed = height - 3 * w;
}
}
if (keyCode == DOWN) {
yPed += height / 4;
if (yPed > height) {
yPed = height - 3 * w;
}
}
if (keyCode==LEFT) {
xPed -= height / 4;
if (xPed < 0 + triangleWidth / 2) {
xPed = width / 2;
}
}
if (keyCode==RIGHT) {
xPed += height / 4;
if (xPed > width - triangleWidth / 2) {
xPed = width / 2;
}
}
}
}
}
boolean gameOver(){
// update bounding box positions
vehicleBoundingBox.x = (int)x;
vehicleBoundingBox.y = (int)y;
pedestrianBoundingBox.x = (int)(xPed - triangleWidth / 2);
pedestrianBoundingBox.y = (int)yPed;
//optional: visualise boxes
fill(255, 140, 0, 70);
rect(pedestrianBoundingBox.x, pedestrianBoundingBox.y, pedestrianBoundingBox.width, pedestrianBoundingBox.height);
rect(vehicleBoundingBox.x, vehicleBoundingBox.y, vehicleBoundingBox.width, vehicleBoundingBox.height);
return vehicleBoundingBox.intersects(pedestrianBoundingBox);
}
//boolean gameOver() {
// // optional visualise collision objects
// rect(x, y, objectWidth, objectHeight);
// rect(xPed, yPed, triangleWidth, triangleHeight);
// // x axis
// float distX = abs( (x + objectWidth / 2) - (xPed + triangleWidth / 2) );
// // y axis
// float distY = abs( (y + objectHeight / 2) - (yPed + triangleHeight / 2) );
// // half combined x distance
// float combinedHalfWidth = ( (objectWidth / 2) + (triangleWidth / 2) );
// // half combined y distance
// float combinedHalfHeight = ( (objectHeight / 2) + (triangleHeight / 2) );
// // check collision
// if (distX < combinedHalfWidth) {
// if (distY < combinedHalfHeight) {
// return true;
// }
// }
// return false;
//}
void circle(float x, float y, float dia){
ellipse(x, y, dia, dia);
}
Bare in mind, if this is an assignment/homework, you might not be allowed to use java.awt.Rectangle. Speaking of which, if this is an assignment you should mention that in the question.
Update
Here's an updated version better handling the game over state.
float x;
float y;
float w;
float h;
float xPed;
float yPed;
float objectWidth;
float objectHeight;
float triangleWidth;
float triangleHeight;
float dia;
int speed = 2;
// defaults to false
boolean isGameOver;
void setup() {
size(1200, 400);
background(255);
x = width / 60;
y = height / 40;
w = width / 80;
xPed = width / 2;
triangleWidth = height / 4;
triangleHeight = 2.5 * w;
yPed = height - 3 * w;
dia = w / 2;
h = w / 2;
objectWidth = 4 * w;
objectHeight = 10 * h;
}
void draw() {
//reset background
background(255);
line(0, height/4, width, height/4);
if (isGameOver) {
textSize(100);
fill(255, 0, 0);
text("Game Over", width / 3, height / 2);
}else{
// check colloisions only in game state and update game over state
isGameOver = checkCollisions();
vehicle();
pedestrian();
}
}
void vehicle() {
//moving vehicle
x += speed;
// reset vehicle
noFill();
if (x > width) {
x = 0;
} else if (x < 0) {
x = width;
}
//head of vehicle
fill(0, 194, 0, 50);
rect(x, y, w, h);
rect(x + 3 * w, y, w, h);
rect(x, y + h, 4 * w, 4 *h);
//eyes of vehicle
fill(0);
rect(x + w, 3 * y, w * 0.85, h);
rect(x + 3 * w, 3 * y, w * 0.85, h);
//body of vehicle
fill(0, 240, 0, 80);
rect(x + 1.5 * w, 6.3 * h, 1.5 * w, 3 *h );
//left arm
line(x + 1.5 *w, 6.3 * h, x + 0.5 * w, 7.3 * h);
//right arm
line(x + 3 * w, 6.3 * h, x + 4 * w, 7.3 * h);
//left leg
line(x + 1.5 * w, 9.3 * h, x + w, 11.3 * h);
//right leg
line(x + 3 * w, 9.3 * h, x + 3.5 * w, 11.3 * h);
}
// draw pedestrian
void pedestrian() {
fill(255, 140, 0, 70);
//body of pedestrian
triangle(xPed, yPed, xPed - triangleWidth / 2, yPed + 2.5 * w, xPed + triangleWidth / 2, yPed + 2.5 * w);
fill(0);
circle(xPed + triangleWidth / 4, yPed, dia);
circle(xPed - triangleWidth / 4, yPed, dia);
fill(255, 165, 0);
ellipse(xPed, yPed + w, 1.5 * dia, 3 * dia);
// visualise bounding box
//fill(255, 140, 0, 70);
//rect(xPed - triangleWidth / 2, yPed, triangleWidth, triangleHeight);
}
// arrow key moving
void keyPressed() {
if (isGameOver){
// exit game over
isGameOver = false;
// lazy way to restart the game
// normally you'd write & call a reset() function to reset player/vehicle positions, avodiing instant gameOver
setup();
} else {
if (key == CODED) {
if (keyCode == UP) {
yPed -= height / 4;
if (yPed <= 0) {
yPed = height - 3 * w;
}
}
if (keyCode == DOWN) {
yPed += height / 4;
if (yPed > height) {
yPed = height - 3 * w;
}
}
if (keyCode==LEFT) {
xPed -= height / 4;
if (xPed < 0 + triangleWidth / 2) {
xPed = width / 2;
}
}
if (keyCode==RIGHT) {
xPed += height / 4;
if (xPed > width - triangleWidth / 2) {
xPed = width / 2;
}
}
}
}
}
boolean checkCollisions() {
// optional visualise collision objects
fill(255, 140, 0, 70);
rect(x, y, objectWidth, objectHeight);
rect(xPed - triangleWidth / 2, yPed, triangleWidth, triangleHeight);
// x axis
float distX = abs( (x + objectWidth / 2) - xPed );
// y axis
float distY = abs( (y + objectHeight / 2) - (yPed + triangleHeight / 2) );
// half combined x distance
float combinedHalfWidth = ( (objectWidth / 2) + (triangleWidth / 2) );
// half combined y distance
float combinedHalfHeight = ( (objectHeight / 2) + (triangleHeight / 2) );
// check collision
if (distX < combinedHalfWidth) {
if (distY < combinedHalfHeight) {
return true;
}
}
return false;
}
The main changes are:
reintroduced gameOver boolean as isGameOver which is used to change between the two states
renamed gameOver() to checkCollisions() to avoid confusion.
In this case, with just two states, a boolean will do.
It's important to also reset game variables when changing state (e.g. reset player/vehicle positions, etc.)
In case your game may require more states you can use an integer and constants. This answer has a demo code snippet.
If multiple states are required OOP was introduced, this answer also has demo code.
Hello coding community I need your help.
I took a sketch from openprocessing and I need to convert it into p5.js. The first script is the source code, then below will by my translation. I'm not sure about the syntax.
float x, y, x2, y2, rad, rad2, dist, dist2;
float deg, incr, yIn, rotateBy, ang;
void setup() {
size(600, 600);
background(#02021A);
incr = 1; // numVerts = 360/incr
rad = -20;
rad2 = -160;
dist = 500;
dist2 = 550;
}
void draw() {
noStroke();
fill(#02021A, 10);
rect(0, 0, width, height);
fill(random(0, 255), 255, 255);
rotateBy += .003;
pushMatrix();
translate(width/2, height/2);
rotate(rotateBy);
deg = 0;
while (deg <= 360) {
deg += incr;
ang = radians(deg);
x = cos(ang) * (rad + (dist * noise(y/100, yIn)));
y = sin(ang) * (rad + (dist * noise(x/80, yIn)));
ellipse(x, y, 1.5, 1.5);
x2 = sin(ang) * (rad2 + (dist2 * noise(y2/20, yIn)));
y2 = cos(ang) * (rad2 + (dist2 * noise(y2/20, yIn)));
ellipse(x2, y2, 1, 1);
}
yIn += .005;
popMatrix();
}
This what I've done.
p5.js:
let x, y, x2, y2, rad, rad2, dist, dist2;
let deg, incr, yIn, rotateBy, ang;
function setup() {
createCanvas(600, 600);
background('#02021A');
incr = 1; // numVerts = 360/incr
rad = -20;
rad2 = -160;
dist = 500;
dist2 = 550;
}
function draw() {
noStroke();
fill('#02021A');
rect(0, 0, width, height);
fill(random(0, 255), 255, 255);
rotateBy += '.003';
push();
translate(width/2, height/2);
rotate(rotateBy);
deg = 0;
while (deg <= 360) {
deg += incr;
ang = radians(deg);
x = cos(ang) * (rad + (dist * noise(y/100, yIn)));
y = sin(ang) * (rad + (dist * noise(x/80, yIn)));
ellipse(x, y, 1.5, 1.5);
x2 = sin(ang) * (rad2 + (dist2 * noise(y2/20, yIn)));
y2 = cos(ang) * (rad2 + (dist2 * noise(y2/20, yIn)));
ellipse(x2, y2, 1, 1);
}
yIn += '.005';
pop();
}
But it still doesn't work. Could you help me understand if the syntax is the same in these two languages.
You're almost there, but there are a couple of gotchas:
you declare variables at the top (e.g. float x, y, x2, y2, rad, rad2, dist, dist2;, etc.), however you don't initialize them with values. Because JavaScript is untyped (unlike Java), the interpreter can't guess what type you meant and the variables will be initialised to undefined (while in Java, because they're float type they'll default to 0). Doing math operations on undefined results in NaN (not a number).
you're accidentally incrementing some values by strings instead of floats: rotateBy += '.003'; yIn += '.005';
optional: fill(#02021A, 10); won't work in p5.js, however you can use fill(r,g,b,a) and pass your values in hex notation: fill(0x02, 0x02, 0x1A, 10);
This is your code with these two fixes applied:
let x = 0, y = 0, x2 = 0, y2 = 0, rad = 0, rad2 = 0, dist = 0, dist2 = 0;
let deg = 0, incr = 0, yIn = 0, rotateBy = 0, ang = 0;
function setup() {
createCanvas(600, 600);
background('#02021A');
incr = 1; // numVerts = 360/incr
rad = -20;
rad2 = -160;
dist = 500;
dist2 = 550;
}
function draw() {
noStroke();
fill(0x02, 0x02, 0x1A, 10);
rect(0, 0, width, height);
fill(random(0, 255), 255, 255);
rotateBy += 0.003;
push();
translate(width/2, height/2);
rotate(rotateBy);
deg = 0;
while (deg <= 360) {
deg += incr;
ang = radians(deg);
x = cos(ang) * (rad + (dist * noise(y/100, yIn)));
y = sin(ang) * (rad + (dist * noise(x/80, yIn)));
ellipse(x, y, 1.5, 1.5);
x2 = sin(ang) * (rad2 + (dist2 * noise(y2/20, yIn)));
y2 = cos(ang) * (rad2 + (dist2 * noise(y2/20, yIn)));
ellipse(x2, y2, 1, 1);
}
yIn += 0.005;
pop();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>
That looks pretty cool! Have fun !
What I'd like to achieve is close to this there. You can also just take a look at those screenshots.
The actual result
Notice how the refraction is evolving as the page scrolls down/up. Scrolling, there is also a source of light going right to left.
After scrolling
Ideally I'd like the text to have that transparent glass reflective aspect like on the example provided. But also, to refract what is behind, which does not seem to be the case here. Indeed, when the canvas is left alone, the refraction still happens, so i suspect the effects is done knowing what would be displayed in the background. As for me, I'd like to refract whats behind dynamically. Yet again i'm thinking that i might have been achieved this way for a reason, maybe performance issue
All non canvas elements removed
Indeed, it looks like it it based from the background, but the background is not within the canvas. Also, as you can see, on the next picture, the refraction effect is still hapenning even though the background is removed.
Refraction
The source of light is still there and i suspect it's using some kind of ray casting/ray tracing method. I'm not at all familiar with drawing in the canvas (except using p5.js for simple things),and it took me a long time to find ray tracing with no idea of what i'm looking for.
.... Questions ....
How do i get the glass transparent reflective aspect on the text ? Should it be achieve with graphic design tools ? (I don't know how to get an object (see screenshot below) that seem to have the texture bind afterwards.I'm not even sure if i'm using the right vocabulary but assuming I am, I don't know how to make such texture.)
text object no "texture"
How to refract everything that would be placed behind the glass object? (Before I came to the conclusion that I needed to use canvas, not just because I found this exemple, but also because of other considerations related to the project I'm working on. I've invest a lot of time learning suffisant svg to achieve what you can see on the next screenshot,and failed to achieve what was aimed. I'm not willing to do so the same with ray casting thus my third question. I hope it's understandable...Still the refracted part is there but looks a lot less realistic than in the provided example.)
SVG
Is ray casting/ray tracing is the right path to dig in for achieving the refraction ? Will it be okay to use if its ray tracing every objects behind.
Thanks for your time and concern.
Reflection and Refraction
There are so many tutorials online to achieve this FX I can not see the point in repeating them.
This answer presents an approximation using a normal map in place of a 3D model, and flat texture maps to represent the reflection and refraction maps, rather than 3D textures traditionally used to get reflections and refraction.
Generating a normal map.
The snippet below generates a normal map from input text with various options. The process is reasonably quick (not real time) and will be the stand in for a 3D model in the webGL rendering solution.
It first creates a height map of the text, adds some smoothing, then converts the map to a normal map.
text.addEventListener("keyup", createNormalMap)
createNormalMap();
function createNormalMap(){
text.focus();
setTimeout(() => {
const can = normalMapText(text.value, "Arial Black", 96, 8, 2, 0.1, true, "round");
result.innerHTML = "";
result.appendChild(can);
}, 0);
}
function normalMapText(text, font, size, bevel, smooth = 0, curve = 0.5, smoothNormals = true, corners = "round") {
const canvas = document.createElement("canvas");
const mask = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const ctxMask = mask.getContext("2d");
ctx.font = size + "px " + font;
const tw = ctx.measureText(text).width;
const cx = (mask.width = canvas.width = tw + bevel * 3) / 2;
const cy = (mask.height = canvas.height = size + bevel * 3) / 2;
ctx.font = size + "px " + font;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.lineJoin = corners;
const step = 255 / (bevel + 1);
var j, i = 0, val = step;
while (i < bevel) {
ctx.lineWidth = bevel - i;
const v = ((val / 255) ** curve) * 255;
ctx.strokeStyle = `rgb(${v},${v},${v})`;
ctx.strokeText(text, cx, cy);
i++;
val += step;
}
ctx.fillStyle = "#FFF";
ctx.fillText(text, cx, cy);
if (smooth >= 1) {
ctxMask.drawImage(canvas, 0, 0);
ctx.filter = "blur(" + smooth + "px)";
ctx.drawImage(mask, 0, 0);
ctx.globalCompositeOperation = "destination-in";
ctx.filter = "none";
ctx.drawImage(mask, 0, 0);
ctx.globalCompositeOperation = "source-over";
}
const w = canvas.width, h = canvas.height, w4 = w << 2;
const imgData = ctx.getImageData(0,0,w,h);
const d = imgData.data;
const heightBuf = new Uint8Array(w * h);
j = i = 0;
while (i < d.length) {
heightBuf[j++] = d[i]
i += 4;
}
var x, y, xx, yy, zz, xx1, yy1, zz1, xx2, yy2, zz2, dist;
i = 0;
for(y = 0; y < h; y ++){
for(x = 0; x < w; x ++){
if(d[i + 3]) { // only pixels with alpha > 0
const idx = x + y * w;
const x1 = 1;
const z1 = heightBuf[idx - 1] === undefined ? 0 : heightBuf[idx - 1] - heightBuf[idx];
const y1 = 0;
const x2 = 0;
const z2 = heightBuf[idx - w] === undefined ? 0 : heightBuf[idx - w] - heightBuf[idx];
const y2 = -1;
const x3 = 1;
const z3 = heightBuf[idx - w - 1] === undefined ? 0 : heightBuf[idx - w - 1] - heightBuf[idx];
const y3 = -1;
xx = y3 * z2 - z3 * y2
yy = z3 * x2 - x3 * z2
zz = x3 * y2 - y3 * x2
dist = (xx * xx + yy * yy + zz * zz) ** 0.5;
xx /= dist;
yy /= dist;
zz /= dist;
xx1 = y1 * z3 - z1 * y3
yy1 = z1 * x3 - x1 * z3
zz1 = x1 * y3 - y1 * x3
dist = (xx1 * xx1 + yy1 * yy1 + zz1 * zz1) ** 0.5;
xx += xx1 / dist;
yy += yy1 / dist;
zz += zz1 / dist;
if (smoothNormals) {
const x1 = 2;
const z1 = heightBuf[idx - 2] === undefined ? 0 : heightBuf[idx - 2] - heightBuf[idx];
const y1 = 0;
const x2 = 0;
const z2 = heightBuf[idx - w * 2] === undefined ? 0 : heightBuf[idx - w * 2] - heightBuf[idx];
const y2 = -2;
const x3 = 2;
const z3 = heightBuf[idx - w * 2 - 2] === undefined ? 0 : heightBuf[idx - w * 2 - 2] - heightBuf[idx];
const y3 = -2;
xx2 = y3 * z2 - z3 * y2
yy2 = z3 * x2 - x3 * z2
zz2 = x3 * y2 - y3 * x2
dist = (xx2 * xx2 + yy2 * yy2 + zz2 * zz2) ** 0.5 * 2;
xx2 /= dist;
yy2 /= dist;
zz2 /= dist;
xx1 = y1 * z3 - z1 * y3
yy1 = z1 * x3 - x1 * z3
zz1 = x1 * y3 - y1 * x3
dist = (xx1 * xx1 + yy1 * yy1 + zz1 * zz1) ** 0.5 * 2;
xx2 += xx1 / dist;
yy2 += yy1 / dist;
zz2 += zz1 / dist;
xx += xx2;
yy += yy2;
zz += zz2;
}
dist = (xx * xx + yy * yy + zz * zz) ** 0.5;
d[i+0] = ((xx / dist) + 1.0) * 128;
d[i+1] = ((yy / dist) + 1.0) * 128;
d[i+2] = 255 - ((zz / dist) + 1.0) * 128;
}
i += 4;
}
}
ctx.putImageData(imgData, 0, 0);
return canvas;
}
<input id="text" type="text" value="Normal Map" />
<div id="result"></div>
Approximation
To render the text we need to create some shaders. As we are using a normal map the vertex shader can be very simple.
Vertex shader
We are using a quad to render the whole canvas. The vertex shader outputs the 4 corners and converts each corner to a texture coordinate.
#version 300 es
in vec2 vert;
out vec2 texCoord;
void main() {
texCoord = vert * 0.5 + 0.5;
gl_Position = vec4(verts, 1, 1);
}
Fragment shader
The fragment shader has 3 texture inputs. The normal map, and the reflection and refraction maps.
The fragment shader first works out if the pixel is part of the background, or on the text. If on the text it converts the RGB texture normal into a vector normal.
It then uses vector addition to get the reflected and refracted textures. Mixing those textures by the normal maps z value. In effect refraction is strongest when the normal is facing up and reflection strongest when normal facing away
#version 300 es
uniform sampler2D normalMap;
uniform sampler2D refractionMap;
uniform sampler2D reflectionMap;
in vec2 texCoord;
out vec4 pixel;
void main() {
vec4 norm = texture(normalMap, texCoord);
if (norm.a > 0) {
vec3 normal = normalize(norm.rgb - 0.5);
vec2 tx1 = textCoord + normal.xy * 0.1;
vec2 tx2 = textCoord - normal.xy * 0.2;
pixel = vec4(mix(texture(refractionMap, tx2).rgb, texture(reflectionMap, tx1).rgb, abs(normal.z)), norm.a);
} else {
pixel = texture(refactionMap, texCoord);
}
}
That is the most basic form that will give the impression of reflection and refraction.
Example NOT REAL reflection refraction.
The example is a little more complex as the various textures have different sizes and thus need to be scaled in the fragment shader to be the correct size.
I have also added some tinting to both the refraction and reflections and mixed the reflection via a curve.
The background is scrolled to the mouse position. To match a background on the page you would move the canvas over the background.
There are a few #defines in the frag shader to control the settings. You could make them uniforms, or constants.
mixCurve controls the mix of reflect refract textures. Values < 1 > 0 ease out refraction, values > 1 ease out the reflection.
The normal map is one to one with rendered pixels. As 2D canvas rendering is rather poor quality you can get a better result by over sampling the normal map in the fragment shader.
const vertSrc = `#version 300 es
in vec2 verts;
out vec2 texCoord;
void main() {
texCoord = verts * vec2(0.5, -0.5) + 0.5;
gl_Position = vec4(verts, 1, 1);
}
`
const fragSrc = `#version 300 es
precision highp float;
#define refractStrength 0.1
#define reflectStrength 0.2
#define refractTint vec3(1,0.95,0.85)
#define reflectTint vec3(1,1.25,1.42)
#define mixCurve 0.3
uniform sampler2D normalMap;
uniform sampler2D refractionMap;
uniform sampler2D reflectionMap;
uniform vec2 scrolls;
in vec2 texCoord;
out vec4 pixel;
void main() {
vec2 nSize = vec2(textureSize(normalMap, 0));
vec2 scaleCoords = nSize / vec2(textureSize(refractionMap, 0));
vec2 rCoord = (texCoord - scrolls) * scaleCoords;
vec4 norm = texture(normalMap, texCoord);
if (norm.a > 0.99) {
vec3 normal = normalize(norm.rgb - 0.5);
vec2 tx1 = rCoord + normal.xy * scaleCoords * refractStrength;
vec2 tx2 = rCoord - normal.xy * scaleCoords * reflectStrength;
vec3 c1 = texture(refractionMap, tx1).rgb * refractTint;
vec3 c2 = texture(reflectionMap, tx2).rgb * reflectTint;
pixel = vec4(mix(c2, c1, abs(pow(normal.z,mixCurve))), 1.0);
} else {
pixel = texture(refractionMap, rCoord);
}
}
`
var program, loc;
function normalMapText(text, font, size, bevel, smooth = 0, curve = 0.5, smoothNormals = true, corners = "round") {
const canvas = document.createElement("canvas");
const mask = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const ctxMask = mask.getContext("2d");
ctx.font = size + "px " + font;
const tw = ctx.measureText(text).width;
const cx = (mask.width = canvas.width = tw + bevel * 3) / 2;
const cy = (mask.height = canvas.height = size + bevel * 3) / 2;
ctx.font = size + "px " + font;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.lineJoin = corners;
const step = 255 / (bevel + 1);
var j, i = 0, val = step;
while (i < bevel) {
ctx.lineWidth = bevel - i;
const v = ((val / 255) ** curve) * 255;
ctx.strokeStyle = `rgb(${v},${v},${v})`;
ctx.strokeText(text, cx, cy);
i++;
val += step;
}
ctx.fillStyle = "#FFF";
ctx.fillText(text, cx, cy);
if (smooth >= 1) {
ctxMask.drawImage(canvas, 0, 0);
ctx.filter = "blur(" + smooth + "px)";
ctx.drawImage(mask, 0, 0);
ctx.globalCompositeOperation = "destination-in";
ctx.filter = "none";
ctx.drawImage(mask, 0, 0);
ctx.globalCompositeOperation = "source-over";
}
const w = canvas.width, h = canvas.height, w4 = w << 2;
const imgData = ctx.getImageData(0,0,w,h);
const d = imgData.data;
const heightBuf = new Uint8Array(w * h);
j = i = 0;
while (i < d.length) {
heightBuf[j++] = d[i]
i += 4;
}
var x, y, xx, yy, zz, xx1, yy1, zz1, xx2, yy2, zz2, dist;
i = 0;
for(y = 0; y < h; y ++){
for(x = 0; x < w; x ++){
if(d[i + 3]) { // only pixels with alpha > 0
const idx = x + y * w;
const x1 = 1;
const z1 = heightBuf[idx - 1] === undefined ? 0 : heightBuf[idx - 1] - heightBuf[idx];
const y1 = 0;
const x2 = 0;
const z2 = heightBuf[idx - w] === undefined ? 0 : heightBuf[idx - w] - heightBuf[idx];
const y2 = -1;
const x3 = 1;
const z3 = heightBuf[idx - w - 1] === undefined ? 0 : heightBuf[idx - w - 1] - heightBuf[idx];
const y3 = -1;
xx = y3 * z2 - z3 * y2
yy = z3 * x2 - x3 * z2
zz = x3 * y2 - y3 * x2
dist = (xx * xx + yy * yy + zz * zz) ** 0.5;
xx /= dist;
yy /= dist;
zz /= dist;
xx1 = y1 * z3 - z1 * y3
yy1 = z1 * x3 - x1 * z3
zz1 = x1 * y3 - y1 * x3
dist = (xx1 * xx1 + yy1 * yy1 + zz1 * zz1) ** 0.5;
xx += xx1 / dist;
yy += yy1 / dist;
zz += zz1 / dist;
if (smoothNormals) {
const x1 = 2;
const z1 = heightBuf[idx - 2] === undefined ? 0 : heightBuf[idx - 2] - heightBuf[idx];
const y1 = 0;
const x2 = 0;
const z2 = heightBuf[idx - w * 2] === undefined ? 0 : heightBuf[idx - w * 2] - heightBuf[idx];
const y2 = -2;
const x3 = 2;
const z3 = heightBuf[idx - w * 2 - 2] === undefined ? 0 : heightBuf[idx - w * 2 - 2] - heightBuf[idx];
const y3 = -2;
xx2 = y3 * z2 - z3 * y2
yy2 = z3 * x2 - x3 * z2
zz2 = x3 * y2 - y3 * x2
dist = (xx2 * xx2 + yy2 * yy2 + zz2 * zz2) ** 0.5 * 2;
xx2 /= dist;
yy2 /= dist;
zz2 /= dist;
xx1 = y1 * z3 - z1 * y3
yy1 = z1 * x3 - x1 * z3
zz1 = x1 * y3 - y1 * x3
dist = (xx1 * xx1 + yy1 * yy1 + zz1 * zz1) ** 0.5 * 2;
xx2 += xx1 / dist;
yy2 += yy1 / dist;
zz2 += zz1 / dist;
xx += xx2;
yy += yy2;
zz += zz2;
}
dist = (xx * xx + yy * yy + zz * zz) ** 0.5;
d[i+0] = ((xx / dist) + 1.0) * 128;
d[i+1] = ((yy / dist) + 1.0) * 128;
d[i+2] = 255 - ((zz / dist) + 1.0) * 128;
}
i += 4;
}
}
ctx.putImageData(imgData, 0, 0);
return canvas;
}
function createChecker(size, width, height) {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
canvas.width = width * size;
canvas.height = height * size;
for(var y = 0; y < size; y ++) {
for(var x = 0; x < size; x ++) {
const xx = x * width;
const yy = y * height;
ctx.fillStyle ="#888";
ctx.fillRect(xx,yy,width,height);
ctx.fillStyle ="#DDD";
ctx.fillRect(xx,yy,width/2,height/2);
ctx.fillRect(xx+width/2,yy+height/2,width/2,height/2);
}
}
return canvas;
}
const mouse = {x:0, y:0};
addEventListener("mousemove",e => {mouse.x = e.pageX; mouse.y = e.pageY });
var normMap = normalMapText("GLASSY", "Arial Black", 128, 24, 1, 0.1, true, "round");
canvas.width = normMap.width;
canvas.height = normMap.height;
const locations = {updates: []};
const fArr = arr => new Float32Array(arr);
const gl = canvas.getContext("webgl2", {premultipliedAlpha: false, antialias: false, alpha: false});
const textures = {};
setup();
function texture(gl, image, {min = "LINEAR", mag = "LINEAR", wrapX = "REPEAT", wrapY = "REPEAT"} = {}) {
const texture = gl.createTexture();
target = gl.TEXTURE_2D;
gl.bindTexture(target, texture);
gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, gl[min]);
gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, gl[mag]);
gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl[wrapX]);
gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl[wrapY]);
gl.texImage2D(target, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
return texture;
}
function bindTexture(texture, unit) {
gl.activeTexture(gl.TEXTURE0 + unit);
gl.bindTexture(gl.TEXTURE_2D, texture);
}
function Location(name, data, type = "fv", autoUpdate = true) {
const glUpdateCall = gl["uniform" + data.length + type].bind(gl);
const loc = gl.getUniformLocation(program, name);
locations[name] = {data, update() {glUpdateCall(loc, data)}};
autoUpdate && locations.updates.push(locations[name]);
return locations[name];
}
function compileShader(src, type, shader = gl.createShader(type)) {
gl.shaderSource(shader, src);
gl.compileShader(shader);
return shader;
}
function setup() {
program = gl.createProgram();
gl.attachShader(program, compileShader(vertSrc, gl.VERTEX_SHADER));
gl.attachShader(program, compileShader(fragSrc, gl.FRAGMENT_SHADER));
gl.linkProgram(program);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint8Array([0,1,2,0,2,3]), gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ARRAY_BUFFER, fArr([-1,-1,1,-1,1,1,-1,1]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(loc = gl.getAttribLocation(program, "verts"));
gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
gl.useProgram(program);
Location("scrolls", [0, 0]);
Location("normalMap", [0], "i", false).update();
Location("refractionMap", [1], "i", false).update();
Location("reflectionMap", [2], "i", false).update();
textures.norm = texture(gl,normMap);
textures.reflect = texture(gl,createChecker(8,128,128));
textures.refract = texture(gl,createChecker(8,128,128));
gl.viewport(0, 0, normMap.width, normMap.height);
bindTexture(textures.norm, 0);
bindTexture(textures.reflect, 1);
bindTexture(textures.refract, 2);
loop();
}
function draw() {
for(const l of locations.updates) { l.update() }
gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_BYTE, 0);
}
function loop() {
locations.scrolls.data[0] = -1 + mouse.x / canvas.width;
locations.scrolls.data[1] = -1 + mouse.y / canvas.height;
draw();
requestAnimationFrame(loop);
}
canvas {
position: absolute;
top: 0px;
left: 0px;
}
<canvas id="canvas"></canvas>
Personally I find this FX more visually pleasing than simulations based on real lighting models. Though keep in mind THIS IS NOT Refraction or Reflections.