/*!\file convolutions.c
 *
 * \brief filtres de convolution adaptés à SDL2
 * \author Farès BELHADJ, amsi@ai.univ-paris8.fr
 * \date February 13 2014
 */

//AJOUTEZ VOS #include ici

/*!\brief réalise un filtre sobel sur l'image décrite dans \a img.
 *
 * \param img est la surface SDL décrivant l'image, elle doît être 4 bytes par pixel.
 */
void sobel(SDL_Surface * img) {
  int i, j, k, l, m, y, x;
  float Mx[] = {
    1, 0, -1,
    2, 0, -2,
    1, 0, -1
  }, My[] = {
    1, 2, 1,
    0, 0, 0,
    -1, -2, -1
  }, Gxr, Gxg, Gxb, Gyr, Gyg, Gyb, nr, ng, nb;
  Uint32 * ppixels = img->pixels, * tpixels = NULL;
  Uint8 r, g, b, s;
  assert(img->format->BytesPerPixel == 4);
  tpixels = malloc(img->w * img->h * sizeof * tpixels);
  assert(tpixels);
  for(i = 0; i < img->h; i++) {
    for(j = 0; j < img->w; j++) {
      Gxr = Gxg = Gxb = Gyr = Gyg = Gyb = 0;
      for(k = -1, m = 0; k < 2; k++) {
	for(l = -1; l < 2; l++) {
	  x = j + l; y = i + k;
	  if(x >= 0 && y >= 0 && x <= img->w && y <= img->h) {
	    SDL_GetRGB(ppixels[(y * img->w + x)], img->format, &r, &g, &b);
	    Gxr += r * Mx[m];
	    Gxg += g * Mx[m];
	    Gxb += b * Mx[m];
	    Gyr += r * My[m];
	    Gyg += g * My[m];
	    Gyb += b * My[m];
	  }
	  m++;
	}
      }
      nr = sqrt(Gxr * Gxr + Gyr * Gyr);
      ng = sqrt(Gxg * Gxg + Gyg * Gyg);
      nb = sqrt(Gxb * Gxb + Gyb * Gyb);
      nr = MIN(nr, 255);
      ng = MIN(ng, 255);
      nb = MIN(nb, 255);
      s = ((nr + ng + nb) / 3.0) > 60 ? 255 : 0;
      tpixels[(i * img->w + j)] = SDL_MapRGB(img->format, (Uint8)s, (Uint8)s, (Uint8)s);
    }
  }
  memcpy(ppixels, tpixels, img->w * img->h * sizeof * tpixels);
  free(tpixels);
}
