diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml new file mode 100644 index 00000000..384cedbd --- /dev/null +++ b/.github/workflows/pages.yml @@ -0,0 +1,66 @@ +# Sample workflow for building and deploying a Hugo site to GitHub Pages +name: Deploy Hugo site to Pages + +on: + # Runs on pushes targeting the default branch + push: + branches: ["main"] + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages +permissions: + contents: read + pages: write + id-token: write + +# Allow one concurrent deployment +concurrency: + group: "pages" + cancel-in-progress: true + +# Default to bash +defaults: + run: + shell: bash + +jobs: + # Build job + build: + runs-on: ubuntu-latest + env: + HUGO_VERSION: 0.99.0 + steps: + - name: Install Hugo CLI + run: | + wget -O ${{ runner.temp }}/hugo.deb https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_extended_${HUGO_VERSION}_Linux-64bit.deb \ + && sudo dpkg -i ${{ runner.temp }}/hugo.deb + - name: Checkout + uses: actions/checkout@v3 + with: + submodules: recursive + - name: Setup Pages + id: pages + uses: actions/configure-pages@v1 + - name: Build with Hugo + run: | + hugo \ + --minify \ + --baseURL ${{ steps.pages.outputs.base_url }} + - name: Upload artifact + uses: actions/upload-pages-artifact@v1 + with: + path: ./public + + # Deployment job + deploy: + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + needs: build + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v1 diff --git a/.gitignore b/.gitignore index 7220fb2e..4e5d0e86 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ # Logs *.log .hugo_build.lock +.DS_Store \ No newline at end of file diff --git a/.gitmodules b/.gitmodules index 1d95c411..eb663cee 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,6 @@ [submodule "themes/book"] path = themes/book url = https://github.com/alex-shpak/hugo-book +[submodule "themes/ananke"] + path = themes/ananke + url = https://github.com/theNewDynamic/gohugo-theme-ananke.git diff --git a/README.md b/README.md index 244e35f3..efd2393d 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,9 @@ -# Showcase Template +# Grupo de estudio +- Angela Cardenas +- Diego Carvajal: Estudiante de sistemas con intereses en el desarollo de mecánicas interactivas en la web, +- Brayan Portela +- David Muñoz -Welcome to the [gohugo](https://gohugo.io/) template to create rich content [academic reports](https://www.wordy.com/writers-workshop/writing-an-academic-report/) having [p5.js](https://p5js.org/) sketches. - -## Hacking - -Install the [gohugo](https://gohugo.io/) [static site generator](https://jamstack.org/generators/) then: ```sh $git clone https://github.com/VisualComputing/showcase @@ -12,12 +11,3 @@ $cd showcase $git submodule update --init --recursive $hugo server -D --disableFastRender ``` - -Deploy with `$git push` after redefined `baseURL` in `config.toml` which should point to your actual public remote. - -### Remarks - -1. If you renamed the repo, say to `newreponame`, don't forget to update all url references of the markdown and js file sources, to reflect that change, i.e., look in all the [content folder](https://github.com/VisualComputing/showcase/tree/main/content) files for `showcase` occurrences and replace them by `newreponame`. -2. If you forked the repo don't forget to activate the [actions](https://github.com/VisualComputing/showcase/actions). -3. Don't forget to select the `gh-pages` branch as the one to serve your site from at the [pages section of your repo configuration page](https://docs.github.com/en/pages/getting-started-with-github-pages/configuring-a-publishing-source-for-your-github-pages-site), if it is no so by default. -4. The **showcase** template uses the [hugo-book](https://github.com/alex-shpak/hugo-book) theme by default. Check the [hugo themes site](https://themes.gohugo.io/) if you wish to add other ones. \ No newline at end of file diff --git a/config.toml b/config.toml index 3a9cf553..7665fdf9 100644 --- a/config.toml +++ b/config.toml @@ -1,7 +1,7 @@ -baseURL = "https://visualcomputing.github.io/showcase" +baseURL = "https://dicarvajalb.github.io/visual_computing" languageCode = "en-us" -title = "Showcase Template" -theme = 'book' +title = "Grupo de estudio" +theme = "book" # Book configuration disablePathToLower = true @@ -22,7 +22,7 @@ enableGitInfo = true # Set source repository location. # Used for 'Last Modified' and 'Edit this page' links. - BookRepo = 'https://github.com/visualcomputing/showcase' + BookRepo = 'https://github.com/Dicarvajalb/visual_computing' # Configure the date format used on the pages # - In git information @@ -35,3 +35,4 @@ enableGitInfo = true # Theme will print warning if page referenced in markdown does not exists. BookPortableLinks = false + diff --git a/content/_index.md b/content/_index.md index 39001154..79e8d69c 100644 --- a/content/_index.md +++ b/content/_index.md @@ -3,37 +3,12 @@ title: Introduction type: docs --- -# Showcase Template - -Welcome to the [gohugo](https://gohugo.io/) template to create rich content [academic reports](https://www.wordy.com/writers-workshop/writing-an-academic-report/) having [p5.js](https://p5js.org/) sketches. - -## Hacking - -Install the [gohugo](https://gohugo.io/) [static site generator](https://jamstack.org/generators/) then: - -```sh -$git clone https://github.com/VisualComputing/showcase -$cd showcase -$git submodule update --init --recursive -$hugo server -D --disableFastRender -``` - -Deploy with `$git push` after redefined `baseURL` in `config.toml` which should point to your actual public remote. - -### Remarks - -{{< hint info >}} -If you renamed the repo, say to `newreponame`, don't forget to update all url references of the markdown and js file sources, to reflect that change, i.e., look in all the [content folder](https://github.com/VisualComputing/showcase/tree/main/content) files for `showcase` occurrences and replace them by `newreponame`. -{{< /hint >}} +# Grupo de estudio +- Angela Cardenas {{< hint info >}} -If you forked the repo don't forget to activate the [actions](https://github.com/VisualComputing/showcase/actions). +**Diego Carvajal:** +Soy estudiante de sistemas con intereses en el desarollo de mecánicas interactivas en la web, me gusta correr, las películas de suspenso, los libros de ciencia ficción y el arte/estilo ciberpunk. {{< /hint >}} - -{{< hint info >}} -Don't forget to select the `gh-pages` branch as the one to serve your site from at the [pages section of your repo configuration page](https://docs.github.com/en/pages/getting-started-with-github-pages/configuring-a-publishing-source-for-your-github-pages-site), if it is no so by default. -{{< /hint >}} - -{{< hint info >}} -The **showcase** template uses the [hugo-book](https://github.com/alex-shpak/hugo-book) theme by default. Check the [hugo themes site](https://themes.gohugo.io/) if you wish to add other ones. -{{< /hint >}} \ No newline at end of file +- Brayan Portela +- David Muñoz \ No newline at end of file diff --git a/content/docs/shortcodes/Taller 1/Convoluciones.md b/content/docs/shortcodes/Taller 1/Convoluciones.md new file mode 100644 index 00000000..096086f9 --- /dev/null +++ b/content/docs/shortcodes/Taller 1/Convoluciones.md @@ -0,0 +1,313 @@ +# **1. Convoluciones** +--- +## Problem statement + +Una convolucion sobre una imagen es un calculo matematico sobre un conjunto de pixeles sobre la misma, esta operacion hace uso de los denominados **Kernel**; +Un kernel es una matriz con valores determinados los cuales permiten aplicar diferentes mascaras sobre las imagenes, los valores dentro de las matrices de los kernel se pueden alterar con base en el resultado que se desee obtener se pueden modificar. + +- Se desea una aplicacion web que pueda aplicar diferentes convoluciones a una imagen. + +## Background + +La **operacion de convolucion** se define como: + +{{< katex display >}} +g(x,y)=\omega *f(x,y)=\sum _{dx=-a}^{a}{\sum _{dy=-b}^{b}{\omega (dx,dy)f(x-dx,y-dy)}} +{{< /katex >}} + +Sin embargo, se puede definir mas facilmente si se utiliza el kernel como un vector 1-dimensional asi. Con este vector, se toman los 4 canales **__R,G,B,A__** y se separan en vectores que puedan operarse de manera escalar, recordemos que el producto escalar entre dos vectores se define como; + + +{{< katex display >}} +u \cdot v = u {\displaystyle =u_{1}\cdot v_{1}+u_{2}\cdot v_{2}+...+u_{n}\cdot v_{n}} {\displaystyle =u_{1}\cdot v_{1}+u_{2}\cdot v_{2}+...+u_{n}\cdot v_{n}}, +{{< /katex >}} + + +**Precaucion** +> Al operar la imagen se deben tener en cuenta la inexistencia de pixeles externos, si se aplicara la convolucion donde el centro del kernel se ubica sobre el primer pixel, habran posiciones que no esten definidas por lo cual hay dos posibles alternativas. +* Operar desde el pixel **(1,1)** +* Operar desde el pixel **(0,0)** pero reescribiendo toda la imagen añadiendo pixeles de valor 0 al rededor de la imagen; +--- + +{{< hint info >}} +**¿Como interactuar con la ilusión?** +Para cambiar los efectos sobre la imagen hay de usar el Slider para seleccionar uno +de los kernels, ya despues de seleccionado se debe presionar el boton **Recargar canvas**. +{{< /hint >}} + +**Kernels disponibles** + + +| Name | Matrix | +|-----------|--------| +|Identity| [0, 0, 0, 0, 1, 0, 0, 0, 0]| +|Sharpen| [0, -1, 0, -1, 5, -1, 0, -1, 0]| +|Box Blur| [1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9]| +|Edge Detection| [-1, -1, -1, -1, 8, -1, -1, -1, -1]| +|Gaussian Blur| [1, 2, 1, 2, 4, 2, 1, 2, 1]| +|Emboss| [-2, -1, 0, -1, 1, 1, 0, 1, 2]| +|Bottom Sobel| [-1,2,-1,0,0,0,1,2,1]| +|Outline| [-1,-1,-1,-1,8,-1,-1,-1,-1]| +|Top Sobel| [1,2,1,0,0,0,-1,-2,-1| + +## Code + +{{< p5-iframe sketch="/visual_computing/sketches/convolutions.js" width="625" height="625" >}} + +{{< details "**CODIGO:** Convoluciones" close >}} +**C**odigo generado usando el editor web de **P5.js**. +```javascript + var img,kernel; +let channelsMap,RedMat,BlueMat,GreenMat,newChannels,fMap; + +function preload() { + img = loadImage('/showcase/sketches/bubbleCatC.png'); +} + +function setup() { + createCanvas(600,600); + noLoop(); + + //Boton de Recarga + button = createButton('Recargar Canvas'); + button.position(10, 10); + button.mousePressed(reload); + + //Cambiar el kernel + slider = createSlider(1, 9, 1, 1); + slider.position(200, 10); + slider.style('width', '120px'); +} + +//Calcular el producto punto +function ppunto(Pix,Ker){ + let sum = 0; + for(let x = 0;x < Ker.length;x++){ + sum = sum + (Pix[x]*Ker[x]) + } + return sum; +} + +//Dividimos los canales en arreglos individuales +function ChannelDivider(ImgArr){ + let imgRed = [], imgGreen = [], imgBlue = [], imgAlpha = []; + for(let i = 0; i < ImgArr.length ; i+=4){ + imgRed.push(ImgArr[i]); + imgGreen.push(ImgArr[i+1]); + imgBlue.push(ImgArr[i+2]); + imgAlpha.push(ImgArr[i+3]); + } + return [imgRed,imgGreen,imgBlue,imgAlpha] +} + +//Recomponer la imagen +function ChannelComposer(R,G,B,A){ + let imageChannels = []; + for(let i = 0; i < A.length*4 ; i+=4){ + imageChannels[i] = R[i/4]; + imageChannels[i+1] = G[i/4]; + imageChannels[i+2] = B[i/4]; + imageChannels[i+3] = A[i/4]; + } + return imageChannels; +} + +//separar los arreglos para hacer una matriz +function ArraySplice(arr,dim){ + var matrix = [], i, k; + for (i = 0, k = -1; i < arr.length; i++) { + if (i % dim === 0) { + k++; + matrix[k] = []; + } + matrix[k].push(arr[i]); + } + return matrix; +} +//Reescribir el arreglo como matriz +function dimensioner(LTM){ + var extended = []; + for(let r = 0; r < LTM.length ; r++){ + for(let c = 0; c < LTM[r].length; c++){ + //Si estoy en el primer pixel + if(r==0 && c==0){ + extended.push( + [0,0,0, + 0,LTM[r][c],LTM[r][c+1], + 0,LTM[r+1][c],LTM[r+1][c+1]] + ); + }else + //si estoy en la primer fila + if(r==0 && (c>0 && c!=LTM[r].length - 1)){ + extended.push( + [0,0,0, + LTM[r][c-1],LTM[r][c],LTM[r][c+1], + LTM[r+1][c-1],LTM[r+1][c],LTM[r+1][c+1]] + ); + }else + //Si estoy en el el ultimo pixel de una fila + if(r==0 && c==LTM[r].length - 1){ + extended.push( + [0,0,0, + LTM[r][c-1],LTM[r][c],0, + LTM[r+1][c-1],LTM[r+1][c],0] + ); + }else + + //si estoy en el primer pixel de una columna + if((r>0 && r0 && r0 && c }} + +--- + +## Conclusions + +El ejercicio es bastante complejo debido a las limitantes que existen al momento del renderizado, Sin embargo la manipulacion matematica de la imagen permite un acercamiento practico a funciones utilizadas por editores graficos lo cual permite entender que procesos se realizan bajo las interfaces para poder obtener resultados. \ No newline at end of file diff --git a/content/docs/shortcodes/Taller 1/Histograma.md b/content/docs/shortcodes/Taller 1/Histograma.md new file mode 100644 index 00000000..99cfb346 --- /dev/null +++ b/content/docs/shortcodes/Taller 1/Histograma.md @@ -0,0 +1,89 @@ +# Histograma +--- +## Problem statement + +Un histograma de imagen es una representación gráfica de la distribución tonal en una imagen digital. Para esto traza el número de píxeles para cada valor tonal de manera que al mirar el histograma de una imagen específica, un espectador podrá juzgar la distribución tonal completa de un vistazo. + +Tiene muchos usos entre ellos sirve dar al fotógrafo una mejor comprensión de los valores de brillo en una imagen. + + + +## Background +Un histograma es una representación de la distribución de datos numericos, este fue creado por Karl Pearson. Este tiene 2 ejes x y y, el primero contiene eventos cuya frecuencia debe contar y el otro contiene la frecuencia. + +## Code + +{{< p5-iframe sketch="/visual_computing/sketches/histogram.js" width="720" height="420" >}} +{{< p5-iframe sketch="/visual_computing/sketches/histogram2.js" width="700" height="440" >}} +{{< p5-iframe sketch="/visual_computing/sketches/histogram3.js" width="400" height="400" >}} + +{{< details "**CODIGO:** Histograma" close >}} +**C**odigo generado usando el editor web de **P5.js**. +```javascript +var img; +var maxRange = 256; +var histogram = new Array(maxRange); +function preload() { + img = loadImage("/visual_computing/sketches/einstein.jpg"); // Load the image +} + +function setup() { + createCanvas(img.width, img.height+10); + background(255); + img.resize(0,400); + colorMode(HSL, maxRange); + image(img, 0, 0); + + for (i = 0; i <= maxRange; i++) { + histogram[i] = 0 + } + + transform_rgb(); + + construir_histograma(); + +} + +function construir_histograma(){ + image(img, 0, 0); + stroke(300,100,80) + push() + translate(10,0) + for (x = 0; x <= maxRange; x++) { + index = histogram[x]; + + y1=int(map(index, 0, max(histogram), img.height, img.height-200)); + y2 = img.height + xPos = map(x,0,maxRange,0, img.width-20) + stroke('red'); + line(xPos, y1, xPos, y2); + + } + pop() +} + +function transform_rgb(){ + loadPixels(); + + for (var x = 0; x < img.width; x+=5) { + for (var y = 0; y < img.height; y+=5) { + var loc = (x + y * img.width) * 4; + var h = pixels[loc]; + var s = pixels[loc + 1]; + var l = pixels[loc + 2]; + var a = pixels[loc + 3]; + b = int(l); + histogram[b]++ + } + } +} + + //Bibliografia: https://editor.p5js.org/ebenjmuse/sketches/HyPfeGkCZ +``` +{{< /details >}} + +--- + +## Conclusions + +El ejercicio es bastante complejo debido a que debe adaptarse a cualquier imagen, pero es un analisis muy util de la imagen ya que con un solo vistazo se sabe cual es la tendencia de los colores. \ No newline at end of file diff --git a/content/docs/shortcodes/Taller 1/Ilusiones/BindingMovement.md b/content/docs/shortcodes/Taller 1/Ilusiones/BindingMovement.md new file mode 100644 index 00000000..5d6f8f2b --- /dev/null +++ b/content/docs/shortcodes/Taller 1/Ilusiones/BindingMovement.md @@ -0,0 +1,149 @@ +# Movimiento Enlazado +--- +## Problem statement + +La presente ilusión muestra 4 líneas aparentemente moviéndose de forma _independiente_, sin embargo, al revisarlas de forma extensiva se puede notar que se mueven en pares ordenados paralelos. La figura que describe este movimiento corresponde a un rombo el cual posee sus vértices ocultos; + +Al hacer que los vértices sean visibles se puede notar como el tenerlos ocultos crea el movimiento ilusorio. + +{{< hint info >}} +**¿Como interactuar con la ilusión?** +Para visibilizar las figuras que desmontan la ilusión es necesario marcar +el checkbox **"Visible"** , el Slider que se encuentra permite cambiar la +visibilidad _"Alpha"_ de las figuras. +{{< /hint >}} + +## Code + +{{< p5-global-iframe id="sketchid" width="625" height="625" >}} + let bgColor = 200, checkbox; + function setup() { + createCanvas(600,600); + angleMode(DEGREES); + rectMode(CENTER); + + //transparency + slider = createSlider(20, 255, 100); + slider.position(10, 10); + slider.style('width', '80px'); + + //Squares Transparency + checkbox = createCheckbox('Visible', false); + checkbox.position(10,40); + + } + + function drawSquares(visible){ + let xAxis = 150; + let yAxis = 150; + let size = 120; + + rotate(45); + + if(!checkbox.checked()){ + fill(bgColor); + noStroke() + }else{ + let alpha = slider.value(); + fill(0,100,100,alpha); + noStroke(); + } + + rect(xAxis,-yAxis,size,size); + rect(-xAxis,yAxis,size,size); + rect(xAxis,yAxis,size,size); + rect(-xAxis,-yAxis,size,size); + } + + function mainSquare(){ + translate(p5.Vector.fromAngle(millis()/500,40)); + let bSize = 300; + rotate(45); + fill(bgColor) + stroke(0, 0, 255); + strokeWeight(6); + rect(0,0,bSize,bSize); + } + + function draw() { + background(bgColor); + translate(width/2,height/2); + + push(); + mainSquare(); + pop(); + + drawSquares(false); + } +{{< /p5-global-iframe >}} + +{{< details "**CODIGO:** Movimiento Enlazado" close >}} +**C**odigo generado usando el editor web de **P5.js**. +```javascript + let bgColor = 200, checkbox; + function setup() { + createCanvas(600,600); + angleMode(DEGREES); + rectMode(CENTER); + + //transparency + slider = createSlider(20, 255, 100); + slider.position(10, 10); + slider.style('width', '80px'); + + //Squares Transparency + checkbox = createCheckbox('Visible', false); + checkbox.position(10,40); + + } + + function drawSquares(visible){ + let xAxis = 150; + let yAxis = 150; + let size = 120; + + rotate(45); + + if(!checkbox.checked()){ + fill(bgColor); + noStroke() + }else{ + let alpha = slider.value(); + fill(0,100,100,alpha); + noStroke(); + } + + rect(xAxis,-yAxis,size,size); + rect(-xAxis,yAxis,size,size); + rect(xAxis,yAxis,size,size); + rect(-xAxis,-yAxis,size,size); + } + + function mainSquare(){ + translate(p5.Vector.fromAngle(millis()/500,40)); + let bSize = 300; + rotate(45); + fill(bgColor) + stroke(0, 0, 255); + strokeWeight(6); + rect(0,0,bSize,bSize); + } + + function draw() { + background(bgColor); + translate(width/2,height/2); + + push(); + mainSquare(); + pop(); + + drawSquares(false); + } +``` +{{< /details >}} + +--- + +## Conclusions + +Para el ojo inexperto el movimiento puede resultar complejo ya que la ilusion cumple con el objetivo y de primera mano da a enter que tras ella se requieren calculos y codigos complejos para obtener la sincronizacion. Sin embargo, el desarrollo del ejercicio permite entender como la manipulacion geometrica y de factores como perspectiva y velocidad permiten generar animaciones complejas. \ No newline at end of file diff --git a/content/docs/shortcodes/Taller 1/Ilusiones/SKE.md b/content/docs/shortcodes/Taller 1/Ilusiones/SKE.md new file mode 100644 index 00000000..d9ca04b8 --- /dev/null +++ b/content/docs/shortcodes/Taller 1/Ilusiones/SKE.md @@ -0,0 +1,58 @@ +# Efecto esteroquinético + +## Problem statement + +El efecto esteroquinético es una ilusión visual de la profundidad. Es un efecto ilusorio que depende del movimiento. Se basa en que la rotación de figuras adecuadas crea una ilusión tridimensional + +## Code + +Pasos dentro del código: + +1. Dibujar el primer circulo +2. Iterar por cada círculo definiendo su rotación y su posición. + +{{< details title="source code" open=false >}} +{{< highlight html >}} +let angle = 0; +let speed = 0.05; +let circleColor = true; + +function setup() { +createCanvas(400, 400); +} + +function draw() { +background(220); +angle += speed; +strokeWeight(1) +circle(200,200,400); +cirrcle(375) +} + +function cirrcle(size){ +fill(255,255,0) +if(circleColor){ +fill(0,0,255) + } +circleColor = !circleColor + +if(size>100){ +translate(p5.Vector.fromAngle(millis() / 1000, 12.5)); +strokeWeight(0) +circle(200,200, size); +cirrcle(size-25) +}else if(size>0){ +translate(p5.Vector.fromAngle(millis() / 1000, -12.5)); +circle(200,200, size); + cirrcle(size-25) +} +return +} +{{< /highlight >}} +{{< /details >}} + +{{< p5-iframe sketch="/visual_computing/sketches/illusion3d.js" width="450" height="450" >}} + +## Conclusions + +Es una manera muy interesante de crear la ilusión de la tercera dimensión, estos conceptos van encaminados hacia la creación de gráficas en 3D. diff --git a/content/docs/shortcodes/Taller 1/Ilusiones/SteppingFeet.md b/content/docs/shortcodes/Taller 1/Ilusiones/SteppingFeet.md new file mode 100644 index 00000000..e9769bdf --- /dev/null +++ b/content/docs/shortcodes/Taller 1/Ilusiones/SteppingFeet.md @@ -0,0 +1,184 @@ +# Paso a paso +--- +## Problem statement + +Tambien llamada Stepping feet, es una ilusión visual de percepción de movimiento. Esta muestra dos pies, uno azul y otro amarillo, que se mueven horizontalmente a través de un paisaje que consta de rayas blancas y negras. Aunque ambos pies se mueven a una velocidad constante, su velocidad percibida es distinta. + + +{{< hint info >}} +**¿Como interactuar con la ilusión?** +Para cambiar la velocidad de las figuras se usa el primer slider, para cambiar la relación baras/pie se usa el segundo slider y para mover o detener los pies se debe clickear la casilla de move. +{{< /hint >}} + +## Code + +{{< p5-iframe sketch="/visual_computing/sketches/stepping_feet.js" width="625" height="625" >}} + +{{< details "**CODIGO:** Paso a paso" close >}} +**C**odigo generado usando el editor web de **P5.js**. +```javascript +var canvasWidth = 600; +var canvasHeight = 400; + +var quantity = 2; +var speed = 1; + +var positionXBar1 = 0; +var positionYBar1 = canvasHeight / 3; +var positionYBar2 = (2*canvasHeight) / 3; +var widthBar = 80; +var heightBar = 40; +var colorBar1 = 'yellow'; +var colorBar2 = 'blue'; +var moveBarRight = true; +var isMove = true; + +var sliderSpeed; + +function setup() { + createCanvas(canvasWidth, canvasHeight); + background('white'); + drawLayout(); +} + +function draw() { + drawBoard(); + updateSpeed(); + drawBar1(); + drawBar2(); +} + +function drawBoard(){ + let position; + + quantity = sliderQuantity.value(); + + let realLines = (canvasWidth / widthBar) * quantity; + let widthLine = widthBar / quantity; + let numberLines = realLines % 2 == 0 ? realLines + 1 : realLines; + + for (let i = 0; i < numberLines; i++) { + position = i * widthLine; + if (i % 2 == 0) { + fill('black'); + rect(position, 0, widthLine, canvasHeight); + } else { + strokeWeight(0) + fill('white'); + rect(position, 0, widthLine, canvasHeight); + } + } +} + +function drawBar1(){ + fill(colorBar1); + rect(positionXBar1, positionYBar1, widthBar, heightBar); + if (moveBarRight) { + positionXBar1 += speed; + if (positionXBar1 + widthBar > canvasWidth) { + moveBarRight = false; + } + } else { + positionXBar1 -= speed; + if (positionXBar1 <= 0) { + moveBarRight = true; + } + } +} + +function drawBar2() { + fill(colorBar2); + rect(positionXBar1, positionYBar2, widthBar, heightBar); + if (moveBarRight) { + positionXBar1 += speed; + if (positionXBar1 + widthBar > canvasWidth) { + moveBarRight = false; + } + } else { + positionXBar1 -= speed; + if (positionXBar1 <= 0) { + moveBarRight = true; + } + } + } + + function updateSpeed() { + if (isMove) { + speed = sliderSpeed.value(); + } + } + +function drawLayout() { + //Reset button + button = createButton('Reset'); + button.position(40, 440); + button.mousePressed(() => { + canvasWidth = 600; + canvasHeight = 400; + quantity = 2; + speed = 1; + positionXBar1 = 0; + positionYBar1 = canvasHeight / 3; + positionXBar2 = 0; + positionYBar2 = (2*canvasHeight) / 3; + widthBar = 80; + heightBar = 40; + moveBarRight = true; + }); + + //Move checkbox + checkbox = createCheckbox('Move', isMove); + checkbox.position(40, 470); + checkbox.mousePressed(() => { + if (speed === 0) { + isMove = true; + speed = sliderSpeed.value(); + } else { + isMove = false; + speed = 0; + } + }); + + //Slider speed + sliderSpeed = createSlider(1, 10, 1); + sliderSpeed.position(40, 500); + sliderSpeed.style('width', '80px'); + + //Slider quantity + sliderQuantity = createSlider(1, 10, 1); + sliderQuantity.position(40, 540); + sliderQuantity.style('width', '80px'); + + //Change color + sel = createSelect(); + sel.position(40, 580); + sel.option('blue-yellow'); + sel.option('red-green'); + sel.option('grey'); + sel.selected('kiwi'); + sel.changed((value) => { + switch(value.target.value) { + case 'blue-yellow': + colorBar1 = 'yellow' + colorBar2 = 'blue' + break; + case 'red-green': + colorBar1 = 'green' + colorBar2 = 'red' + break; + case 'grey': + colorBar1 = 'white' + colorBar2 = 'black' + break; + } + }); + +} +``` +{{< /details >}} + +--- + +## Conclusions + +La clave de esta ilusión es el contraste, ya que cuando hay un mayor contraste entre el pie y el fondo, el pie se hace visible más facilmente y da una sensación de movimiento rapido mientras que cuando el contraste es bajo, el pie es más dificil de diferenciar del fondo y parecer ir más lento. Esta ilusió demuestra que el fondo de un objeto puede tener un efecto significativo en su velocidad percibida. \ No newline at end of file diff --git a/content/docs/shortcodes/Taller 1/Ilusiones/_index.md b/content/docs/shortcodes/Taller 1/Ilusiones/_index.md new file mode 100644 index 00000000..ab17ba59 --- /dev/null +++ b/content/docs/shortcodes/Taller 1/Ilusiones/_index.md @@ -0,0 +1,13 @@ +--- +bookCollapseSection: true +--- + +# Taller 1 + +## Objetivo + +En este taller fortaleceremos conceptos de manipulación de píxeles para la modificación de una imagen mediante Kernels, reproduciremos ilusiones ópticas para familiarizarnos con P5.js y construiremos un visualizador de histogramas. + +## Types + +{{
}} diff --git a/content/docs/shortcodes/Taller 1/Lightness.md b/content/docs/shortcodes/Taller 1/Lightness.md new file mode 100644 index 00000000..f64f9013 --- /dev/null +++ b/content/docs/shortcodes/Taller 1/Lightness.md @@ -0,0 +1,87 @@ +# Lightness + +## Problem statement + +Sería útil tener una herramienta que permita la manipulación de luminosidad de una imagen, y de esta manera poder aclarar imágenes oscuras para poder ver sus siluetas. + +## Background + +- Manipulación de pixeles usando `P5.js` +- Uso de [HSL](https://en.wikipedia.org/wiki/HSL_and_HSV#Lightness) +- Conversión entre HSL y RGB + +## Code + +Pasos dentro del código: + +1. Cargar la imagen a manipular y el `botón de rango` +2. Dado un valor en el `botón de rango`, se aumenta la luminosidad de cada pixel en la imagen.S + +{{< details title="source code" open=false >}} +{{< highlight html >}} + +new p5((p) =>{ +let img; +let myPixels; +p.preload = function() { +img = p.loadImage("/showcase/sketches/medusa.jpeg"); +} + +p.setup = function () { +p.createCanvas(400, 400); +let inp = p.createInput("0","range"); + +inp.size(100); + +inp.input((e) => handleBtn(e)); + +inp.position(0,p.height-20) +p.image(img, 0, 0, p.width, p.height); +p.colorMode(p.RGB) +p.loadPixels(); +myPixels = [...p.pixels] +console.log("myPixels",myPixels[0]) +} + +p.draw = function (){ + +} + +handleBtn= function(inp){ +console.log("inp", inp.target.value) +let d = p.pixelDensity(); +let halfImage = 4 _ (p.width _ d) _ (p.height _ d); +for (let i = 0; i < halfImage; i += 4) { + +let colorRGB = p.color(myPixels[i],myPixels[i+1], myPixels[i+2]) +let hueValue = p.floor( p.hue(colorRGB) ); +let saturationValue = p.saturation(colorRGB); +let lightnessValue = p.lightness(colorRGB); + +let colorHSV = p.color(`hsl(${ hueValue }, ${ saturationValue }%, ${ (lightnessValue + parseFloat(inp.target.value))}%)`) + +p.pixels[i] = p.red(colorHSV); +p.pixels[i + 1] = p.green(colorHSV); +p.pixels[i + 2] = p.blue(colorHSV); +p.pixels[i + 3] = p.alpha(colorHSV); +} +p.updatePixels(); +console.log("myPixels",myPixels[0]) +} + +handleImg = function(event){ +console.log("event.target",event.target.value) +p.loadImage(event.target.value, img2 => { +p.image(img2, 0, 0, p.width, p.height); +}); + +} +}) +{{< /highlight >}} +{{< /details >}} + +{{< p5-iframe sketch="/visual_computing/sketches/lightness.js" width="450" height="450" >}} + +## Conclusions + +Esta forma de manipular los pixeles llega a buenos resultados en cuanto a la modificación de luminocidad, pero es costosa computacionalmente, sería interesante descubrir el trabajo que realizan programas como Photoshop para lograr una óptima manipulación sobre una imagen. diff --git a/content/docs/shortcodes/Taller 1/Multiplicacion RGB.md b/content/docs/shortcodes/Taller 1/Multiplicacion RGB.md new file mode 100644 index 00000000..9d547b76 --- /dev/null +++ b/content/docs/shortcodes/Taller 1/Multiplicacion RGB.md @@ -0,0 +1,54 @@ +# Multiplicación RGB + +## Problem statement + +¿Qué sucede si multiplicamos dos colores RGB? + +## Code + +Pasos dentro del código: + +1. Obtener los 2 valores RGB de la paleta +2. Calcular su multiplicación y mostrarla en pantalla + +{{< details title="source code" open=false >}} +{{< highlight html >}} +let backgroundColor; +let color1, color2 +function setup() { + createCanvas(200, 200); + let c1 = createInput("0,0,0",'color') + let c2 = createInput("0,0,0",'color') + + + c1.input(()=> setColor1(c1,c2)) + c2.input(()=> setColor1(c1,c2)) +} + +function setColor1(c1,c2){ + let color1 = color(red(c1.value()), green(c1.value()), blue(c1.value())) + let black = color(0,0,0) + fill(color1) + rect(0,0, 130,130) + let color2 = color(red(c2.value()), green(c2.value()), blue(c2.value())) + fill(color2) + rect(70,70, 130,130) + + //let white = color(255,255,255) + + const cred = (red(c1.value()) * red(c2.value())) / 255; + const cblue = (blue(c1.value()) * blue(c2.value())) / 255; + const cgreen = (green(c1.value()) * green(c2.value())) /255; + fill(color(cred, cgreen,cblue)) + rect(70,70, 60,60) + //background(cred,cgreen,cblue) + +} +{{< /highlight >}} +{{< /details >}} + +{{< p5-iframe sketch="/visual_computing/sketches/RGBmultiply.js" width="450" height="450" >}} + +## Conclusions + +La multiplicación RGB, bajo algunos casos, hacer ver que cuadrados tienen una cierta transparencia, y que los colores se combinan. diff --git a/content/docs/shortcodes/Taller 1/_index.md b/content/docs/shortcodes/Taller 1/_index.md new file mode 100644 index 00000000..ab17ba59 --- /dev/null +++ b/content/docs/shortcodes/Taller 1/_index.md @@ -0,0 +1,13 @@ +--- +bookCollapseSection: true +--- + +# Taller 1 + +## Objetivo + +En este taller fortaleceremos conceptos de manipulación de píxeles para la modificación de una imagen mediante Kernels, reproduciremos ilusiones ópticas para familiarizarnos con P5.js y construiremos un visualizador de histogramas. + +## Types + +{{
}} diff --git a/content/docs/shortcodes/Taller 2/Aplicacion 3-D/Laberinto.md b/content/docs/shortcodes/Taller 2/Aplicacion 3-D/Laberinto.md new file mode 100644 index 00000000..143db232 --- /dev/null +++ b/content/docs/shortcodes/Taller 2/Aplicacion 3-D/Laberinto.md @@ -0,0 +1,348 @@ +# Laberinto 3-D + +## Problema + +Implemente una aplicacion 3D con WebGL. Puede usar la libreria p5.treegl o cualquier otra libreria necesaria. + +## Introduccion + +Un **laberinto** es un lugar compuesto por un conjunto de calles y encrucijadas con una disposicion compleja. El Objetivo de los laberintos es confudir a quienes se adentren dentro del mismo. Historicamente, los laberintos han sido mencionados en la mitologia como retos para los heroes **["El laberinto de Creta"]** asi mismo como una representacion artistica para la inteligencia y destreza. + +## Desarrollo + +Para poder Cumplir el objetivo de la aplicacion, se presenta el siguiente curso de acción tomado para el desarrollo. + +- Crear los objetos con ayuda de **P5.js**. +- Migrar los objetos a **p5.treegl** . +- Inclinar un plano en **3D**. +- Creacion de **colisiones** entre objetos. +- Mover un objeto sujeto al plano y sobre el plano. +- Induccion de fuerzas y mecanicas [**Aceleracion,Gravedad**]. + +## Codigos + +--- + +1. **Colisiones y Movimiento sobre la inclinacion del plano:** Haciendo uso de las libreria p5.treegl y los metodos nativos de p5, se consigue rotar un plano con base en el movimiento que dicte el cursor. Sobre este plano se encuentra una esfera la cual esta colisionando contra este. La esfera se movera sieguien el vector de rotacion y orientacion del plano. + +{{< hint info >}} +**¿Como interactuar con el plano?** +Para cambiar la inclinacion debe deslizar el mouse presionando el boton de click derecho sobre el Canvas. Para mover la esfera use las teclas **"a"** y **"d"**. +{{< /hint >}} + +{{< details "**CODIGO:** Colisiones y Movimiento" close >}} + +```javascript +let planePosition, + planeSize, + planeColor, + planeRotateV, + planeMagnitudeR, + planeMaxMagR; +let spherePosition, sphereMoveVector, sphereRadius, maxVertex, minVertex; +let fbo1, + cam1, + length = 600, + boxes, + box_key; +let mouseInitialV, mouseCurrentV, fovy; + +const SPEED = 5; + +function createPlane() { + planeMaxMagR = 25; + planeColor = "black"; + planeMagnitudeR = 0; + + planeRotateV = createVector(1, 0, 0); + planeSize = createVector(100, 50, 0); //ancho y alto + planePosition = createVector(0, 0, 0); +} + +function createSphere() { + sphereMoveVector = createVector(0, 1, 0); + sphereRadius = 10; + spherePosition = createVector(0, 0, sphereRadius); + + minVertex = createVector(-planeSize.x / 2, -planeSize.y / 2, 0); + maxVertex = createVector(planeSize.x / 2, planeSize.y / 2, 0); +} + +function setup() { + createCanvas(length, length); + fbo1 = createGraphics(width, height, WEBGL); + + // FBO camera + cam1 = new Dw.EasyCam(fbo1._renderer, { distance: 200 }); + let state1 = cam1.getState(); + cam1.state_reset = state1; // state to use on reset (double-click/tap) + cam1.setViewport([0, 0, width / 2, height]); + document.oncontextmenu = function () { + return false; + }; + + //Interactive elements + createPlane(); + createSphere(); + + // scene interactions + fovy = createSlider(PI / 12, PI * (11 / 12), PI / 3, PI / 48); + fovy.position(10, 10); + fovy.style("width", "80px"); +} + +function draw() { + //Background elements + fbo1.background(120, 125, 115); + fbo1.reset(); + fbo1.perspective(fovy.value()); + fbo1.axes(); + fbo1.grid(); + fbo1.rotate((PI / 100) * planeMagnitudeR, planeRotateV); + + //Dibujar el plano + fbo1.push(); + fbo1.fill(planeColor); + fbo1.translate(planePosition); + fbo1.plane(planeSize.x, planeSize.y); + fbo1.pop(); + + //Dibujar la esfera + fbo1.push(); + fbo1.fill("white"); + fbo1.translate(spherePosition); + fbo1.sphere(sphereRadius); + fbo1.pop(); + + // movimiento de la esfera + if (keyIsPressed && key == "a") { + spherePosition = createVector( + sphereMoveVector.x * 2 + spherePosition.x, + sphereMoveVector.y * 2 + spherePosition.y, + sphereMoveVector.z * 2 + spherePosition.z + ); + //spherePosition.z += 1 + } else if (keyIsPressed && key == "d") { + spherePosition = createVector( + sphereMoveVector.x * -2 + spherePosition.x, + sphereMoveVector.y * -2 + spherePosition.y, + sphereMoveVector.z * -2 + spherePosition.z + ); + } + + //Colisión + if ( + spherePosition.x >= minVertex.x && + spherePosition.y >= minVertex.y && + spherePosition.z - 10 >= minVertex.z && + spherePosition.x <= maxVertex.x && + spherePosition.y <= maxVertex.y && + spherePosition.z - 10 <= maxVertex.z + ) { + planeColor = "white"; + } else { + planeColor = "black"; + } + beginHUD(); + image(fbo1, 0, 0); + endHUD(); +} + +function getVectorModule(vector) { + return Math.sqrt(vector.x ** 2 + vector.y ** 2 + vector.z ** 2); +} + +function mousePressed() { + mouseInitialV = createVector(mouseX, mouseY, 0); +} + +function mouseDragged() { + mouseCurrentV = createVector(mouseX, mouseY, 0); + + let vectorSubstra = createVector( + mouseInitialV.x - mouseCurrentV.x, + mouseInitialV.y - mouseCurrentV.y, + mouseInitialV.z - mouseCurrentV.z + ); + let mod = getVectorModule(vectorSubstra); + + let vectorDir = createVector( + vectorSubstra.x / mod, + vectorSubstra.y / mod, + vectorSubstra.z / mod + ); + sphereMoveVector = createVector(vectorDir.x, vectorDir.y, vectorDir.z); + + let aux = vectorDir.x; + vectorDir.x = vectorDir.y; + vectorDir.y = -aux; + + if (mod < planeMaxMagR) { + planeMagnitudeR = mod; + } + planeRotateV = vectorDir; +} +``` + +{{< /details >}} + +## {{< p5-iframe srcdoc="lib3" srcdoc="lib4" sketch="/visual_computing/sketches/Inclination.js" width="625" height="625" >}} + +2. **Aceleracion:** Con base en el ejercicio anterior, ahora la esfera se deplaza sujeta al plano pero con una aceleracion de caracter oscilatorio dado por la funcion **Seno**. + +{{< hint info >}} +**¿Como interactuar con el plano?** +Para cambiar la inclinacion debe deslizar el mouse presionando el boton de click derecho sobre el Canvas, la esfera puede salirse del plano y del area visible por lo cual puede usar el slider para ajustar el zoom o el boton central del mouse. +{{< /hint >}} + +{{< details "**CODIGO:** Aceleracion" close >}} + +```javascript +let fbo1, cam1, fovy; +let P, B; +let mouseInitialV, mouseCurrentV; + +function Plane() { + this.planeMaxMagR = 25; + this.planeColor = "black"; + this.planeMagnitudeR = 0; + + this.planeRotateV = createVector(1, 0, 0); + this.planeSize = createVector(100, 100, 0); //ancho y alto + this.planePosition = createVector(0, 0, 0); + + this.draw = function (fbo) { + fbo.push(); + fbo.fill(this.planeColor); + fbo.translate(this.planePosition); + fbo.plane(this.planeSize.x, this.planeSize.y); + fbo.pop(); + }; +} + +function Ball(P) { + this.sphereMoveVector = createVector(0, 0, 0); + this.acceleration = createVector(0, 0, 0); + this.sphereRadius = 10; + this.spherePosition = createVector(0, 0, this.sphereRadius); + + this.minVertex = createVector(-P.planeSize.x / 2, -P.planeSize.y / 2, 0); + this.maxVertex = createVector(P.planeSize.x / 2, P.planeSize.y / 2, 0); + + this.draw = function (fbo) { + fbo.push(); + fbo.fill("white"); + fbo.translate(this.spherePosition); + fbo.sphere(this.sphereRadius); + fbo.pop(); + }; +} + +function setup() { + createCanvas(600, 600); + fbo1 = createGraphics(width, height, WEBGL); + + // FBO camera + cam1 = new Dw.EasyCam(fbo1._renderer, { distance: 200 }); + let state1 = cam1.getState(); + cam1.state_reset = state1; // state to use on reset (double-click/tap) + cam1.setViewport([0, 0, width / 2, height]); + document.oncontextmenu = function () { + return false; + }; + + // scene interactions + fovy = createSlider(PI / 12, PI * (11 / 12), PI / 3, PI / 48); + fovy.position(10, 10); + fovy.style("width", "80px"); + + P = new Plane(); + B = new Ball(P); +} + +function draw() { + fbo1.background(120, 125, 115); + fbo1.reset(); + fbo1.perspective(fovy.value()); + fbo1.axes(); + fbo1.grid(); + fbo1.rotate((PI / 180) * P.planeMagnitudeR, P.planeRotateV); + fbo1.strokeWeight(0.5); + + P.draw(fbo1); + B.draw(fbo1); + + // movimiento de la esfera + if (P.planeRotateV.x != 0 || P.planeRotateV.y != 0) { + B.sphereMoveVector.x = B.acceleration.x * 0.15 + B.sphereMoveVector.x; + B.sphereMoveVector.y = B.acceleration.y * 0.15 + B.sphereMoveVector.y; + + B.spherePosition.x = B.sphereMoveVector.x * 0.15 + B.spherePosition.x; + B.spherePosition.y = B.sphereMoveVector.y * 0.15 + B.spherePosition.y; + } else if (P.planeRotateV.x == 0 && P.planeRotateV.y == 0) { + B.sphereMoveVector = createVector(0, 0, 0); + B.acceleration = createVector(0, 0, 0); + } + + //Colisión + if ( + B.spherePosition.x >= B.minVertex.x && + B.spherePosition.y >= B.minVertex.y && + B.spherePosition.z - 10 >= B.minVertex.z && + B.spherePosition.x <= B.maxVertex.x && + B.spherePosition.y <= B.maxVertex.y && + B.spherePosition.z - 10 <= B.maxVertex.z + ) { + P.planeColor = "white"; + } else { + P.planeColor = "black"; + } + + beginHUD(); + image(fbo1, 0, 0); + endHUD(); +} + +function getVectorModule(vector) { + return Math.sqrt(vector.x ** 2 + vector.y ** 2 + vector.z ** 2); +} + +function mousePressed() { + mouseInitialV = createVector(mouseX, mouseY, 0); +} + +function mouseDragged() { + mouseCurrentV = createVector(mouseX, mouseY, 0); + let vectorSubstra = createVector( + mouseInitialV.x - mouseCurrentV.x, + mouseInitialV.y - mouseCurrentV.y, + mouseInitialV.z - mouseCurrentV.z + ); + let mod = getVectorModule(vectorSubstra); + let vectorDir = createVector( + vectorSubstra.x / mod, + vectorSubstra.y / mod, + vectorSubstra.z / mod + ); + let sine = sqrt(1 - sq(vectorDir.z)); + + B.acceleration = createVector( + -sine * vectorDir.x, + -sine * vectorDir.y, + sine * vectorDir.z + ); + + let aux = vectorDir.x; + vectorDir.x = vectorDir.y; + vectorDir.y = -aux; + + if (mod < P.planeMaxMagR) { + P.planeMagnitudeR = mod; + } + P.planeRotateV = vectorDir; + P.planeRotateV.z = 0; +} +``` + +{{< /details >}} +{{< p5-iframe srcdoc="lib3" srcdoc="lib4" sketch="/visual_computing/sketches/Acceleration.js" width="625" height="625" >}} diff --git a/content/docs/shortcodes/Taller 2/Aplicacion 3-D/LaberintoP2.md b/content/docs/shortcodes/Taller 2/Aplicacion 3-D/LaberintoP2.md new file mode 100644 index 00000000..1abf8074 --- /dev/null +++ b/content/docs/shortcodes/Taller 2/Aplicacion 3-D/LaberintoP2.md @@ -0,0 +1,2045 @@ +## Parte 2 + +--- + +3. **Colisiones y Creacion:** Tomando lo creado en los ejercicios anteriores se crea un laberinto sencillo por el cual la esfera pueda desplazarse, se trata de simular fisicas como fuerzas Newtonianas para dar realismo a la aplicacion. + +{{< hint info >}} +**¿Como interactuar con el plano?** +Para cambiar la inclinacion debe deslizar el mouse presionando el boton de click derecho sobre el Canvas, la esfera puede salirse del plano y del area visible por lo cual puede usar el slider para ajustar el zoom o el boton central del mouse. +{{< /hint >}} + +{{< details "**CODIGO:** Aceleracion" close >}} + +```javascript +function Ball(P){ + this.sphereMoveVector = createVector(0,0,0); + this.acceleration = createVector(0,0,0) + this.sphereRadius = 7; + this.spherePosition = createVector(92.5-38*4.5,38*-1,this.sphereRadius); + + this.minVertex = createVector(-P.planeSize.x/2,-P.planeSize.y/2,0); + this.maxVertex = createVector(P.planeSize.x/2,P.planeSize.y/2,0); + + this.draw = function(fbo){ + fbo.push(); + fbo.fill("rgb(0, 0, 0)"); + fbo1.noStroke(); + fbo.translate(this.spherePosition); + fbo.sphere(this.sphereRadius) + fbo.pop() + } + this.move = function(P, acceleration, factorAcc, isAcelerate){ + + if(P.planeRotateV.x != 0 || P.planeRotateV.y != 0){ + if(isAcelerate){ + this.sphereMoveVector.x = (acceleration.x*factorAcc)*isAcelerate; + this.sphereMoveVector.y = (acceleration.y*factorAcc)*isAcelerate; + + this.spherePosition.x = (this.sphereMoveVector.x*factorAcc) + this.spherePosition.x + this.spherePosition.y = (this.sphereMoveVector.y*factorAcc) + this.spherePosition.y; + } + else{ + this.sphereMoveVector.x = (acceleration.x*factorAcc) + this.sphereMoveVector.x; + this.sphereMoveVector.y = (acceleration.y*factorAcc) + this.sphereMoveVector.y; + this.spherePosition.x = (this.sphereMoveVector.x*factorAcc) + this.spherePosition.x + this.spherePosition.y = (this.sphereMoveVector.y*factorAcc) + this.spherePosition.y; + } + + }else if(P.planeRotateV.x == 0 && P.planeRotateV.y == 0){ + this.sphereMoveVector = createVector(0,0,0); + this.acceleration = createVector(0,0,0); + } + // if(P.planeRotateV.x != 0 || P.planeRotateV.y != 0){ + // B.sphereMoveVector.x = (B.acceleration.x*0.1) + B.sphereMoveVector.x; + // B.sphereMoveVector.y = (B.acceleration.y*0.1) + B.sphereMoveVector.y; + + // B.spherePosition.x = (B.sphereMoveVector.x*0.1) + B.spherePosition.x + // B.spherePosition.y = (B.sphereMoveVector.y*0.1) + B.spherePosition.y; + + // }else if(P.planeRotateV.x == 0 && P.planeRotateV.y == 0){ + // B.sphereMoveVector = createVector(0,0,0); + // B.acceleration = createVector(0,0,0); + // } + } +} + + +'use strict'; + +// See: +// https://github.com/processing/p5.js/blob/main/contributor_docs/creating_libraries.md +// https://github.com/processing/p5.js/blob/main/src/core/README.md +// https://github.com/processing/p5.js/blob/main/contributor_docs/webgl_mode_architecture.md + +/** @namespace */ +var Tree = (function (ext) { + const INFO = + { + LIBRARY: 'p5.treegl', + VERSION: '0.3.0', + HOMEPAGE: 'https://github.com/VisualComputing/p5.treegl' + }; + Object.freeze(INFO); + const NONE = 0; + // Axes consts + const X = 1 << 0; + const Y = 1 << 1; + const Z = 1 << 2; + const _X = 1 << 3; + const _Y = 1 << 4; + const _Z = 1 << 5; + const LABELS = 1 << 6; + // grid style + const SOLID = 0; + const DOTS = 1 + // bullseye and picking shape + const SQUARE = 0; + const CIRCLE = 1; + // only picking shape + const PROJECTION = 2; + // Frustum consts + const NEAR = 1 << 0; + const FAR = 1 << 1; + const LEFT = 1 << 2; + const RIGHT = 1 << 3; + const BOTTOM = 1 << 4; + const TOP = 1 << 5; + const BODY = 1 << 6; + // visibility + const INVISIBLE = 0; + const VISIBLE = 1; + const SEMIVISIBLE = 2; + // spaces + const WORLD = 'WORLD'; + const EYE = 'EYE'; + const NDC = 'NDC'; + const SCREEN = 'SCREEN'; + const MODEL = 'MODEL'; + // points + const ORIGIN = [0, 0, 0]; + // vectors + const i = [1, 0, 0]; + const j = [0, 1, 0]; + const k = [0, 0, 1]; + const _i = [-1, 0, 0]; + const _j = [0, -1, 0]; + const _k = [0, 0, -1]; + // shaders + // precision + const lowp = 0; + const mediump = 1; + const highp = 2; + // in + const pmvMatrix = 1 << 0; + const pMatrix = 1 << 1; + const mvMatrix = 1 << 2; + const nMatrix = 1 << 3; + // out + const color4 = 1 << 0; + const texcoords2 = 1 << 1; + const normal3 = 1 << 2; + const position2 = 1 << 3; + const position3 = 1 << 4; + ext ??= {}; + ext.INFO = INFO; + ext.NONE = NONE; + ext.X = X; + ext.Y = Y; + ext.Z = Z; + ext._X = _X; + ext._Y = _Y; + ext._Z = _Z; + ext.LABELS = LABELS; + ext.SOLID = SOLID; + ext.DOTS = DOTS; + ext.SQUARE = SQUARE; + ext.CIRCLE = CIRCLE; + ext.PROJECTION = PROJECTION; + ext.NEAR = NEAR; + ext.FAR = FAR; + ext.LEFT = LEFT; + ext.RIGHT = RIGHT; + ext.BOTTOM = BOTTOM; + ext.TOP = TOP; + ext.BODY = BODY; + ext.INVISIBLE = INVISIBLE; + ext.VISIBLE = VISIBLE; + ext.SEMIVISIBLE = SEMIVISIBLE; + ext.WORLD = WORLD; + ext.EYE = EYE; + ext.NDC = NDC; + ext.SCREEN = SCREEN; + ext.MODEL = MODEL; + ext.ORIGIN = ORIGIN; + ext.i = i; + ext.j = j; + ext.k = k; + ext._i = _i; + ext._j = _j; + ext._k = _k; + ext.lowp = lowp; + ext.mediump = mediump; + ext.highp = highp; + ext.pmvMatrix = pmvMatrix; + ext.pMatrix = pMatrix; + ext.mvMatrix = mvMatrix; + ext.nMatrix = nMatrix; + ext.color4 = color4; + ext.texcoords2 = texcoords2; + ext.normal3 = normal3; + ext.position2 = position2; + ext.position3 = position3; + return ext; +})(Tree); + + +(function () { + console.log(Tree.INFO); + + // 1. Matrix stuff + + p5.Matrix.prototype.mult3 = function (vector) { + if (this.mat3 === undefined) { + console.error('mult3 only works with mat3'); + return; + } + return new p5.Vector(this.mat3[0] * vector.x + this.mat3[3] * vector.y + this.mat3[6] * vector.z, + this.mat3[1] * vector.x + this.mat3[4] * vector.y + this.mat3[7] * vector.z, + this.mat3[2] * vector.x + this.mat3[5] * vector.y + this.mat3[8] * vector.z); + }; + + p5.Matrix.prototype.mult4 = function (vector) { + return new p5.Vector(...this._mult4([vector.x, vector.y, vector.z, 1])); + }; + + p5.Matrix.prototype._mult4 = function (vec4) { + if (this.mat4 === undefined) { + console.error('_mult4 only works with mat4'); + return; + } + return [this.mat4[0] * vec4[0] + this.mat4[4] * vec4[1] + this.mat4[8] * vec4[2] + this.mat4[12] * vec4[3], + this.mat4[1] * vec4[0] + this.mat4[5] * vec4[1] + this.mat4[9] * vec4[2] + this.mat4[13] * vec4[3], + this.mat4[2] * vec4[0] + this.mat4[6] * vec4[1] + this.mat4[10] * vec4[2] + this.mat4[14] * vec4[3], + this.mat4[3] * vec4[0] + this.mat4[7] * vec4[1] + this.mat4[11] * vec4[2] + this.mat4[15] * vec4[3]]; + }; + + p5.prototype.tMatrix = function (matrix) { + return matrix.copy().transpose(matrix); + } + + p5.prototype.invMatrix = function (matrix) { + return matrix.copy().invert(matrix); + } + + p5.prototype.axbMatrix = function (a, b) { + return a.copy().apply(b); + } + + p5.prototype.iMatrix = function () { + return new p5.Matrix(); + } + + p5.prototype.lMatrix = function () { + return this._renderer.lMatrix(...arguments); + } + + // defaults: from: iMatrix, to: eMatrix + p5.RendererGL.prototype.lMatrix = function ( + { + from = new p5.Matrix(), + to = this.eMatrix() + } = {}) { + return to.copy().invert(to).apply(from); + } + + p5.prototype.dMatrix = function () { + return this._renderer.dMatrix(...arguments); + } + + // defaults: from: iMatrix, to: eMatrix + p5.RendererGL.prototype.dMatrix = function ( + { + from = new p5.Matrix(), + to = this.eMatrix(), + matrix = from.copy().invert(from).apply(to) + } = {}) { + // Note that this transposes mat4 into mat3 + return new p5.Matrix('mat3', [matrix.mat4[0], matrix.mat4[4], matrix.mat4[8], + matrix.mat4[1], matrix.mat4[5], matrix.mat4[9], + matrix.mat4[2], matrix.mat4[6], matrix.mat4[10]]); + } + + p5.prototype.pMatrix = function () { + return this._renderer.pMatrix(...arguments); + } + + p5.RendererGL.prototype.pMatrix = function () { + return this.uPMatrix.copy(); + } + + p5.prototype.mvMatrix = function () { + return this._renderer.mvMatrix(...arguments); + } + + // defaults when mMatrix is defined: vMatrix: this.vMatrix, mMatrix: + // otherwise it returns a copy of the current mvMatrix + p5.RendererGL.prototype.mvMatrix = function ( + { + vMatrix, + mMatrix + } = {}) { + return mMatrix ? (vMatrix ?? this.vMatrix()).copy().apply(mMatrix) : this.uMVMatrix.copy(); + } + + p5.prototype.mMatrix = function () { + return this._renderer.mMatrix(...arguments); + } + + // defaults: eMatrix: this.eMatrix, mvMatrix: this.mvMatrix + p5.RendererGL.prototype.mMatrix = function ( + { + eMatrix = this.eMatrix(), + mvMatrix = this.mvMatrix() + } = {}) { + return eMatrix.copy().apply(mvMatrix); + } + + p5.prototype.nMatrix = function () { + return this._renderer.nMatrix(...arguments); + } + + p5.RendererGL.prototype.nMatrix = function ({ + vMatrix, + mMatrix, + mvMatrix = this.mvMatrix({ mMatrix: mMatrix, vMatrix: vMatrix }) + } = {}) { + return new p5.Matrix('mat3').inverseTranspose(mvMatrix); + } + + // TODO check where to replace vMatrix for: + // this._curCamera.cameraMatrix + + p5.prototype.vMatrix = function () { + return this._renderer.vMatrix(...arguments); + } + + p5.RendererGL.prototype.vMatrix = function () { + return this._curCamera.vMatrix(); + } + + p5.Camera.prototype.vMatrix = function () { + return this.cameraMatrix.copy(); + } + + p5.prototype.eMatrix = function () { + return this._renderer.eMatrix(...arguments); + } + + p5.RendererGL.prototype.eMatrix = function () { + return this._curCamera.eMatrix(); + } + + p5.Camera.prototype.eMatrix = function () { + return this.cameraMatrix.copy().invert(this.cameraMatrix); + } + + p5.prototype.pmvMatrix = function () { + return this._renderer.pmvMatrix(...arguments); + } + + p5.RendererGL.prototype.pmvMatrix = function ( + { + pMatrix = this.uPMatrix, + vMatrix, + mMatrix, + mvMatrix = this.mvMatrix({ mMatrix: mMatrix, vMatrix: vMatrix }) + } = {}) { + return pMatrix.copy().apply(mvMatrix); + } + + p5.prototype.pvMatrix = function () { + return this._renderer.pvMatrix(...arguments); + } + + // defaults: pMatrix: this.pMatrix, vMatrix: this.vMatrix + p5.RendererGL.prototype.pvMatrix = function ( + { + pMatrix = this.uPMatrix, + vMatrix = this._curCamera.cameraMatrix + } = {}) { + return pMatrix.copy().apply(vMatrix); + } + + p5.prototype.pvInvMatrix = function () { + return this._renderer.pvInvMatrix(...arguments); + } + + p5.RendererGL.prototype.pvInvMatrix = function ( + { + pMatrix, + vMatrix, + pvMatrix + } = {}) { + let matrix = pvMatrix ? pvMatrix.copy() : this.pvMatrix({ pMatrix: pMatrix, vMatrix: vMatrix }); + return matrix.invert(matrix); + } + + p5.prototype._isOrtho = function () { + return this._renderer._isOrtho(...arguments); + } + + p5.RendererGL.prototype._isOrtho = function () { + return this.uPMatrix._isOrtho(); + } + + p5.Matrix.prototype._isOrtho = function () { + return this.mat4[15] != 0; + } + + p5.prototype.nPlane = function () { + return this._renderer.nPlane(...arguments); + } + + p5.RendererGL.prototype.nPlane = function () { + return this.uPMatrix.nPlane(); + } + + p5.Matrix.prototype.nPlane = function () { + return this.mat4[15] == 0 ? this.mat4[14] / (this.mat4[10] - 1) : + (1 + this.mat4[14]) / this.mat4[10]; + } + + p5.prototype.fPlane = function () { + return this._renderer.fPlane(...arguments); + } + + p5.RendererGL.prototype.fPlane = function () { + return this.uPMatrix.fPlane(); + } + + p5.Matrix.prototype.fPlane = function () { + return this.mat4[15] == 0 ? this.mat4[14] / (1 + this.mat4[10]) : + (this.mat4[14] - 1) / this.mat4[10]; + } + + p5.prototype.lPlane = function () { + return this._renderer.lPlane(...arguments); + } + + p5.RendererGL.prototype.lPlane = function () { + return this.uPMatrix.lPlane(); + } + + p5.Matrix.prototype.lPlane = function () { + return this.mat4[15] == 1 ? -(1 + this.mat4[12]) / this.mat4[0] : + this.nPlane() * (this.mat4[8] - 1) / this.mat4[0]; + } + + p5.prototype.rPlane = function () { + return this._renderer.rPlane(...arguments); + } + + p5.RendererGL.prototype.rPlane = function () { + return this.uPMatrix.rPlane(); + } + + p5.Matrix.prototype.rPlane = function () { + return this.mat4[15] == 1 ? (1 - this.mat4[12]) / this.mat4[0] : + this.nPlane() * (1 + this.mat4[8]) / this.mat4[0]; + } + + p5.prototype.tPlane = function () { + return this._renderer.tPlane(...arguments); + } + + p5.RendererGL.prototype.tPlane = function () { + return this.uPMatrix.tPlane(); + } + + p5.Matrix.prototype.tPlane = function () { + // note that inverted values are returned if the projection + // matrix was set with @function frustum. + return this.mat4[15] == 1 ? (this.mat4[13] - 1) / this.mat4[5] : + this.nPlane() * (this.mat4[9] - 1) / this.mat4[5]; + } + + p5.prototype.bPlane = function () { + return this._renderer.bPlane(...arguments); + } + + p5.RendererGL.prototype.bPlane = function () { + return this.uPMatrix.bPlane(); + } + + p5.Matrix.prototype.bPlane = function () { + // note that inverted values are returned if the projection + // matrix was set with @function frustum. + return this.mat4[15] == 1 ? (1 + this.mat4[13]) / this.mat4[5] : + this.nPlane() * (1 + this.mat4[9]) / this.mat4[5]; + } + + p5.prototype.fov = function () { + return this._renderer.fov(...arguments); + } + + p5.RendererGL.prototype.fov = function () { + return this.uPMatrix.fov(); + } + + p5.Matrix.prototype.fov = function () { + if (this.mat4[15] != 0) { + console.error('fov only works for a perspective projection'); + return; + } + return Math.abs(2 * Math.atan(1 / this.mat4[5])); + } + + p5.prototype.hfov = function () { + return this._renderer.hfov(...arguments); + } + + p5.RendererGL.prototype.hfov = function () { + return this.uPMatrix.hfov(); + } + + p5.Matrix.prototype.hfov = function () { + if (this.mat4[15] != 0) { + console.error('hfov only works for a perspective projection'); + return; + } + return Math.abs(2 * Math.atan(1 / this.mat4[0])); + } + + // 2. Space transformations + + p5.prototype.beginHUD = function () { + if (this._renderer instanceof p5.RendererGL) { + this._renderer.beginHUD(...arguments); + } + } + + p5.RendererGL.prototype.beginHUD = function () { + this.mv = this.mvMatrix(); + this.p = this.pMatrix(); + this._rendererState = this.push(); + let gl = this.drawingContext; + gl.flush(); + gl.disable(gl.DEPTH_TEST); + this.resetMatrix(); + let z = Number.MAX_VALUE; + this._curCamera.ortho(0, this.width, -this.height, 0, -z, z); + } + + p5.prototype.endHUD = function () { + if (this._renderer instanceof p5.RendererGL) { + this._renderer.endHUD(...arguments); + } + } + + p5.RendererGL.prototype.endHUD = function () { + let gl = this.drawingContext; + gl.flush(); + gl.enable(gl.DEPTH_TEST); + this.pop(this._rendererState); + this.uPMatrix.set(this.p); + this.uMVMatrix.set(this.mv); + } + + // 2.1 Points + + // NDC stuff needs testing + + p5.prototype._map = function () { + return this._renderer._map(...arguments); + } + + p5.RendererGL.prototype._map = function (n, start1, stop1, start2, stop2) { + return (n - start1) / (stop1 - start1) * (stop2 - start2) + start2; + } + + p5.prototype.treeLocation = function () { + return this._renderer.treeLocation(...arguments); + } + + /** + * Converts locations (i.e., points) from one space into another. + * @param {p5.Vector} vector location to be converted. + * @param {p5.Matrix|String} from source space: either a global + * transform matrix or Tree.WORLD, Tree.EYE, + * Tree.SCREEN, Tree.NDC or Tree.MODEL. + * @param {p5.Matrix|String} to target space: either a global + * transform matrix or Tree.WORLD, Tree.EYE, + * Tree.SCREEN, Tree.NDC or Tree.MODEL. + * @param {p5.Matrix} pMatrix projection matrix. + * @param {p5.Matrix} vMatrix view matrix. + * @param {p5.Matrix} pvMatrix projection times view matrix. + * @param {p5.Matrix} pvInvMatrix (projection times view matrix)^-1. + */ + p5.RendererGL.prototype.treeLocation = function () { + return arguments.length === 1 & arguments[0] instanceof Object ? this._treeLocation(Tree.ORIGIN, arguments[0]) : + this._treeLocation(...arguments); + } + + p5.prototype._treeLocation = function () { + return this._renderer._treeLocation(...arguments); + } + + p5.RendererGL.prototype._treeLocation = function (vector = Tree.ORIGIN, + { + from = Tree.EYE, + to = Tree.WORLD, + pMatrix, + vMatrix, + eMatrix, + pvMatrix, + pvInvMatrix + } = {}) { + if (Array.isArray(vector)) { + vector = new p5.Vector(vector[0] ?? 0, vector[1] ?? 0, vector[2] ?? 0); + } + if (from == Tree.MODEL) { + from = this.mMatrix({ eMatrix: eMatrix }); + } + if (to == Tree.MODEL) { + to = this.mMatrix({ eMatrix: eMatrix }); + } + if ((from == Tree.WORLD) && (to == Tree.SCREEN)) { + return this._screenLocation({ vector: vector, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + } + if ((from == Tree.SCREEN) && (to == Tree.WORLD)) { + return this._location({ vector: vector, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix, pvInvMatrix: pvInvMatrix }); + } + if (from == Tree.SCREEN && to == Tree.NDC) { + return this._screenToNDCLocation(vector); + } + if (from == Tree.NDC && to == Tree.SCREEN) { + return this._ndcToScreenLocation(vector); + } + if (from == Tree.WORLD && to == Tree.NDC) { + return this._screenToNDCLocation(this._screenLocation({ vector: vector, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix })); + } + if (from == Tree.NDC && to == Tree.WORLD) { + return this._location({ vector: this._ndcToScreenLocation(vector), pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix, pvInvMatrix: pvInvMatrix }); + } + if (from == Tree.NDC && (to instanceof p5.Matrix || to == Tree.EYE)) { + return (to == Tree.EYE ? (vMatrix ?? this.vMatrix()) : to.copy().invert(to)).mult4(this._location({ vector: this._ndcToScreenLocation(vector), pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix, pvInvMatrix: pvInvMatrix })); + } + if ((from instanceof p5.Matrix || from == Tree.EYE) && to == Tree.NDC) { + return this._screenToNDCLocation(this._screenLocation({ vector: (from == Tree.EYE ? (eMatrix ?? this.eMatrix()) : from).mult4(vector), pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix })); + } + if (from == Tree.WORLD && (to instanceof p5.Matrix || to == Tree.EYE)) { + return (to == Tree.EYE ? (vMatrix ?? this.vMatrix()) : to.copy().invert(to)).mult4(vector); + } + if ((from instanceof p5.Matrix || from == Tree.EYE) && to == Tree.WORLD) { + return (from == Tree.EYE ? (eMatrix ?? this.eMatrix()) : from).mult4(vector); + } + if (from instanceof p5.Matrix && to instanceof p5.Matrix) { + return this.lMatrix({ from: from, to: to }).mult4(vector); + } + if (from == Tree.SCREEN && (to instanceof p5.Matrix || to == Tree.EYE)) { + return (to == Tree.EYE ? (vMatrix ?? this.vMatrix()) : to.copy().invert(to)).mult4(this._location({ vector: vector, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix, pvInvMatrix: pvInvMatrix })); + } + if ((from instanceof p5.Matrix || from == Tree.EYE) && to == Tree.SCREEN) { + return this._screenLocation({ vector: (from == Tree.EYE ? (eMatrix ?? this.eMatrix()) : from).mult4(vector), pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + } + console.error('couldn\'t parse your treeLocation query!'); + return vector; + } + + p5.RendererGL.prototype._ndcToScreenLocation = function (vector) { + return new p5.Vector(this._map(vector.x, -1, 1, 0, this.width), + this._map(vector.y, -1, 1, 0, this.height), + this._map(vector.z, -1, 1, 0, 1)); + } + + p5.RendererGL.prototype._screenToNDCLocation = function (vector) { + return new p5.Vector(this._map(vector.x, 0, this.width, -1, 1), + this._map(vector.y, 0, this.height, -1, 1), + this._map(vector.z, 0, 1, -1, 1)); + } + + p5.RendererGL.prototype._screenLocation = function ( + { + vector = new p5.Vector(0, 0, 0.5), + pMatrix, + vMatrix, + pvMatrix = this.pvMatrix({ pMatrix: pMatrix, vMatrix: vMatrix }) + } = {}) { + let target = pvMatrix._mult4([vector.x, vector.y, vector.z, 1]); + if (target[3] == 0) { + console.error('screenLocation broken. Check your pvMatrix!'); + return; + } + let viewport = [0, this.height, this.width, -this.height]; + // ndc, but y is inverted + target[0] /= target[3]; + target[1] /= target[3]; + target[2] /= target[3]; + // Map x, y and z to range 0-1 + target[0] = target[0] * 0.5 + 0.5; + target[1] = target[1] * 0.5 + 0.5; + target[2] = target[2] * 0.5 + 0.5; + // Map x,y to viewport + target[0] = target[0] * viewport[2] + viewport[0]; + target[1] = target[1] * viewport[3] + viewport[1]; + return new p5.Vector(target[0], target[1], target[2]); + } + + p5.RendererGL.prototype._location = function ( + { + vector = new p5.Vector(this.width / 2, this.height / 2, 0.5), + pMatrix, + vMatrix, + pvMatrix, + pvInvMatrix = this.pvInvMatrix({ pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }) + } = {}) { + let viewport = [0, this.height, this.width, -this.height]; + let source = [vector.x, vector.y, vector.z, 1]; + // Map x and y from window coordinates + source[0] = (source[0] - viewport[0]) / viewport[2]; + source[1] = (source[1] - viewport[1]) / viewport[3]; + // Map to range -1 to 1 + source[0] = source[0] * 2 - 1; + source[1] = source[1] * 2 - 1; + source[2] = source[2] * 2 - 1; + let target = pvInvMatrix._mult4(source); + if (target[3] == 0) { + console.error('location broken. Check your pvInvMatrix!'); + return; + } + target[0] /= target[3]; + target[1] /= target[3]; + target[2] /= target[3]; + return new p5.Vector(target[0], target[1], target[2]); + } + + // 2.2. Vectors + + // NDC stuff needs testing + + p5.prototype.treeDisplacement = function () { + return this._renderer.treeDisplacement(...arguments); + } + + /** + * Converts displacements (i.e., vectors) from one space into another. + * @param {p5.Vector} vector location to be converted. + * @param {p5.Matrix|String} from source space: either a global + * transform matrix or Tree.WORLD, Tree.EYE, + * Tree.SCREEN, Tree.NDC or Tree.MODEL. + * @param {p5.Matrix|String} to target space: either a global + * transform matrix or Tree.WORLD, Tree.EYE, + * Tree.SCREEN, Tree.NDC or Tree.MODEL. + * @param {p5.Matrix} pMatrix projection matrix. + * @param {p5.Matrix} vMatrix view matrix. + * @param {p5.Matrix} pvMatrix projection times view matrix. + * @param {p5.Matrix} pvInvMatrix (projection times view matrix)^-1. + */ + p5.RendererGL.prototype.treeDisplacement = function () { + return arguments.length === 1 & arguments[0] instanceof Object ? this._treeDisplacement(Tree._k, arguments[0]) : + this._treeDisplacement(...arguments); + } + + p5.prototype._treeDisplacement = function () { + return this._renderer._treeDisplacement(...arguments); + } + + p5.RendererGL.prototype._treeDisplacement = function (vector = Tree._k, + { + from = Tree.EYE, + to = Tree.WORLD, + vMatrix, + eMatrix, + pMatrix + } = {}) { + if (Array.isArray(vector)) { + vector = new p5.Vector(vector[0] ?? 0, vector[1] ?? 0, vector[2] ?? 0); + } + if (from == Tree.MODEL) { + from = this.mMatrix({ eMatrix: eMatrix }); + } + if (to == Tree.MODEL) { + to = this.mMatrix({ eMatrix: eMatrix }); + } + if ((from == Tree.WORLD) && (to == Tree.SCREEN)) { + return this._worldToScreenDisplacement(vector, pMatrix); + } + if ((from == Tree.SCREEN) && (to == Tree.WORLD)) { + return this._screenToWorldDisplacement(vector, pMatrix); + } + if (from == Tree.SCREEN && to == Tree.NDC) { + return this._screenToNDCDisplacement(vector); + } + if (from == Tree.NDC && to == Tree.SCREEN) { + return this._ndcToScreenDisplacement(vector); + } + if (from == Tree.WORLD && to == Tree.NDC) { + return this._screenToNDCDisplacement(this._worldToScreenDisplacement(vector, pMatrix)); + } + if (from == Tree.NDC && to == Tree.WORLD) { + return this._screenToWorldDisplacement(this._ndcToScreenDisplacement(vector), pMatrix); + } + if (from == Tree.NDC && to == Tree.EYE) { + return this.dMatrix({ matrix: eMatrix ?? this.eMatrix() }).mult3(this._screenToWorldDisplacement(this._ndcToScreenDisplacement(vector), pMatrix)); + } + if (from == Tree.EYE && to == Tree.NDC) { + return this._screenToNDCDisplacement(this._worldToScreenDisplacement(this.dMatrix({ matrix: vMatrix ?? this.vMatrix() }).mult3(vector), pMatrix)); + } + if (from == Tree.SCREEN && to instanceof p5.Matrix) { + return this.dMatrix({ matrix: to }).mult3(this._screenToWorldDisplacement(vector, pMatrix)); + } + if (from instanceof p5.Matrix && to == Tree.SCREEN) { + return this._worldToScreenDisplacement(this.dMatrix({ matrix: from.copy().invert(from) }).mult3(vector), pMatrix); + } + if (from instanceof p5.Matrix && to instanceof p5.Matrix) { + return this.dMatrix({ from: from, to: to }).mult3(vector); + } + // all cases below kept for efficiency but they all may + // be simply expressed in terms of the previous case, by: + // Tree.EYE -> eMatrix() + // Tree.WORLD -> iMatrix() + if (from == Tree.EYE && to == Tree.WORLD) { + return this.dMatrix({ matrix: vMatrix ?? this.vMatrix() }).mult3(vector); + } + if (from == Tree.WORLD && to == Tree.EYE) { + return this.dMatrix({ matrix: eMatrix ?? this.eMatrix() }).mult3(vector); + } + if (from == Tree.EYE && to == Tree.SCREEN) { + return this._worldToScreenDisplacement(this.dMatrix({ matrix: vMatrix ?? this.vMatrix() }).mult3(vector), pMatrix); + } + if (from == Tree.SCREEN && to == Tree.EYE) { + return this.dMatrix({ matrix: eMatrix ?? this.eMatrix() }).mult3(this._screenToWorldDisplacement(vector, pMatrix)); + } + if (from == Tree.EYE && to instanceof p5.Matrix) { + return this.dMatrix({ matrix: (vMatrix ?? this.vMatrix()).apply(to) }).mult3(vector); + } + if (from instanceof p5.Matrix && to == Tree.EYE) { + return this.dMatrix({ matrix: from.copy().invert(from).apply(eMatrix ?? this.eMatrix()) }).mult3(vector); + } + if (from == Tree.WORLD && to instanceof p5.Matrix) { + return this.dMatrix({ matrix: to }).mult3(vector); + } + if (from instanceof p5.Matrix && to == Tree.WORLD) { + return this.dMatrix({ matrix: from.copy().invert(from) }).mult3(vector); + } + console.error('couldn\'t parse your treeDisplacement query!'); + return vector; + } + + p5.RendererGL.prototype._worldToScreenDisplacement = function (vector, pMatrix = this.uPMatrix) { + let eyeVector = this._treeDisplacement(vector, { from: Tree.WORLD, to: Tree.EYE }); + let dx = eyeVector.x; + let dy = eyeVector.y; + let perspective = pMatrix.mat4[15] == 0; + if (perspective) { + let position = new p5.Vector(); + let k = Math.abs(this._treeLocation(position, { from: Tree.WORLD, to: Tree.EYE }).z * Math.tan(this.fov(pMatrix) / 2)); + dx /= 2 * k / this.height; + dy /= 2 * k / this.height; + } + let dz = eyeVector.z; + // sign is inverted + dz /= (pMatrix.nPlane() - pMatrix.fPlane()) / (perspective ? Math.tan(this.fov(pMatrix) / 2) : Math.abs(pMatrix.rPlane() - pMatrix.lPlane()) / this.width); + return new p5.Vector(dx, dy, dz); + } + + p5.RendererGL.prototype._screenToWorldDisplacement = function (vector, pMatrix = this.uPMatrix) { + let dx = vector.x; + let dy = vector.y; + // Scale to fit the screen relative vector displacement + let perspective = pMatrix.mat4[15] == 0; + if (perspective) { + let position = new p5.Vector(); + let k = Math.abs(this._treeLocation(position, { from: Tree.WORLD, to: Tree.EYE }).z * Math.tan(this.fov(pMatrix) / 2)); + dx *= 2 * k / this.height; + dy *= 2 * k / this.height; + } + let dz = vector.z; + dz *= (pMatrix.nPlane() - pMatrix.fPlane()) / (perspective ? Math.tan(this.fov(pMatrix) / 2) : Math.abs(pMatrix.rPlane() - pMatrix.lPlane()) / this.width); + let eyeVector = new p5.Vector(dx, dy, dz); + return this._treeDisplacement(eyeVector, { from: Tree.EYE, to: Tree.WORLD }); + } + + p5.RendererGL.prototype._ndcToScreenDisplacement = function (vector) { + return new p5.Vector(this.width * vector.x / 2, this.height * vector.y / 2, vector.z / 2); + } + + p5.RendererGL.prototype._screenToNDCDisplacement = function (vector) { + return new p5.Vector(2 * vector.x / this.width, 2 * vector.y / this.height, 2 * vector.z); + } + + // 3. Shader utilities + + p5.prototype.readShader = function (fragFilename, { + precision, + matrices, + varyings + } = {}) { + let shader = new p5.Shader(); + this._coupledWith = fragFilename.substring(fragFilename.lastIndexOf('/') + 1); + shader._vertSrc = this.parseVertexShader({ precision: precision, matrices: matrices, varyings: varyings, _specs: false }); + this._coupledWith = undefined; + this.loadStrings( + fragFilename, + result => { + shader._fragSrc = result.join('\n') + } + ); + return shader; + } + + p5.prototype.makeShader = function (fragSrc, { + precision, + matrices, + varyings + } = {}) { + let shader = new p5.Shader(); + this._coupledWith = 'the fragment shader provided as param in makeShader()'; + shader._vertSrc = this.parseVertexShader({ precision: precision, matrices: matrices, varyings: varyings, _specs: false }); + this._coupledWith = undefined; + shader._fragSrc = fragSrc; + return shader; + } + + p5.prototype.parseVertexShader = function ({ + precision = Tree.mediump, + matrices = Tree.pmvMatrix, + varyings = Tree.color4 | Tree.texcoords2, + _specs = true + } = {}) { + let floatPrecision = `precision ${precision === Tree.highp ? 'highp' : `${precision === Tree.mediump ? 'mediump' : 'lowp'}`} float;` + let color4 = ~(varyings | ~Tree.color4) === 0; + let texcoords2 = ~(varyings | ~Tree.texcoords2) === 0; + let normal3 = ~(varyings | ~Tree.normal3) === 0; + let position2 = ~(varyings | ~Tree.position2) === 0; + let position3 = ~(varyings | ~Tree.position3) === 0; + let pmv = ~(matrices | ~Tree.pmvMatrix) === 0; + let p = ~(matrices | ~Tree.pMatrix) === 0; + let mv = ~(matrices | ~Tree.mvMatrix) === 0; + let n = (~(matrices | ~Tree.nMatrix) === 0) || normal3; + const target = `gl_Position =${pmv ? ' uModelViewProjectionMatrix * ' : `${p && mv ? ' uProjectionMatrix * uModelViewMatrix *' : ''} `}vec4(aPosition, 1.0)`; + let vertexShader = ` +${floatPrecision} +attribute vec3 aPosition; +${color4 ? 'attribute vec4 aVertexColor;' : ''} +${texcoords2 ? 'attribute vec2 aTexCoord;' : ''} +${normal3 ? 'attribute vec3 aNormal;' : ''} +${pmv ? 'uniform mat4 uModelViewProjectionMatrix;' : ''} +${p ? 'uniform mat4 uProjectionMatrix;' : ''} +${mv ? 'uniform mat4 uModelViewMatrix;' : ''} +${n ? 'uniform mat3 uNormalMatrix;' : ''} +${color4 ? 'varying vec4 color4;' : ''} +${texcoords2 ? 'varying vec2 texcoords2;' : ''} +${normal3 ? 'varying vec3 normal3;' : ''} +${position2 ? 'varying vec2 position2;' : ''} +${position3 ? 'varying vec3 position3;' : ''} +void main() { + ${color4 ? 'color4 = aVertexColor;' : ''} + ${texcoords2 ? 'texcoords2 = aTexCoord;' : ''} + ${normal3 ? 'normal3 = normalize(uNormalMatrix * aNormal);' : ''} + ${position2 ? 'position2 = vec4(aPosition, 1.0).xy;' : ''} + ${position3 ? 'position3 = vec4(aPosition, 1.0).xyz;' : ''} + ${target}; +} +`; + let advice = ` +/* +${this._coupledWith ? 'Vertex shader code to be coupled with ' + this._coupledWith : ''} +Generated with treegl version ${Tree.INFO.VERSION} +${_specs ? ` +Feel free to copy, paste, edit and save it. +Refer to createShader (https://p5js.org/reference/#/p5/createShader), +loadShader (https://p5js.org/reference/#/p5/loadShader), readShader +and makeShader (https://github.com/VisualComputing/p5.treegl#handling), +for details.` : ''} +*/ +`; + let result = advice + vertexShader; + result = result.split(/\r?\n/) + .filter(line => line.trim() !== '') + .join("\n"); + console.log(result); + return result; + } + + p5.prototype.emitMousePosition = function (shader, uniform = 'u_mouse') { + shader.setUniform(uniform, [this.mouseX * pixelDensity(), (this.height - this.mouseY) * pixelDensity()]); + } + + p5.prototype.emitPointerPosition = function () { + this._renderer.emitPointerPosition(...arguments); + } + + p5.RendererGL.prototype.emitPointerPosition = function (shader, pointerX, pointerY, uniform = 'u_pointer') { + shader.setUniform(uniform, [pointerX * pixelDensity(), (this.height - pointerY) * pixelDensity()]); + } + + p5.prototype.emitResolution = function () { + this._renderer.emitResolution(...arguments); + } + + p5.RendererGL.prototype.emitResolution = function (shader, uniform = 'u_resolution') { + shader.setUniform(uniform, [this.width * pixelDensity(), this.height * pixelDensity()]); + } + + p5.prototype.emitTexOffset = function (shader, image, uniform = 'u_texoffset') { + shader.setUniform(uniform, [1 / image.width, 1 / image.height]); + } + + // 4. Utility functions + + p5.prototype.pixelRatio = function () { + return this._renderer.pixelRatio(...arguments); + } + + /** + * Returns the world to pixel ratio units at given world location. + * A line of n * pixelRatio(location) world units will be projected + * with a length of n pixels on screen. + * @param {p5.Vector | Array} location world location reference + */ + p5.RendererGL.prototype.pixelRatio = function (location) { + return this._isOrtho() ? Math.abs(this.tPlane() - this.bPlane()) / this.height : + 2 * Math.abs((this._treeLocation(location, { from: Tree.WORLD, to: Tree.EYE, vMatrix: this._curCamera.cameraMatrix })).z) * Math.tan(this.fov() / 2) / this.height; + } + + p5.prototype.visibility = function () { + return this._renderer.visibility(...arguments); + } + + /** + * Returns object visibility (i.e, lies within the eye bounds) + * either Tree.VISIBLE, Tree.INVISIBLE, or Tree.SEMIVISIBLE. + * Object may be either a point, a sphere or an axis-aligned box. + * @param {p5.Vector | Array} corner1 box corner1, use it with corner2. + * @param {p5.Vector | Array} corner2 box corner2, use it with corner1. + * @param {p5.Vector | Array} center sphere (or point) center. + * @param {Number} radius sphere radius. + * @param {Array} bounds frustum equations 6x4 matrix. + */ + p5.RendererGL.prototype.visibility = function ({ + corner1, + corner2, + center, + radius, + bounds = this.bounds() + } = {}) { + return center ? radius ? this._ballVisibility(center, radius, bounds) : this._pointVisibility(center, bounds) + : corner1 && corner2 ? this._boxVisibility(corner1, corner2, bounds) : console.error('couldn\'t parse your visibility query!'); + } + + p5.RendererGL.prototype._pointVisibility = function (point, bounds = this.bounds()) { + for (const key in bounds) { + let d = this.distanceToBound(point, key, bounds); + if (d > 0) { + return Tree.INVISIBLE; + } + if (d === 0) { + return Tree.SEMIVISIBLE; + } + } + return Tree.VISIBLE; + } + + p5.RendererGL.prototype._ballVisibility = function (center, radius, bounds = this.bounds()) { + let allInForAllPlanes = true; + for (const key in bounds) { + let d = this.distanceToBound(center, key, bounds); + if (d > radius) { + return Tree.INVISIBLE; + } + if ((d > 0) || (-d < radius)) { + allInForAllPlanes = false; + } + } + if (allInForAllPlanes) { + return Tree.VISIBLE; + } + return Tree.SEMIVISIBLE; + } + + p5.RendererGL.prototype._boxVisibility = function (corner1, corner2, bounds = this.bounds()) { + if (Array.isArray(corner1)) { + corner1 = new p5.Vector(corner1[0] ?? 0, corner1[1] ?? 0, corner1[2] ?? 0); + } + if (Array.isArray(corner2)) { + corner2 = new p5.Vector(corner2[0] ?? 0, corner2[1] ?? 0, corner2[2] ?? 0); + } + let allInForAllPlanes = true; + for (const key in bounds) { + let allOut = true; + for (let c = 0; c < 8; ++c) { + let pos = new p5.Vector(((c & 4) != 0) ? corner1.x : corner2.x, ((c & 2) != 0) ? corner1.y : corner2.y, + ((c & 1) != 0) ? corner1.z : corner2.z); + if (this.distanceToBound(pos, key, bounds) > 0) { + allInForAllPlanes = false; + } + else { + allOut = false; + } + } + // The eight points are on the outside side of this plane + if (allOut) { + return Tree.INVISIBLE; + } + } + if (allInForAllPlanes) { + return Tree.VISIBLE; + } + // Too conservative, but tangent cases are too expensive to detect + return Tree.SEMIVISIBLE; + } + + p5.prototype.bounds = function () { + return this._renderer.bounds(...arguments); + } + + /** + * Returns the 6 plane equations of the eye frustum bounds defined + * in the world coordinate system encoded as an object literal + * having 'Tree.LEFT' (left plane), 'Tree.RIGHT' (right plane), + * 'Tree.NEAR' (near plane), 'Tree.FAR' (far plane) 'Tree.TOP' + * (top plane) and 'Tree.BOTTOM' (bottom plane) keys. + * Each key holds a plane equation of the form: + * a*x + b*y + c*z + d = 0, where a, b, c and d are the 4 + * keys of each object literal. + */ + p5.RendererGL.prototype.bounds = function () { + let normals = Array(6); + let distances = Array(6); + // Computed once and for all + // TODO experimental: no need to normalize + let pos = this._treeLocation([0, 0, 0], { from: Tree.EYE, to: Tree.WORLD }); + let viewDir = this._treeDisplacement([0, 0, -1], { from: Tree.EYE, to: Tree.WORLD }); + // same as: let viewDir = this.treeDisplacement(); + let up = this._treeDisplacement([0, 1, 0], { from: Tree.EYE, to: Tree.WORLD }); + let right = this._treeDisplacement([1, 0, 0], { from: Tree.EYE, to: Tree.WORLD }); + let posViewDir = p5.Vector.dot(pos, viewDir); + if (this._isOrtho()) { + normals[0] = p5.Vector.mult(right, -1); + normals[1] = right; + normals[4] = up; + normals[5] = p5.Vector.mult(up, -1); + let wh0 = Math.abs(this.rPlane() - this.lPlane()) / 2; + let wh1 = Math.abs(this.tPlane() - this.bPlane()) / 2; + distances[0] = p5.Vector.dot(p5.Vector.sub(pos, p5.Vector.mult(right, wh0)), normals[0]); + distances[1] = p5.Vector.dot(p5.Vector.add(pos, p5.Vector.mult(right, wh0)), normals[1]); + distances[4] = p5.Vector.dot(p5.Vector.add(pos, p5.Vector.mult(up, wh1)), normals[4]); + distances[5] = p5.Vector.dot(p5.Vector.sub(pos, p5.Vector.mult(up, wh1)), normals[5]); + } + else { + let hhfov = this.hfov() / 2; + let chhfov = Math.cos(hhfov); + let shhfov = Math.sin(hhfov); + normals[0] = p5.Vector.mult(viewDir, -shhfov); + normals[1] = p5.Vector.add(normals[0], p5.Vector.mult(right, chhfov)); + normals[0] = p5.Vector.add(normals[0], p5.Vector.mult(right, -chhfov)); + normals[2] = p5.Vector.mult(viewDir, -1); + normals[3] = viewDir; + let hfov = this.fov() / 2; + let chfov = Math.cos(hfov); + let shfov = Math.sin(hfov); + normals[4] = p5.Vector.mult(viewDir, -shfov); + normals[5] = p5.Vector.add(normals[4], p5.Vector.mult(up, -chfov)); + normals[4] = p5.Vector.add(normals[4], p5.Vector.mult(up, chfov)); + for (let i = 0; i < 2; ++i) { + distances[i] = p5.Vector.dot(pos, normals[i]); + } + for (let j = 4; j < 6; ++j) { + distances[j] = p5.Vector.dot(pos, normals[j]); + } + // Natural equations are: + // dist[0,1,4,5] = pos * normal[0,1,4,5]; + // dist[2] = (pos + zNear() * viewDir) * normal[2]; + // dist[3] = (pos + zFar() * viewDir) * normal[3]; + // 2 times less computations using expanded/merged equations. Dir vectors + // are normalized. + let posRightCosHH = chhfov * p5.Vector.dot(pos, right); + distances[0] = -shhfov * posViewDir; + distances[1] = distances[0] + posRightCosHH; + distances[0] = distances[0] - posRightCosHH; + let posUpCosH = chfov * p5.Vector.dot(pos, up); + distances[4] = -shfov * posViewDir; + distances[5] = distances[4] - posUpCosH; + distances[4] = distances[4] + posUpCosH; + } + // Front and far planes are identical for both camera types. + normals[2] = p5.Vector.mult(viewDir, -1); + normals[3] = viewDir; + distances[2] = -posViewDir - this.nPlane(); + distances[3] = posViewDir + this.fPlane(); + let bounds = {}; + bounds[Tree.LEFT] = { a: normals[0].x, b: normals[0].y, c: normals[0].z, d: distances[0] }; + bounds[Tree.RIGHT] = { a: normals[1].x, b: normals[1].y, c: normals[1].z, d: distances[1] }; + bounds[Tree.NEAR] = { a: normals[2].x, b: normals[2].y, c: normals[2].z, d: distances[2] }; + bounds[Tree.FAR] = { a: normals[3].x, b: normals[3].y, c: normals[3].z, d: distances[3] }; + bounds[Tree.TOP] = { a: normals[4].x, b: normals[4].y, c: normals[4].z, d: distances[4] }; + bounds[Tree.BOTTOM] = { a: normals[5].x, b: normals[5].y, c: normals[5].z, d: distances[5] }; + return bounds; + } + + p5.prototype.distanceToBound = function () { + return this._renderer.distanceToBound(...arguments); + } + + /** + * Returns the signed distance between location and the frustum plane defined + * by bounds and key which may be either Tree.LEFT, Tree.RIGHT, Tree.BOTTOM, + * Tree.TOP, Tree.NEAR or Tree.FAR. The distance is negative if the point lies + * in the planes's bounding halfspace, and positive otherwise. + */ + p5.RendererGL.prototype.distanceToBound = function (location, key, bounds = this.bounds()) { + if (Array.isArray(location)) { + location = new p5.Vector(location[0] ?? 0, location[1] ?? 0, location[2] ?? 0); + } + return p5.Vector.dot(location, new p5.Vector(bounds[key].a, bounds[key].b, bounds[key].c)) - bounds[key].d; + } + + p5.prototype.mousePicking = function ({ + mMatrix = this.mMatrix(), + x, + y, + size = 50, + shape = Tree.CIRCLE, + eMatrix, + pMatrix, + vMatrix, + pvMatrix + } = {}) { + return this.pointerPicking(this.mouseX, this.mouseY, { mMatrix: mMatrix, x: x, y: y, size: size, shape: shape, eMatrix: eMatrix, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + } + + p5.prototype.pointerPicking = function () { + return this._renderer.pointerPicking(...arguments); + } + + /** + * Returns true if pointer is close enough to pointerX, pointerY screen location. + * @param {p5.Matrix} mMatrix model space matrix origin to compute (x, y) from. + * @param {Number} x screen x coordinate. Default is width / 2. + * @param {Number} y screen y coordinate. Default is height / 2. + * @param {Number} size bullseye diameter. Default is 50. + * @param {Number} shape either Tree.CIRCLE, Tree.SQUARE or Tree.PROJECTION. Default is Tree.CIRCLE. + */ + p5.RendererGL.prototype.pointerPicking = function (pointerX, pointerY, { + mMatrix = this.mMatrix(), + x, + y, + size = 50, + shape = Tree.CIRCLE, + eMatrix, + pMatrix, + vMatrix, + pvMatrix + } = {}) { + if (!(x && y)) { + let screenLocation = this.treeLocation({ from: mMatrix, to: Tree.SCREEN, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + x = screenLocation.x; + y = screenLocation.y; + size = size / this.pixelRatio(this.treeLocation({ from: mMatrix, to: Tree.WORLD, eMatrix: eMatrix })); + } + // TODO implement webgl picking here using a switch statement: Tree.CIRCLE, Tree.SQUARE, Tree.PROJECTION + let radius = size / 2; + return shape === Tree.CIRCLE ? + Math.sqrt(Math.pow((x - pointerX), 2.0) + Math.pow((y - pointerY), 2.0)) < radius : + ((Math.abs(pointerX - x) < radius) && (Math.abs(pointerY - y) < radius)); + } + + // 5. Drawing stuff + + p5.prototype.axes = function () { + this._renderer.axes(...arguments); + }; + + /** + * Draws axes. + * @param {Number} size size in world units. + * @param {Number} bits bitwise mask that may be composed of Tree.X, Tree._X, + * Tree.Y, Tree._Y, Tree.Z, Tree._Z and Tree.LABELS bits. + */ + p5.RendererGL.prototype.axes = function ({ size = 100, bits = Tree.LABELS | Tree.X | Tree.Y | Tree.Z } = {}) { + this._rendererState = this.push(); + if (~(bits | ~Tree.LABELS) === 0) { + const charWidth = size / 40.0; + const charHeight = size / 30.0; + const charShift = 1.04 * size; + // The X + this.stroke(200, 0, 0); + this.line(charShift, charWidth, -charHeight, charShift, -charWidth, charHeight); + this.line(charShift, -charWidth, -charHeight, charShift, charWidth, charHeight); + // The Y + this.stroke(0, 200, 0); + this.line(charWidth, charShift, charHeight, 0.0, charShift, 0.0); + this.line(0.0, charShift, 0.0, -charWidth, charShift, charHeight); + this.line(-charWidth, charShift, charHeight, 0.0, charShift, 0.0); + this.line(0.0, charShift, 0.0, 0.0, charShift, -charHeight); + // The Z + this.stroke(0, 100, 200); + this.line(-charWidth, -charHeight, charShift, charWidth, -charHeight, charShift); + this.line(charWidth, -charHeight, charShift, -charWidth, charHeight, charShift); + this.line(-charWidth, charHeight, charShift, charWidth, charHeight, charShift); + } + // X Axis + this.stroke(200, 0, 0); + if (~(bits | ~Tree.X) === 0) { + this.line(0, 0, 0, size, 0, 0); + } + if (~(bits | ~Tree._X) === 0) { + this.line(0, 0, 0, -size, 0, 0); + } + // Y Axis + this.stroke(0, 200, 0); + if (~(bits | ~Tree.Y) === 0) { + this.line(0, 0, 0, 0, size, 0); + } + if (~(bits | ~Tree._Y) === 0) { + this.line(0, 0, 0, 0, -size, 0); + } + // Z Axis + this.stroke(0, 100, 200); + if (~(bits | ~Tree.Z) === 0) { + this.line(0, 0, 0, 0, 0, size); + } + if (~(bits | ~Tree._Z) === 0) { + this.line(0, 0, 0, 0, 0, -size); + } + this.pop(this._rendererState); + }; + + p5.prototype.grid = function () { + this._renderer.grid(...arguments); + }; + + /** + * Draws grid + * @param {Number} size grid size in world units. Default is 100. + * @param {Number} subdivisions number of grid subdivisions. Default is 10. + * @param {Number} style either Tree.DOTS or Tree.SOLID. Default is Tree.DOTS. + */ + p5.RendererGL.prototype.grid = function ({ size = 100, subdivisions = 10, style = Tree.DOTS } = {}) { + this._rendererState = this.push(); + if (style === Tree.DOTS) { + let weight = this.curStrokeWeight; + // other useful as well: this.curStrokeColor this.curFillColor + let posi = 0; + let posj = 0; + this.strokeWeight(weight * 2); + this.beginShape(0x0000); + for (let i = 0; i <= subdivisions; ++i) { + posi = size * (2.0 * i / subdivisions - 1.0); + for (let j = 0; j <= subdivisions; ++j) { + posj = size * (2.0 * j / subdivisions - 1.0); + this.vertex(posi, posj, 0); + } + } + this.endShape(); + const internalSub = 5; + const subSubdivisions = subdivisions * internalSub; + this.strokeWeight(weight); + this.beginShape(0x0000); + for (let i = 0; i <= subSubdivisions; ++i) { + posi = size * (2.0 * i / subSubdivisions - 1.0); + for (let j = 0; j <= subSubdivisions; ++j) { + posj = size * (2.0 * j / subSubdivisions - 1.0); + if (((i % internalSub) != 0) || ((j % internalSub) != 0)) + this.vertex(posi, posj, 0); + } + } + this.endShape(); + } + else { + for (let i = 0; i <= subdivisions; ++i) { + const pos = size * (2.0 * i / subdivisions - 1.0); + this.line(pos, -size, 0, pos, +size, 0); + this.line(-size, pos, 0, size, pos, 0); + } + } + this.pop(this._rendererState); + }; + + p5.prototype.cross = function () { + this._renderer.cross(...arguments); + }; + + /** + * Draws a cross on the screen. + * @param {p5.Matrix} mMatrix model space matrix origin to compute (x, y) from. + * @param {Number} x screen x coordinate. Default is width / 2. + * @param {Number} y screen y coordinate. Default is height / 2. + * @param {Number} size cross size. Default is 50. + */ + p5.RendererGL.prototype.cross = function ({ + mMatrix = this.mMatrix(), + x, + y, + size = 50, + eMatrix, + pMatrix, + vMatrix, + pvMatrix + } = {}) { + if (!(x && y)) { + let screenLocation = this.treeLocation({ from: mMatrix, to: Tree.SCREEN, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + x = screenLocation.x; + y = screenLocation.y; + size = size / this.pixelRatio(this.treeLocation({ from: mMatrix, to: Tree.WORLD, eMatrix: eMatrix })); + } + const half_size = size / 2.0; + this._rendererState = this.push(); + this.beginHUD(); + this.line(x - half_size, y, x + half_size, y); + this.line(x, y - half_size, x, y + half_size); + this.endHUD(); + this.pop(this._rendererState); + }; + + p5.prototype.bullsEye = function () { + this._renderer.bullsEye(...arguments); + }; + + /** + * Draws a bulls-eye on the screen. + * @param {p5.Matrix} mMatrix model space matrix origin to compute (x, y) from. + * @param {Number} x screen x coordinate. Default is width / 2. + * @param {Number} y screen y coordinate. Default is height / 2. + * @param {Number} size bullseye diameter. Default is 50. + * @param {Number} shape either Tree.CIRCLE or Tree.SQUARE. Default is Tree.CIRCLE. + */ + p5.RendererGL.prototype.bullsEye = function ({ + mMatrix = this.mMatrix(), + x, + y, + size = 50, + shape = Tree.CIRCLE, + eMatrix, + pMatrix, + vMatrix, + pvMatrix + } = {}) { + if (!(x && y)) { + let screenLocation = this.treeLocation({ from: mMatrix, to: Tree.SCREEN, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + x = screenLocation.x; + y = screenLocation.y; + size = size / this.pixelRatio(this.treeLocation({ from: mMatrix, to: Tree.WORLD, eMatrix: eMatrix })); + } + this._rendererState = this.push(); + if (shape === Tree.CIRCLE) { + this.beginHUD(); + this._circle({ x, y, radius: size / 2 }) + this.endHUD(); + } + else { + const half_length = size / 2.0; + this.beginHUD(); + this.line((x - half_length), (y - half_length) + (0.6 * half_length), (x - half_length), (y - half_length)); + this.line((x - half_length), (y - half_length), (x - half_length) + (0.6 * half_length), (y - half_length)); + this.line((x + half_length) - (0.6 * half_length), (y - half_length), (x + half_length), (y - half_length)); + this.line((x + half_length), (y - half_length), (x + half_length), ((y - half_length) + (0.6 * half_length))); + this.line((x + half_length), ((y + half_length) - (0.6 * half_length)), (x + half_length), (y + half_length)); + this.line((x + half_length), (y + half_length), ((x + half_length) - (0.6 * half_length)), (y + half_length)); + this.line((x - half_length) + (0.6 * half_length), (y + half_length), (x - half_length), (y + half_length)); + this.line((x - half_length), (y + half_length), (x - half_length), ((y + half_length) - (0.6 * half_length))); + this.endHUD(); + } + this.cross({ x: x, y: y, size: 0.6 * size }); + this.pop(this._rendererState); + }; + + p5.prototype._circle = function () { + this._renderer._circle(...arguments); + }; + + p5.RendererGL.prototype._circle = function ({ filled = false, x = this.width / 2, y = this.height / 2, radius = 100, detail = 50 } = {}) { + this._rendererState = this.push(); + if (filled) { + this.beginShape(0x0005); + for (let t = 0; t <= detail; t++) { + const x = Math.cos(t * (2 * Math.PI) / detail); + const y = Math.sin(t * (2 * Math.PI) / detail); + this.vertex(0, 0, 0, 0.5, 0.5) + this.vertex(radius * x, radius * y, 0, (x * 0.5) + 0.5, (y * 0.5) + 0.5); + } + this.endShape(); + } + else { + this.translate(x, y); + const angle = (2 * Math.PI) / detail; + let lastPosition = { x: radius, y: 0 }; + for (let i = 1; i <= detail; i++) { + let position = { x: Math.cos(i * angle) * radius, y: Math.sin(i * angle) * radius }; + this.line(lastPosition.x, lastPosition.y, position.x, position.y); + lastPosition = position; + } + } + this.pop(this._rendererState); + }; + + p5.prototype.viewFrustum = function () { + this._renderer.viewFrustum(...arguments); + }; + + /** + * Display fbo view frustum. + * @param {p5.RendererGL | p5.Graphics} fbo renderer which viewing frustum is to be displayed. + * @param {Number} bits bitwise view-frustum mask that may be composed of Tree.NEAR, Tree.FAR and Tree.BODY bits. + * @param {Function} viewer callback fbo visual representation. + */ + p5.RendererGL.prototype.viewFrustum = function ({ + fbo = _renderer, + bits = Tree.NEAR | Tree.FAR, + viewer = () => this.axes({ size: 50, bits: Tree.X | Tree._X | Tree.Y | Tree._Y | Tree.Z | Tree._Z }) + } = {}) { + if (this === fbo) { + console.error('displaying viewFrustum requires an fbo different than this'); + return; + } + this._rendererState = this.push(); + this.resetMatrix(); + this.applyMatrix(...this.vMatrix().mat4); + this.applyMatrix(...fbo.eMatrix().mat4); + fbo._isOrtho() ? this._viewOrtho(fbo, bits, viewer) : this._viewPerspective(fbo, bits, viewer); + this.pop(this._rendererState); + }; + + p5.RendererGL.prototype._viewOrtho = function (fbo, bits, viewer) { + if (viewer !== Tree.NONE) { + viewer(); + } + let l = fbo.lPlane(); + let r = fbo.rPlane(); + let b = fbo.bPlane(); + let t = fbo.tPlane(); + let n = fbo.nPlane(); + let f = fbo.fPlane(); + if (~(bits | ~Tree.FAR) === 0) { + this.beginShape(); + this.vertex(r, t, -f, 0, 0); + this.vertex(l, t, -f, 1, 0); + this.vertex(l, b, -f, 1, 1); + this.vertex(r, b, -f, 0, 1); + this.endShape(); + } + else { + this.line(r, t, -f, l, t, -f); + this.line(l, t, -f, l, b, -f); + this.line(l, b, -f, r, b, -f); + this.line(r, b, -f, r, t, -f); + } + if (~(bits | ~Tree.BODY) === 0) { + this.beginShape(); + this.vertex(l, t, -f); + this.vertex(l, t, -n); + this.vertex(r, t, -n); + this.vertex(r, t, -f); + this.endShape(); + this.beginShape(); + this.vertex(r, t, -f); + this.vertex(r, t, -n); + this.vertex(r, b, -n); + this.vertex(r, b, -f); + this.endShape(); + this.beginShape(); + this.vertex(r, b, -f); + this.vertex(r, b, -n); + this.vertex(l, b, -n); + this.vertex(l, b, -f); + this.endShape(); + this.beginShape(); + this.vertex(l, t, -n); + this.vertex(l, t, -f); + this.vertex(l, b, -f); + this.vertex(l, b, -n); + this.endShape(); + } + else { + this.line(r, t, -n, r, t, -f); + this.line(l, t, -n, l, t, -f); + this.line(l, b, -n, l, b, -f); + this.line(r, b, -n, r, b, -f); + } + // TODO implement near plane texture + if (~(bits | ~Tree.NEAR) === 0) { + this.beginShape(); + this.vertex(r, t, -n, 0, 0); + this.vertex(l, t, -n, 1, 0); + this.vertex(l, b, -n, 1, 1); + this.vertex(r, b, -n, 0, 1); + this.endShape(); + } + else { + this.line(r, t, -n, l, t, -n); + this.line(l, t, -n, l, b, -n); + this.line(l, b, -n, r, b, -n); + this.line(r, b, -n, r, t, -n); + } + }; + + p5.RendererGL.prototype._viewPerspective = function (fbo, bits, viewer) { + if (viewer !== Tree.NONE) { + viewer(); + } + let magnitude = Math.tan(fbo.fov() / 2); + let aspectRatio = fbo.width / fbo.height; + const points = [ + { x: 0, y: 0, z: 0 }, + { x: 0, y: 0, z: 0 }, + ]; + points[0].z = fbo.nPlane(); + points[1].z = fbo.fPlane(); + points[0].y = points[0].z * magnitude; + points[0].x = points[0].y * aspectRatio; + const ratio = points[1].z / points[0].z; + points[1].y = ratio * points[0].y; + points[1].x = ratio * points[0].x; + if (~(bits | ~Tree.FAR) === 0) { + this.beginShape(); + this.vertex(-points[1].x, points[1].y, -points[1].z, 0, 0); + this.vertex(points[1].x, points[1].y, -points[1].z, 1, 0); + this.vertex(points[1].x, -points[1].y, -points[1].z, 0, 1); + this.vertex(-points[1].x, -points[1].y, -points[1].z, 1, 1); + this.endShape(); + } + else { + this.line(-points[1].x, points[1].y, -points[1].z, points[1].x, points[1].y, -points[1].z); + this.line(points[1].x, points[1].y, -points[1].z, points[1].x, -points[1].y, -points[1].z); + this.line(points[1].x, -points[1].y, -points[1].z, -points[1].x, -points[1].y, -points[1].z); + this.line(-points[1].x, -points[1].y, -points[1].z, -points[1].x, points[1].y, -points[1].z); + } + if (~(bits | ~Tree.BODY) === 0) { + this.beginShape(); + this.vertex(-points[1].x, points[1].y, -points[1].z); + this.vertex(-points[0].x, points[0].y, -points[0].z); + this.vertex(points[0].x, points[0].y, -points[0].z); + this.vertex(points[1].x, points[1].y, -points[1].z); + this.endShape(); + this.beginShape(); + this.vertex(points[1].x, points[1].y, -points[1].z); + this.vertex(points[0].x, points[0].y, -points[0].z); + this.vertex(points[0].x, -points[0].y, -points[0].z); + this.vertex(points[1].x, -points[1].y, -points[1].z); + this.endShape(); + this.beginShape(); + this.vertex(points[1].x, -points[1].y, -points[1].z); + this.vertex(points[0].x, -points[0].y, -points[0].z); + this.vertex(-points[0].x, -points[0].y, -points[0].z); + this.vertex(-points[1].x, -points[1].y, -points[1].z); + this.endShape(); + this.beginShape(); + this.vertex(-points[0].x, points[0].y, -points[0].z); + this.vertex(-points[1].x, points[1].y, -points[1].z); + this.vertex(-points[1].x, -points[1].y, -points[1].z); + this.vertex(-points[0].x, -points[0].y, -points[0].z); + this.endShape(); + this.line(0, 0, 0, points[0].x, points[0].y, -points[0].z); + this.line(0, 0, 0, -points[0].x, points[0].y, -points[0].z); + this.line(0, 0, 0, -points[0].x, -points[0].y, -points[0].z); + this.line(0, 0, 0, points[0].x, -points[0].y, -points[0].z); + } + else { + this.line(0, 0, 0, points[1].x, points[1].y, -points[1].z); + this.line(0, 0, 0, -points[1].x, points[1].y, -points[1].z); + this.line(0, 0, 0, -points[1].x, -points[1].y, -points[1].z); + this.line(0, 0, 0, points[1].x, -points[1].y, -points[1].z); + } + // TODO implement near plane texture + // Something along the lines + // this.textureMode(NORMAL); + // this.tint(255, 126); // Apply transparency without changing color + // this.texture(fbo); + // doesn't work since this.texture is not found + if (~(bits | ~Tree.NEAR) === 0) { + this.beginShape(); + this.vertex(-points[0].x, points[0].y, -points[0].z, 0, 0); + this.vertex(points[0].x, points[0].y, -points[0].z, 1, 0); + this.vertex(points[0].x, -points[0].y, -points[0].z, 0, 1); + this.vertex(-points[0].x, -points[0].y, -points[0].z, 1, 1); + this.endShape(); + } + else { + this.line(-points[0].x, points[0].y, -points[0].z, points[0].x, points[0].y, -points[0].z); + this.line(points[0].x, points[0].y, -points[0].z, points[0].x, -points[0].y, -points[0].z); + this.line(points[0].x, -points[0].y, -points[0].z, -points[0].x, -points[0].y, -points[0].z); + this.line(-points[0].x, -points[0].y, -points[0].z, -points[0].x, points[0].y, -points[0].z); + } + }; +})(); + +function Plane(){ + this.planeMaxMagR = 25; + this.planeColor = "rgb(255, 247, 233)"; + this.planeMagnitudeR = 0; + + this.planeRotateV = createVector(1,0,0); + this.planeSize = createVector(200,200,0); //ancho y alto + this.planePosition = createVector(0,0,0); + + this.draw = function(fbo){ + + fbo.fill(this.planeColor); + fbo.translate(this.planePosition); + fbo.plane(this.planeSize.x,this.planeSize.y) + + }; +} + +class Wall { + + constructor(originX,originY,originZ,width,height,depth, fillColor){ + this.fillColor = fillColor + this.origin = createVector(originX,originY,originZ) + this.width = width + this.height = height + this.depth = depth + this.wallMax = createVector(originX+ width/2, originY+ height/2, originZ+ depth/2) + this.wallMin = createVector(originX-width/2, originY-height/2, originZ - depth/2) + } + + + draw(fbo){ + fbo.push() + //fbo.line(this.wallMin.x,this.wallMin.y,this.wallMin.z,this.wallMax.x,this.wallMax.y,this.wallMax.z) + fbo.fill(this.fillColor) + fbo.translate(this.origin.x,this.origin.y,this.origin.z) + fbo.box(this.width, this.height,this.depth) + fbo.pop() + }; + closestPointSphere(B) { + // get box closest point to sphere center by clamping + const x = Math.max(this.wallMin.x, Math.min(B.spherePosition.x, this.wallMax.x)); + const y = Math.max(this.wallMin.y, Math.min(B.spherePosition.y, this.wallMax.y)); + const z = Math.max(this.wallMin.z, Math.min(B.spherePosition.z, this.wallMax.z)); + + // this is the same as isPointInsidespherePosition + return createVector(x,y,z); +} +isPointInside(point) { + return ( + point.x >= this.wallMin.x && + point.x <= this.wallMax.x && + point.y >= this.wallMin.y && + point.y <= this.wallMax.y && + point.z >= this.wallMin.z && + point.z <= this.wallMax.z + ); +} + collisionWithSphere(B){ + let cPoint = this.closestPointSphere(B) + const distance = Math.sqrt( + (cPoint.x - B.spherePosition.x) * (cPoint.x - B.spherePosition.x) + + (cPoint.y - B.spherePosition.y) * (cPoint.y - B.spherePosition.y) + + (cPoint.z - B.spherePosition.z) * (cPoint.z - B.spherePosition.z) + ); + let sine = sqrt(1-sq(B.acceleration.z)); + let cPointBouncing = undefined + if(distance= B.minVertex.x && + B.spherePosition.y >= B.minVertex.y && + B.spherePosition.z-10 >= B.minVertex.z && + B.spherePosition.x <= B.maxVertex.x && + B.spherePosition.y <= B.maxVertex.y && + B.spherePosition.z-10 <= B.maxVertex.z){ + + P.planeColor = "white" + } + else{ + P.planeColor = "rgba(255, 247, 233,1)" + } + + + beginHUD(); + image(fbo1, 0, 0); + endHUD(); +} +} + + +function getVectorModule(vector){ + return Math.sqrt(vector.x**2 +vector.y**2 +vector.z**2); +} + +function mousePressed() { + mouseInitialV = createVector(mouseX, mouseY, 0); +} + + +function mouseDragged(){ + + mouseCurrentV = createVector(mouseX, mouseY, 0); + let vectorSubstra = createVector(mouseInitialV.x - mouseCurrentV.x, + mouseInitialV.y - mouseCurrentV.y, + mouseInitialV.z - mouseCurrentV.z); + let mod = getVectorModule(vectorSubstra); + let vectorDir = createVector(vectorSubstra.x/mod, + vectorSubstra.y/mod, + vectorSubstra.z/mod ); + let sine = sqrt(1-sq(vectorDir.z)); + + B.acceleration = createVector(-sine*vectorDir.x, -sine*vectorDir.y, sine*vectorDir.z); + + let aux = vectorDir.x; + vectorDir.x = vectorDir.y; + vectorDir.y = -aux; + + if (mod < P.planeMaxMagR){ + P.planeMagnitudeR = mod + } + P.planeRotateV = vectorDir; + P.planeRotateV.z = 0; + +} + +function closestPoint(spherePosition, boxMin, boxMax) { + // get box closest point to sphere center by clamping + const x = Math.max(boxMin.x, Math.min(spherePosition.x, boxMax.x)); + const y = Math.max(boxMin.y, Math.min(spherePosition.y, boxMax.y)); + const z = Math.max(boxMin.z, Math.min(spherePosition.z, boxMax.z)); + + // this is the same as isPointInsidespherePosition + return createVector(x,y,z); +} +function dataToWalls(wallsData){ + let walls = wallsData.map(({x,y,z,width,height,depth, fillColor}) =>{ + return new Wall(x,y,z,width,height,depth,fillColor) + }) + return walls +} +function drawListObjects(list, fbo){ + list.forEach(object =>{ + object.draw(fbo) + }) +} +function collisionWalls(walls, B) { + + for(let i=0;i}} +{{< p5-iframe srcdoc="lib3" srcdoc="lib4" sketch="/visual_computing/sketches/maze/sketch.js" width="450" height="450">}} + +--- + +# Conclusiones + +- **P5.treegl** Permitio que la realizacion del ejercicio fuera un poco mas simple de lo que se hubiese logrado a fuerza bruta, sin embargo p5.js presenta muchas desventajas al momento de simular fisicas en los objetos ya que para crearlos son pocos los parametros que existen por lo cual no se recomienda para personas no experimentadas. +- El Funcionamiento de tipo vectorial que existe en **P5** permite una aproximacion matematica para la manipulacion del espacio y los objetos creados en el. + +# Referencias + +{{< hint warning >}} + +- [1] _“Reference | p5.js,”_ **p5js.org.** https://p5js.org/es/reference/ (accessed Oct. 18, 2022). +- [2] _“p5.treegl,”_ **GitHub**, Sep. 12, 2022. https://github.com/VisualComputing/p5.treegl (accessed Oct. 18, 2022). +- [3] _“Laberinto,”_ **Wikipedia**, Aug. 24, 2022. https://es.wikipedia.org/wiki/Laberinto (accessed Oct. 18, 2022). + +{{< /hint >}} diff --git a/content/docs/shortcodes/Taller 2/Aplicacion 3-D/_index.md b/content/docs/shortcodes/Taller 2/Aplicacion 3-D/_index.md new file mode 100644 index 00000000..af83640f --- /dev/null +++ b/content/docs/shortcodes/Taller 2/Aplicacion 3-D/_index.md @@ -0,0 +1,11 @@ +--- +bookCollapseSection: true +--- + +# Aplicacion 3D + +## Objetivo + +X + +{{
}} diff --git a/content/docs/shortcodes/Taller 2/Rasterizacion/Midpoint Circle Algorithm.md b/content/docs/shortcodes/Taller 2/Rasterizacion/Midpoint Circle Algorithm.md new file mode 100644 index 00000000..b5e379b6 --- /dev/null +++ b/content/docs/shortcodes/Taller 2/Rasterizacion/Midpoint Circle Algorithm.md @@ -0,0 +1,55 @@ +# Midpoint Circle Algorithm + +El algoritmo de dibujo de círculo de punto medio es un algoritmo utilizado para determinar los puntos necesarios para rasterizar un círculo. + +Usamos el algoritmo del punto medio para calcular todos los puntos del perímetro del círculo en el primer octante y luego los imprimimos junto con sus puntos de espejo en los otros octantes. Esto funcionará porque un círculo es simétrico con respecto a su centro. + +![](https://media.geeksforgeeks.org/wp-content/uploads/circle-5.jpg) + +## Formulas + +Dado un circle centrado en (0,0) y un radio r. Teniendo un punto con coordenadas p(x,y) + +{{< katex display >}} +F(p) = x^2+y^2-r^2 +{{< /katex >}} + +| Name | Matrix | +| ------------------------------------------- | -------------------------------- | +| {{< katex display >}}F(p) < 0{{< /katex >}} | El punto esta dentro del circulo | +| {{< katex display >}}F(p) = 0{{< /katex >}} | El punto esta en el perimetro | +| {{< katex display >}}F(p) > 0{{< /katex >}} | El punto esta fuera del circulo | + +![](https://3.bp.blogspot.com/-X8qWA41L1Tc/W8wU2ONH55I/AAAAAAAAAKY/DFM7qT67HfgIpRwThlCH8izwzHG6JF7gACLcBGAs/s1600/midpointcircle%2B%25281%2529.png) + +{{< details title="Midpoint circle algorithm" open=false >}} + +```javascript +function calculateOctant(middle) { + x += 1; + // Mid-point is inside or on the perimeter + if (p <= 0) { + p = p + 2 * x + 1; + } else { + y -= 1; + p = p + 2 * x - 2 * y + 1; + } + const __x = x * space; + const __y = y * space; + savePointsCircle(__x, __y); + if (fillCircle) { + for (let i = 1; i < r; i++) { + savePointsCircle(__x, __y - space * i); + } + } + + if (x >= y - 1) { + return true; + } + return false; +} +``` +{{< /details >}} + + +{{< p5-iframe sketch="/visual_computing/sketches/rasterization.js" width="646" height="646" >}} diff --git a/content/docs/shortcodes/Taller 2/Rasterizacion/Triangle Rasterization.md b/content/docs/shortcodes/Taller 2/Rasterizacion/Triangle Rasterization.md new file mode 100644 index 00000000..6711c0ee --- /dev/null +++ b/content/docs/shortcodes/Taller 2/Rasterizacion/Triangle Rasterization.md @@ -0,0 +1,220 @@ +# Triangle rasterization + +La rasterización es el proceso por el cual una imagen se transforma en un conjunto de pixeles, los cuales pueden ser mostrados a traves de una salida digital. Este procedimiento incluye el uso de diferentes algoritmos dependiendo de la figura que se vaya a rasterizar. + +Por ejemplo para razterizar un triangulo se necesita el desarrollo de dos pasos: +- Capturar su figura +- Recorrer su figura a traves de los pixeles + +Para el primer paso es necesario verificar si el triangulo encaja en alguna de las siguientes opciones: + +![](https://brakeza.com/wp-content/uploads/2018/12/concepto_rasterizacio%CC%81n.png) + +Si no encaja en la figura BottomFlat o TopFlat, el triangulo debera partirse en dos como muestra la siguiente imagen: + +![](https://docs.hektorprofe.net/cdn/graficos3d/image-49.png) + +De manera que los triangulos resultantes sean de tipo BottomFlat o TopFlat. + +Posteriormente se determinan los valores de x por donde pasa el triangulo, de forma que si el triangulo es de tipo BottomFlat, se recorra linea por linea de arriba abajo, y de izquierda a derecha y si es de tipo TopFlat de abajo hacia arriba y de izquierda a derecha. + + ## Formulas +La formula para determinar los valores de x antes mencionada es dependiente del tipo, asi con pa, pb y pc como puntos del triangulo, las formulas serian las siguientes: + +- BottomFlat + {{< katex display >}} + ext1 = (pb.x - pa.x) / (pb.y - pa.y); + ext2 = (pc.x - pa.x) / (pc.y - pa.y); + {{< /katex >}} +- TopFlat +{{< katex display >}} + ext1 = (pc.x - pa.x) / (pc.y - pa.y); + ext2 = (pc.x - pb.x) / (pc.y - pb.y); + {{< /katex >}} + + Donde ext1 representa el expremo izquierdo de la fila y ext1 representa el expremo derecho de la fila que contiene el triangulo. + + + +{{< details title="Raterization algorithm" open=false >}} + +```javascript +let n1 = 500; +let n2 = 420; +let n3 = 258; +let n4 = 420; +let n5 = 486; +let n6 = 275; +let space = 20; +var p1, p2, p3, p4; +let puntos; +let x,y; +let beads; +let beadSize = 20; +let cols, rows; +let num; + +function setup() { + createCanvas(621, 621) + cols = ceil(621 / beadSize); + rows = ceil(621 / beadSize); + beads = new Array(cols); + for (let x = 0; x < cols; x++){ + beads[x] = new Array(rows).fill(false); + } + organizeTriangle(); + clasifyTriangle(); +} + +function draw() { + background(0,0,40); + drawGrid(); + paint(num); + line(puntos[0].x, puntos[0].y, puntos[1].x, puntos[1].y); + line(puntos[0].x, puntos[0].y, puntos[2].x, puntos[2].y); + line(puntos[2].x, puntos[2].y, puntos[1].x, puntos[1].y); + stroke("red"); + +} + +function drawBeads(columnainicial, columnafinal,filas){ + let filasm = filas + 1; + let columnainicialm = columnainicial - 4; + push(); + noStroke(); + //fill(0); + fill(0, 179, 255); + for (let i = columnainicialm; i <= columnafinal; i++){ + for (let j = filas; j < filasm; j++){ + square(i * beadSize, j * beadSize, beadSize); + } + + } + pop(); +} + +function drawGrid(){ + push(); + stroke(200); + for (let x = 0; x < 621; x+= beadSize){ + line(x, 0, x, 621); + } + + for (let y = 0; y < 621; y+= beadSize){ + line(0, y, 621, y); + } + pop(); +} + + +function organizeTriangle(){ + p1= { + x: n1, + y: n2 + }; + p2 = { + x: n3, + y: n4 + }; + p3 = { + x: n5, + y: n6 + } + puntos = [p1, p2, p3]; + + for (var i = 0; i < 3; i++) { + for (var j = 0; j < 2; j++){ + if(puntos[i].y > puntos[j+1].y ){ + let punto = puntos[i]; + puntos[i] = puntos[j + 1]; + puntos[j + 1 ] = punto; + } + } + } + + if(puntos[0].y == puntos[1].y){ + if(puntos[0].x > puntos[1].x){ + let punto = puntos[0]; + puntos[0] = puntos[1]; + puntos[1] = punto; + } + } + +} + +function clasifyTriangle(){ + if (puntos[1].y == puntos[2].y) { + num = 1; + } else if (puntos[0].y == puntos[1].y) { + num = 2; + } else { + num = 3; + x = (int) (puntos[0].x + ((puntos[1].y - puntos[0].y) / (puntos[2].y - puntos[0].y)) * (puntos[2].x - puntos[0].x)); + y = (int) (puntos[1].y); + + p4 = { + x: x, + y: y + } + + //scanBottomFlatTriangle(puntos[0], puntos[1], p4); + //scanTopFlatTriangle(p4, puntos[1], puntos[2]); + + } +} + +function scanTopFlatTriangle(pa, pb, pc){ + + let invslope1 = (pc.x - pa.x) / (pc.y - pa.y); + let invslope2 = (pc.x - pb.x) / (pc.y - pb.y); + + let curx1 = pc.x; + let curx2 = pc.x; + + for (var scanlineY = pc.y; scanlineY < pa.y;scanlineY--) { + scanLine(curx1, curx2, scanlineY); + curx1 -= invslope1; + curx2 -= invslope2; + } +} + +function scanBottomFlatTriangle(pa, pb, pc){ + let invslope1 = parseInt((pb.x - pa.x) / (pb.y - pa.y)); + let invslope2 = parseInt((pc.x - pa.x) / (pc.y - pa.y)); + + let curx1 = pa.x; + let curx2 = pa.x; + + for (var scanlineY = pa.y; scanlineY <= pb.y;scanlineY++) { + scanLine(curx1, curx2, scanlineY); + curx1 += invslope1; + curx2 += invslope2; + } +} +function scanLine(curx1, curx2, scanlineY){ + curx1 = parseInt(curx1/ beadSize); + curx2 = parseInt(curx2 / beadSize); + scanlineY = parseInt(scanlineY / beadSize); + console.log(curx1); + console.log(curx2); + console.log(scanlineY); + drawBeads(curx1, curx2,scanlineY); +} + +function paint(num){ + if(num == 1){ + scanBottomFlatTriangle(puntos[0], puntos[1], puntos[2]); + }else{ + if(num == 2){ + scanTopFlatTriangle(puntos[0], puntos[1], puntos[2]); + } + } +} +``` +{{< /details >}} + +{{< p5-iframe sketch="/visual_computing/sketches/rasterization_2.js" width="646" height="646" >}} + + ## Referencias + + https://brakeza.com/rasterizacion-del-triangulo#:~:text=El%20t%C3%A9rmino%20bajo%20el%20que,el%20interior%20de%20un%20tri%C3%A1ngulo. diff --git a/content/docs/shortcodes/Taller 2/Rasterizacion/_index.md b/content/docs/shortcodes/Taller 2/Rasterizacion/_index.md new file mode 100644 index 00000000..f11d6ff1 --- /dev/null +++ b/content/docs/shortcodes/Taller 2/Rasterizacion/_index.md @@ -0,0 +1,11 @@ +--- +bookCollapseSection: true +--- + +# Rasterizacion + +## Objetivo + +X + +{{
}} diff --git a/content/docs/shortcodes/Taller 2/_index.md b/content/docs/shortcodes/Taller 2/_index.md new file mode 100644 index 00000000..3cf1d754 --- /dev/null +++ b/content/docs/shortcodes/Taller 2/_index.md @@ -0,0 +1,11 @@ +--- +bookCollapseSection: true +--- + +# Taller 2 + +## Objetivo + +X + +{{
}} diff --git a/content/docs/shortcodes/Taller 3/Ambient Light/_index.md b/content/docs/shortcodes/Taller 3/Ambient Light/_index.md new file mode 100644 index 00000000..cbfe9cb5 --- /dev/null +++ b/content/docs/shortcodes/Taller 3/Ambient Light/_index.md @@ -0,0 +1,144 @@ +# Luz ambiente + +La luz ambiente no suele tener un punto de origen definido. Se puede ver como una iluminación en todas direcciones. + + +## implementación + +Cada pixel del objeto es definido mediante la formula + +{{< katex display >}} +color = ambient * (uMaterialColor * uColor) +{{< /katex >}} + +* Donde **color** es el color final del pixel +* **ambient** es la cantidad de luminosidad +* **uMaterialColor** es el color del pixel original +* **uColor** es el color de ambiente elegido + + + +{{< p5-iframe sketch="/visual_computing/sketches/shaders/diffuse/diffuseRefl2.js" lib1="https://cdn.jsdelivr.net/gh/VisualComputing/p5.treegl/p5.treegl.js" lib2="https://cdn.jsdelivr.net/gh/freshfork/p5.EasyCam@1.2.1/p5.easycam.js" width="625" height="475" >}} + + +{{< details "**CODIGO:** ambientLight.js" close >}} +```javascript + +let lightShader; +let ambient; +function preload() { + lightShader = readShader('../../../../sketches/shaders/diffuse/ambient.frag', + { varyings: Tree.NONE }); +} + +function setup() { + createCanvas(600, 450, WEBGL); + // easycam stuff + let state = { + distance: 250, // scalar + center: [0, 0, 0], // vector + rotation: [0, 0, 0, 1], // quaternion + }; + easycam = createEasyCam(); + easycam.state_reset = state; // state to use on reset (double-click/tap) + easycam.setState(state, 2000); // now animate to that state + perspective(); + + colorMode(RGB,1); + // disable p5 lightning + noLights(); + ambient = createSlider(0, 1, 1.0, 0.05); + ambient.position(420, 10); + ambient.style('width', '80px'); + ambient.input(() => { lightShader.setUniform('ambient', ambient.value()) }); + + lightShader.setUniform('ambient', 0); + + colorPicker = createColorPicker(color(1,1,1)); + colorPicker.position(420,50) + colorPicker.input(() => { lightShader.setUniform('uColor', + [red(colorPicker.color()), + green(colorPicker.color()), + blue(colorPicker.color()), + 1.0]) }) + lightShader.setUniform('uColor', + [red(colorPicker.color()), + green(colorPicker.color()), + blue(colorPicker.color()), + 1.0]) + shader(lightShader); + // ... + // select initial brush +} + +function draw() { + + background(120); + push(); + strokeWeight(0.8); + stroke('magenta'); + grid({ dotted: false }); + pop(); + axes(); + + noStroke(); + fill(1,0,1) + push() + translate(0,0,5) + box(10,200,10); + pop() + + + fill(1,0,1) + push() + translate(0,0,5) + box(200,10,10); + pop() + + fill(0.8,0.3,0.3) + push() + translate(0,100,100) + box(200,10,200); + pop() + + fill(1,1,0) + push() + translate(100,0,100) + box(10,200,200); + pop() + +} + + +function mouseWheel(event) { + //comment to enable page scrolling + return false; +} + +function hexToRgb(hex) { + hex = hex.replace('#', ''); + + var bigint = parseInt(hex, 16); + + var r = (bigint >> 16) & 255; + var g = (bigint >> 8) & 255; + var b = bigint & 255; + + return color(r, g, b); +} +``` +{{< /details >}} + +# Conclusiones + +- Por su facilidad y rapidez, se podría intentar acoplar a una interfaz de personalización de una aplicación. + +# Referencias + +{{< hint warning >}} + +- [1] _“Reference | p5.js,”_ **p5js.org.** https://p5js.org/es/reference/ (accessed Oct. 18, 2022). +- [2] _“p5.treegl,”_ **GitHub**, Sep. 12, 2022. https://github.com/VisualComputing/p5.treegl (accessed Oct. 18, 2022). +- [3] _“Graphics lighting,”_ **Wikipedia**, Nov. 25, 2022 .https://en.wikipedia.org/wiki/Computer_graphics_lighting (accessed Nov. 25-28, 2022). + +{{< /hint >}} diff --git a/content/docs/shortcodes/Taller 3/Coloring/_index.md b/content/docs/shortcodes/Taller 3/Coloring/_index.md new file mode 100644 index 00000000..b5a7b81f --- /dev/null +++ b/content/docs/shortcodes/Taller 3/Coloring/_index.md @@ -0,0 +1,26 @@ +# Color blending + +Blending two colors is implemented by doing a component-wise multiplication between them +{{< p5-iframe sketch="/visual_computing/sketches/shaders/blend.js" width="470" height="275" >}} + +{{< details "**CODIGO:** blend.frag" close >}} +``` +precision mediump float; + +// uniforms are emitted from the sketch +// https://p5js.org/reference/#/p5.Shader/setUniform +uniform vec4 uMaterial1; +uniform vec4 uMaterial2; + +void main() { + gl_FragColor = uMaterial1 * uMaterial2; +} +``` +{{< /details >}} + + +# Color blending with lightness +{{< p5-iframe sketch="/visual_computing/sketches/shaders/light.js" width="470" height="275" >}} + +# Different blending modes +{{< p5-iframe sketch="/visual_computing/sketches/shaders/blendMode.js" width="470" height="475" >}} diff --git a/content/docs/shortcodes/Taller 3/Image Processing/_index.md b/content/docs/shortcodes/Taller 3/Image Processing/_index.md new file mode 100644 index 00000000..ca09eb6d --- /dev/null +++ b/content/docs/shortcodes/Taller 3/Image Processing/_index.md @@ -0,0 +1,420 @@ +## Image Processing + +El **procesamiento de imagenes** es la manipulación de imagenes mediante procesos computacionales manejados por **GPU** y el uso de algoritmos que modifican las imagenes. En muchos de los casos se utilizan **operaciones matematicas de nivel matricial** para transformar los colores de las imagenes, o distorsionarlas como se lograria con **efectos de amplificación**. + +### 1. **Procesamiento** + +{{< hint info >}} +**Ejercicio 1:** +Implemente una aplicacion para el procesamiento de imagenes / videos que soporte el uso de diferentes mascaras, incluyendo kernels de tamaño diferente a 3x3 y: +* Una Herramienta de region de interes para aplicar selectivamente una mascara: +* Una Herramienta de magnidicacion. +* Una herramienta que integre **Luma** y otras herramientas. +{{< /hint >}} + +{{< hint info >}} +**Ejercicio 2.1:** +Incluir el canal **azul** en la visualizacion UV, ya sea **Azul + Verde** ó **Azul + Rojo**. +{{< /hint >}} + +{{< hint warning >}} +**Solucion Ejercicio 2.1:** +Modificar el shader para que evalue 2 variables y reajuste el color dependiendo de una de las opciones seleccionadas, modificando uno de los canales dependiendo de la opcion. +{{< /hint >}} + +{{< p5-iframe sketch="/visual_computing/sketches/app.js" width="725" height="725" >}} + +{{< details "**CODIGO:** app.js" close >}} +```javascript + +let maskShader; +let img; +let video_src; +let video_on; +let cam_src; +let cam_on; +let ColorT; + +let mask_mode; +let coloring; +let lenses; +//let maskmode; + +function preload() { + video_src = createVideo(['/visual_computing/vid/drift.mp4']); + video_src.hide(); + + cam_src = createCapture(VIDEO); + cam_src.size(width, height); + cam_src.hide(); + + maskShader = readShader('/visual_computing/sketches/shaders/mask.frag', { varyings: Tree.texcoords2 }); + img = loadImage('/visual_computing/imgs/car.jpg'); +} + +function setup() { + createCanvas(700, 700, WEBGL); + noStroke(); + textureMode(NORMAL); + + //Camera selector + cam_on = createCheckbox('Live', false); + cam_on.style('color','black'); + cam_on.position(10,50); + + //Camera Controls + cam_on.changed(() => { + if(cam_on.checked()){ + maskShader.setUniform('texture',cam_src); + }else{ + maskShader.setUniform('texture', img); + } + }); + + + //Video Controls + video_on = createCheckbox('Video', false); + video_on.style('color', 'black'); + video_on.position(10, 30); + + //Video & image Switcher + video_on.changed(() => { + if (video_on.checked()) { + maskShader.setUniform('texture', video_src); + video_src.loop(); + } else { + maskShader.setUniform('texture', img); + video_src.pause(); + } + }); + + //Mask controls + mask_mode = createCheckbox('Masks', false); + mask_mode.position(10, 10); + mask_mode.style('color', 'black'); + + //Coloring checkbox + coloring = createCheckbox('Coloring',false); + coloring.position(165, 10); + coloring.style('color','black'); + + //Lenses checkbox + lenses = createCheckbox('Lense',false); + lenses.position(360, 10); + lenses.style('color','black'); + + //Shader apply + shader(maskShader); + maskShader.setUniform('texture', img); + emitTexOffset(maskShader, img, 'texOffset'); + + //Kernel selector + sel = createSelect(); + sel.position(80, 10); + sel.option('None'); + sel.option('Edges'); + sel.option('Sharpen'); + sel.option('Box Blur'); + sel.option('Emboss'); + + + sel.selected('None'); + + //Coloring selector + selC = createSelect(); + selC.position(245, 10); + selC.option('None'); + selC.option('Luma'); + selC.option('Average'); + selC.option('HSV Value V'); + selC.option('HSL Value L'); + selC.option('Tint'); + + selC.selected('None'); + + //Color Picker + colorT = createColorPicker(color(255,255,255)); + colorT.position(175, 30); + + //lenses parameters + Rslider = createSlider(50.0, 150.0, 50.0); + Rslider.position(360, 30); + Rslider.style('width', '80px'); + let div1 = createDiv('Lens Radio'); + div1.style('font-size', '18px'); + div1.style('color', '#000000'); + div1.position(450, 30); + + Sslider = createSlider(0.0, 1.0, 0.0, 0.01); + Sslider.position(360, 50); + Sslider.style('width', '80px'); + let div2 = createDiv('Lens Amplitude'); + div2.style('font-size', '18px'); + div2.style('color', '#000000'); + div2.position(450, 50); + +} + +function draw() { + background(0); + + //Mask Mode + if (mask_mode.checked()){ + + //Enable Masks Mode + maskShader.setUniform('maskmode',true); + maskShader.setUniform('coloringmode',false); + + //kernels + if (sel.value()=='Edges') { + maskShader.setUniform('mask', [-1, -1, -1, -1, 8, -1, -1, -1, -1]); + }else if(sel.value()=='Sharpen'){ + maskShader.setUniform('mask', [0, -1, 0, -1, 5, -1, 0, -1, 0]); + }else if(sel.value()=='Box Blur'){ + maskShader.setUniform('mask', [1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9]); + }else if(sel.value()=='Emboss'){ + maskShader.setUniform('mask', [-2, -1, 0, -1, 1, 1, 0, 1, 2]); + }else{ + maskShader.setUniform('mask', [0, 0, 0, 0, 1, 0, 0, 0, 0]); + } + + }else if(coloring.checked()){ + + + //Enable Coloring Mode + maskShader.setUniform('maskmode',false); + maskShader.setUniform('coloringmode',true); + + if(selC.value()=="None"){ + maskShader.setUniform('HSVV',false); + maskShader.setUniform('HSLL',false); + maskShader.setUniform('grey_scale',false); + maskShader.setUniform('average',false); + maskShader.setUniform('Tint',false); + + }else if(selC.value()=="Luma"){ + maskShader.setUniform('grey_scale',true); + maskShader.setUniform('average',false); + maskShader.setUniform('HSVV',false); + maskShader.setUniform('HSLL',false); + maskShader.setUniform('Tint',false); + + }else if(selC.value()=="Average"){ + maskShader.setUniform('average',true); + maskShader.setUniform('grey_scale',false); + maskShader.setUniform('HSVV',false); + maskShader.setUniform('HSLL',false); + maskShader.setUniform('Tint',false); + + }else if(selC.value() =="HSV Value V"){ + maskShader.setUniform('HSVV',true); + maskShader.setUniform('HSLL',false); + maskShader.setUniform('average',false); + maskShader.setUniform('grey_scale',false); + maskShader.setUniform('Tint',false); + + }else if(selC.value() =="HSL Value L"){ + maskShader.setUniform('HSLL',true); + maskShader.setUniform('HSVV',false); + maskShader.setUniform('average',false); + maskShader.setUniform('grey_scale',false); + maskShader.setUniform('Tint',false); + + }else if(selC.value() =="Tint"){ + maskShader.setUniform('Tint',true); + maskShader.setUniform('HSLL',false); + maskShader.setUniform('HSVV',false); + maskShader.setUniform('average',false); + maskShader.setUniform('grey_scale',false); + + let RC = colorT.color(); + maskShader.setUniform('colorT',[red(RC),green(RC),blue(RC),1.0]); + } + + }else if(lenses.checked()){ + maskShader.setUniform('lensemode',true); + maskShader.setUniform('maskmode',false); + maskShader.setUniform('coloringmode',false); + + maskShader.setUniform('mouseData',[mouseX,mouseY]); + maskShader.setUniform('resolution',[width,height]); + maskShader.setUniform('radio', Rslider.value()); + maskShader.setUniform('scale', Sslider.value()); + }else{ + maskShader.setUniform('lensemode',false); + maskShader.setUniform('maskmode',false); + maskShader.setUniform('coloringmode',false); + } + + + quad(-width / 2, -height / 2, width / 2, -height / 2, width / 2, height / 2, -width / 2, height / 2); +} + +``` +{{< /details >}} + +{{< details "**CODIGO:** mask.frag" close >}} +```glsl +precision mediump float; + +uniform bool maskmode; +uniform bool coloringmode; +uniform bool lensemode; + +uniform bool grey_scale; +uniform bool average; +uniform bool HSVV; +uniform bool HSLL; +uniform bool Tint; + +uniform vec4 colorT; + +uniform sampler2D texture; + +uniform vec2 texOffset; +uniform float mask[9]; + +varying vec2 texcoords2; + +uniform vec2 mouseData; +uniform vec2 resolution; + +uniform vec4 passerGL; + +uniform float radio; +uniform float scale; + +//-------------------------------------------------------------------------- + +float rim = 2.0; +vec2 handview = vec2(10.0,50.0); + +vec2 curveGen(vec2 toPow, float dist){ + float x = dist/radio; + return toPow * (1.0 - x) * exp (-2.0 * x * x); +} + +void Amplify (){ + + vec2 UV = gl_FragCoord.xy / resolution.xy; + gl_FragColor = texture2D(texture, UV); + + vec2 center = mouseData.xy; + float dist = distance(gl_FragCoord.xy,center); + + vec2 distV = gl_FragCoord.xy - center; + + if (dist > radio && dist < radio + rim){ + gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); + } + + if(abs(distV.x) < (handview.x / 2.0 ) && abs(distV.y + radio) < (handview.y) && dist >= radio + rim){ + gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); + } + + if(dist < radio){ + vec2 trueUV = (gl_FragCoord.xy - (curveGen(distV,dist) * scale)) / resolution.xy ; + gl_FragColor = texture2D(texture, trueUV); + } +} + +//-------------------------------------------------------------------------- + +void Convolution(){ + + vec2 tc0 = texcoords2 + vec2(-texOffset.s, -texOffset.t); + vec2 tc1 = texcoords2 + vec2( 0.0, -texOffset.t); + vec2 tc2 = texcoords2 + vec2(+texOffset.s, -texOffset.t); + vec2 tc3 = texcoords2 + vec2(-texOffset.s, 0.0); + + vec2 tc4 = texcoords2 + vec2( 0.0, 0.0); + vec2 tc5 = texcoords2 + vec2(+texOffset.s, 0.0); + vec2 tc6 = texcoords2 + vec2(-texOffset.s, +texOffset.t); + vec2 tc7 = texcoords2 + vec2( 0.0, +texOffset.t); + vec2 tc8 = texcoords2 + vec2(+texOffset.s, +texOffset.t); + + + vec4 rgba[9]; + rgba[0] = texture2D(texture, tc0); + rgba[1] = texture2D(texture, tc1); + rgba[2] = texture2D(texture, tc2); + rgba[3] = texture2D(texture, tc3); + rgba[4] = texture2D(texture, tc4); + rgba[5] = texture2D(texture, tc5); + rgba[6] = texture2D(texture, tc6); + rgba[7] = texture2D(texture, tc7); + rgba[8] = texture2D(texture, tc8); + + + vec4 convolution; + for (int i = 0; i < 9; i++) { + convolution += rgba[i]*mask[i]; + } + + + gl_FragColor = vec4(convolution.rgb, 1.0); +} + +//-------------------------------------------------------------------------- + +float luma(vec3 texel){ + return 0.299 * texel.r + 0.587 * texel.g + 0.114 * texel.b; + } + +float favg(vec3 texel){ + return (texel.r + texel.g + texel.b ) / 3.0; + } + +float HSV (vec3 texel){ + return max(max(texel.r,texel.g),texel.b); ; + } + +float HSL (vec3 texel){ + float CMax = max(max(texel.r,texel.g),texel.b); + float CMin = min(min(texel.r,texel.g),texel.b); + return (CMax + CMin) / 2.0 ; + } + +float Ftint(float channel, float color){ + float N = channel * (color / 255.0); + return N; + } + +void Coloring(){ + + vec4 texel = texture2D(texture, texcoords2); + + if(grey_scale == true){ + gl_FragColor = vec4((vec3(luma(texel.rgb))), 1.0); + }else if(average == true){ + gl_FragColor = vec4((vec3(favg(texel.rgb))), 1.0); + }else if(HSVV== true){ + gl_FragColor = vec4((vec3(HSV(texel.rgb))), 1.0); + }else if(HSLL== true){ + gl_FragColor = vec4((vec3(HSL(texel.rgb))), 1.0); + }else if(Tint == true){ + gl_FragColor = vec4(Ftint(texel.r,colorT.x),Ftint(texel.g,colorT.y),Ftint(texel.b,colorT.z),1.0); + }else{ + gl_FragColor = texel; + } +} + +//-------------------------------------------------------------------------- + +void main() { + + if(maskmode == true){ + Convolution(); + Coloring(); + }else if(coloringmode == true){ + Coloring(); + }else if(lensemode == true){ + Amplify(); + }else{ + gl_FragColor = texture2D(texture, texcoords2); + } + +} + +``` +{{< /details >}} \ No newline at end of file diff --git a/content/docs/shortcodes/Taller 3/Non Euclidean Geometry/_index.md b/content/docs/shortcodes/Taller 3/Non Euclidean Geometry/_index.md new file mode 100644 index 00000000..b79bdebf --- /dev/null +++ b/content/docs/shortcodes/Taller 3/Non Euclidean Geometry/_index.md @@ -0,0 +1,33 @@ +## Non Euclidean Geometry + +Se denomina geometría no euclidiana o no euclídea, a cualquier sistema formal de geometría cuyos postulados y proposiciones difieren en algún asunto de los establecidos por Euclides en su tratado Elementos. No existe un solo sistema de geometría no euclídea, sino muchos, aunque si se restringe la discusión a espacios homogéneos, en los que la curvatura del espacio es la misma en cada punto, en los que los puntos del espacio son indistinguibles, pueden distinguirse tres formulaciones​ de geometrías + +{{< details title="non_euclidean.frag" open=false >}} + +```javascript +precision mediump float; + +uniform sampler2D texture; +uniform vec2 u_resolution; + +void main() { + vec2 st = gl_FragCoord.xy / u_resolution; + gl_FragColor = texture2D(texture, vec2(st.s, 1.0 - st.t)); +} +``` + +### Cubo + +{{< p5-iframe sketch="/visual_computing/sketches/non_euclidean_cube.js" width="620" height="620" >}} + +### Piramide + +{{< p5-iframe sketch="/visual_computing/sketches/non_euclidean.js" width="620" height="620" >}} + +# Referencias + +{{< hint warning >}} + +- [1] _“GLSL Fragment Coordinate”_ **medium.com** https://medium.com/@vnflqkq/glsl-fragment-coordinate-gl-fragcoord-e792a8d32ea5 (Mar. 8, 2020). + +{{< /hint >}} diff --git a/content/docs/shortcodes/Taller 3/Photomosaic/_index.md b/content/docs/shortcodes/Taller 3/Photomosaic/_index.md new file mode 100644 index 00000000..08fd701f --- /dev/null +++ b/content/docs/shortcodes/Taller 3/Photomosaic/_index.md @@ -0,0 +1,168 @@ +## Fotomosaico + +El fotomosaico es una imagen, retrato o fotografía que se divide por figuras geométricas, generalmente +por cuadrados o rectángulos del mismo tamaño, esto con el fin de remplazar las mismas +por otros retratos, fotografías o imágenes que concuerden con los colores promedio que encierran las +figuras geométricas de la imagen original, logrando que al visualizar la +imagen de un punto lejano se logre ver como la original , pero que al ver de un punto cercano o al +hacer zoom se pueda percibir que se compone de otras imágenes. + +# Fotomosaico + +## Fotomosaico por hardware + +La implementación del fotomosaico se puede realizar a través de hardware, es decir, la construcción de un algoritmo que se encargue de convertir la imagen original en un mosaico de otras. + +En la funcion `preload` definimos el fragmento a usar demoninado `photomosaic.frag`, a partir de ahi al mosaico final vamos a definir ciertos parametros que van a ser obtenidos al momento de recorrer la imagen, aqui se comparan los texeles del color promedio que posee cada pixel de la imagen o video original. + +Los colores promedio de la imagen original son comparados con la imagen devuelta por el quadrille, haciendo uso de una tolerancia que va aumentando hasta encontrar el color mas cercano al del original y de esta forma ese color encontrado es el que se usa para llenar en la imagen que se muestra como resultado. + +{{< details title="photomosaic.js" open=false >}} + +```javascript + +``` + +{{< /details >}} + +{{< details title="photomosaic.frag" open=false >}} + +```javascript +precision mediump float; + +const int num_images = 40; + +// source (image or video) is sent by the sketch +uniform sampler2D source; + +// palette is sent by the sketch +uniform sampler2D palette; +// number of cols are sent by sketch +uniform float cols; + +uniform float lumas[num_images]; +uniform float red_palette[num_images]; +uniform float green_palette[num_images]; +uniform float blue_palette[num_images]; + +// toggles debug +uniform bool debug; + +// toggles coloring +uniform bool color_on; +uniform vec4 background; +uniform vec4 foreground; + +// target horizontal & vertical resolution +uniform float resolution; + +// interpolated color (same name and type as in vertex shader) +varying vec4 vVertexColor; +// interpolated texcoord (same name and type as in vertex shader) +varying vec2 vTexCoord; + +float luma(vec3 color) { + return (0.299 * color.r + 0.587 * color.g + 0.114 * color.b); +} + +void main() { + vec2 fontCoord = vTexCoord * resolution; + vec2 srcCoord = floor(fontCoord); + fontCoord = fontCoord - srcCoord; + srcCoord = srcCoord / vec2(resolution); + float mid = 1.0/(2.0*resolution); + srcCoord = srcCoord + vec2(mid); + + vec4 key = texture2D(source, srcCoord); + if (debug) { + gl_FragColor = key; + } else { + float lumakey = luma(key.rgb); + float selected = 0.0; + + bool complete = false; + for(float j = 0.02; j <= 0.5; j += 0.02){ + for(int i = 0 ; i < num_images; i ++) + { + if((red_palette[i]/255.0> (key.r - j) && red_palette[i]/255.0 < (key.r + j)) && (green_palette[i]/255.0> (key.g - j) && green_palette[i]/255.0 < (key.g + j)) && (blue_palette[i]/255.0> (key.b - j) && blue_palette[i]/255.0 < (key.b + j))){ + selected = float(i); + complete = true; + break; + } + } + if(complete){ + break; + } + } + + vec2 tile = vec2((floor(selected) + fontCoord.x) / cols, fontCoord.y); + + vec4 paletteTexel = texture2D(palette, tile); + gl_FragColor = paletteTexel; + } +} + +``` + +{{< /details >}} + +{{< details title="photomosaic.js" open=false >}} + +```javascript +function preload() { + image_src = loadImage('/visual_computing/imgs/car.jpg'); + video_src = createVideo(['/visual_computing/vid/drift.mp4']); + video_src.hide(); // by default video shows up in separate dom + mosaic = readShader('/visual_computing/sketches/shaders/photomosaic.frag'); + p = []; + for (let i = 1; i <= 40; i++) { + if (i.toString().length == 1) { + p.push(loadImage(`/visual_computing/imgs/cars/00000${i}.jpg`)); + } else { + p.push(loadImage(`/visual_computing/imgs/cars/0000${i}.jpg`)); + } + } +} + +function sample() { + if (pg.width !== SAMPLE_RES * imageCells.width) { + pg = createGraphics(SAMPLE_RES * imageCells.width, SAMPLE_RES); + mosaic.setUniform("cols", imageCells.width); + } + imageCells.sort({ + ascending: true, + cellLength: SAMPLE_RES, + mode: "LUMA", + }); + + luma = imageCells.saveLuma({ + cellLength: SAMPLE_RES, + }); + rgb = imageCells.saveRGB({ + cellLength: SAMPLE_RES, + }); + drawQuadrille(imageCells, { + graphics: pg, + cellLength: SAMPLE_RES, + outlineWeight: 0, + }); + mosaic.setUniform("palette", pg); + mosaic.setUniform("lumas", luma); + mosaic.setUniform("red_palette", rgb.r); + mosaic.setUniform("green_palette", rgb.g); + mosaic.setUniform("blue_palette", rgb.b); +} +``` + +{{< /details >}} + +{{< p5-iframe sketch="/visual_computing/sketches/photomosaic.js" lib1="/visual_computing/sketches/libraries/p5.shaderbox.js" lib2="/visual_computing/sketches/libraries/p5.quadrille.js" width="675" height="675" >}} + +# Referencias + +{{< hint warning >}} + +- [1] _“Shaders”_ **github.com** https://github.com/mattdesl/lwjgl-basics/wiki/Shaders (Mar. 8, 2020). + +{{< /hint >}} + diff --git a/content/docs/shortcodes/Taller 3/Procedural Texturing/_index.md b/content/docs/shortcodes/Taller 3/Procedural Texturing/_index.md new file mode 100644 index 00000000..7efa4cd8 --- /dev/null +++ b/content/docs/shortcodes/Taller 3/Procedural Texturing/_index.md @@ -0,0 +1,280 @@ +# Procedural Texturing + +## Problem statement + +El texturizado procedimental es un método para generar texturas superficiales utilizando procedimientos o algoritmos matemáticos. Esta tecnica tiene muchas ventajas como: el bajo costo de almacenamiento, la resolución ilimitada de texturas y el facil mapeo de texturas. + +Este metodo tiene varios usos como: crear efectos esteticos, aumentar el agarre mecanico, disminuir la resistencia aerodinamica y modelar superficies o representaciones volumétricas de elementos naturales como madera , mármol , granito , metal , piedra y otros. + +## Background + +Ahora bien, para aplicar una textura por medio del Procedural Texturing se necesita primero las coordenadas de textura, estas son las coordenadas de los vértices del objeto en un espacio 2D, que generalmente llamamos st o espacio de textura.Estas nos brindan un marco de referencia con el que podemos trabajar y crear todo tipo de patrones 2D, es decir que a lo largo del eje x, generalmente denotamos las coordenadas s y a lo largo del eje y las coordenadas t. + +Dicho lo anterior para asignar un elemento de la textura a un elemento de pantalla se buscan las coordenadas de textura de ese elemento tomando al espacio de textura como un espacio de coordenadas entre (0,0) y (1,1) como se muestra en la siguiente imagen: + +![](https://learn.microsoft.com/en-us/windows/win32/direct3d9/images/uvcoordinates.jpg) + +Esto se da para que una misma coordenada de textura se pueda asignar a diferentes texturas, como se ve en la siguiente imagen: + +![](https://learn.microsoft.com/en-us/windows/win32/direct3d9/images/texadr1.png) + +Donde la coordenada de textura es (0.5,1.0) y las texturas tienen diferentes tamaños por lo que la textura 1, se le asigna a texel (2,4) y La textura 2 se asigna a texel (3,6). + +La explicación simplificada del proeso de asignación de coordenadas de textura a espacio de pantalla se muestra en la siguiente imagen: + +![](https://www.scratchapixel.com/images/upload/shading-intro/shad-texturecoord.png?) + +En este ejemplo, un píxel, que se muestra a la izquierda de la ilustración, se idealiza en un cuadrado de color. Las direcciones de las cuatro esquinas del píxel se asignan a la primitiva 3D en el espacio del objeto(La forma del píxel a menudo se distorsiona debido a la forma de la primitiva en el espacio 3D y al ángulo de visión), las esquinas del área de la superficie de la primitiva que corresponden a las esquinas del píxel se mapean en el espacio de textura. El proceso de mapeo vuelve a distorsionar la forma del píxel, lo cual es común. El valor de color final del píxel se calcula a partir de los téxeles en la región a la que se asigna el píxel. + +## Code + +A continuación algunos ejemplos: + +Aplicamos el siguiente patron a una esfera: + +![](/visual_computing/imgs/patron.JPG) + +Resultado: + +{{< p5-iframe sketch="/visual_computing/sketches/procedural_texturing.js" width="620" height="620" >}} + +{{< details "**CODIGO:** procedural_texturing.js" close >}} +**C**odigo generado usando el editor web de **P5.js**. +```javascript +let theShader; +let shaderTexture; + +let theta = 0; + +let x; +let y; +let outsideRadius = 200; +let insideRadius = 100; + + +function preload(){ + + theShader = loadShader('/visual_computing/sketches/shaders/shader.vert','/visual_computing/sketches/shaders/shader.frag'); +} + +function setup() { + + createCanvas(windowWidth*0.95, windowHeight*0.95, WEBGL); + noStroke(); + + shaderTexture = createGraphics(710, 400, WEBGL); + + shaderTexture.noStroke(); + +} + +function draw() { + + shaderTexture.shader(theShader); + + theShader.setUniform("u_resolution", [width, height]); + theShader.setUniform("u_mouse", [mouseX>0?mouseX:0.0, mouseY>0?mouseY:0.0]); + + + shaderTexture.rect(0,0,width,height); + + background("blue"); + orbitControl(); + + texture(shaderTexture); + + push(); + rotateZ(theta * mouseX * 0.0001); + rotateX(theta * mouseX * 0.0001); + rotateY(theta * mouseX * 0.0001); + theta += 0.01; + sphere(125); + pop(); +} + + +function windowResized(){ + resizeCanvas(windowWidth, windowHeight); +} +``` +{{< /details >}} + +{{< details "**CODIGO:** shader.frag" close >}} +**C**odigo generado usando el editor web de **P5.js**. +```javascript +#ifdef GL_ES +precision mediump float; +#endif + +#define PI 3.14159265358979323846 + +uniform vec2 u_resolution; +uniform float u_time; + +vec2 rotate2D (vec2 _st, float _angle) { + _st -= 0.5; + _st = mat2(cos(_angle),-sin(_angle), + sin(_angle),cos(_angle)) * _st; + _st += 0.5; + return _st; +} + +vec2 tile (vec2 _st, float _zoom) { + _st *= _zoom; + return fract(_st); +} + +vec2 rotateTilePattern(vec2 _st){ + + _st *= 4.0; + + // Give each cell an index number + // according to its position + float index = 0.0; + index += step(1., mod(_st.x,2.0)); + index += step(1., mod(_st.y,2.0))*2.0; + + _st = fract(_st); + + if(index == 1.0){ + // Rotate cell 1 by -90 degrees + _st = rotate2D(_st,PI*-0.5); + }else if(index == 2.0){ + // Rotate cell 2 by -90 degrees + _st = rotate2D(_st,PI*-0.5); + } + return _st; +} + +void main (void) { + + vec2 st = gl_FragCoord.xy/u_resolution.xy; + + st = tile(st,3.0); + st = rotateTilePattern(st); + + gl_FragColor = vec4(vec3(step(st.x,st.y)),1.0); +} + +//Fuente: https://thebookofshaders.com/09/ +``` +{{< /details >}} + +Aplicamos el siguiente patron a un cubo: + +{{< p5-iframe sketch="/visual_computing/sketches/procedural_texturing_3.js" width="620" height="620" >}} + +Resultado: + +{{< p5-iframe sketch="/visual_computing/sketches/procedural_texturing_2.js" width="620" height="620" >}} + +{{< details "**CODIGO:** procedural_texturing_2.js" close >}} +**C**odigo generado usando el editor web de **P5.js**. +```javascript +let theShader; +let shaderTexture; + +let theta = 0; + +let x; +let y; +let outsideRadius = 200; +let insideRadius = 100; + + +function preload(){ + theShader = loadShader('/visual_computing/sketches/shaders/shader_2.vert','/visual_computing/sketches/shaders/shader_2.frag'); +} + +function setup() { + + createCanvas(windowWidth*0.95, windowHeight*0.95, WEBGL); + noStroke(); + + shaderTexture = createGraphics(710, 400, WEBGL); + + shaderTexture.noStroke(); +} + +function draw() { + + shaderTexture.shader(theShader); + + theShader.setUniform("u_resolution", [width, height]); + theShader.setUniform("u_time", millis() / 1000.0); + theShader.setUniform("u_mouse", [mouseX>0?mouseX:0.0, mouseY>0?mouseY:0.0]); + + + shaderTexture.rect(0,0,width,height); + + background(40); + + orbitControl(); + + texture(shaderTexture); + + push(); + rotateX(frameCount * 0.01); + rotateY(frameCount * 0.005); + box(width / 4); + pop(); +} + + +function windowResized(){ + resizeCanvas(windowWidth, windowHeight); +} + +//Fuente: https://github.com/nakednous/p5jsShaderExamples +``` +{{< /details >}} + +{{< details "**CODIGO:** shader_2.frag" close >}} +**C**odigo generado usando el editor web de **P5.js**. +```javascript +#ifdef GL_ES +precision mediump float; +#endif + +#define PI 3.14159265359 + +uniform vec2 u_resolution; +uniform vec2 u_mouse; +uniform float u_time; + +float plot(vec2 st, float pct){ + return 0.0 ; +} + +void main() { + vec2 st = gl_FragCoord.xy/u_resolution; + + vec2 mt = vec2(sin(u_time),cos(u_time)); + + float y = sin(st.x*PI*3.000); + float altura = abs( pow(mt.x*cos(st.x*PI*2.4),3.0) + +pow(mt.y*sin(st.y*PI*2.040),2.0)); + vec3 color = vec3(altura); + + float pct = plot(st,y); + color = (1.0-pct)*color+pct*vec3(0.524,0.570,0.565); + + gl_FragColor = vec4(color.rg,1.144,0.944); +} +//Fuente: https://www.shadertoy.com/ +``` +{{< /details >}} + +## Conclusiones + +Este no solo es un metodo sencillo sino tambien uno muy practico con el cual se pueden replican un sinfin de texturas. + +## Referencias + +https://learn.microsoft.com/en-us/windows/win32/direct3d9/texture-coordinates + +https://github.com/nakednous/p5jsShaderExamples + +https://thebookofshaders.com/09/ + +https://www.shadertoy.com/ \ No newline at end of file diff --git a/content/docs/shortcodes/Taller 3/Spatial Coherence/_index.md b/content/docs/shortcodes/Taller 3/Spatial Coherence/_index.md new file mode 100644 index 00000000..5d3c3aa9 --- /dev/null +++ b/content/docs/shortcodes/Taller 3/Spatial Coherence/_index.md @@ -0,0 +1,90 @@ +# Spatial Coherence + +## Problem statement + +La coherencia espacial es el efecto visual por el cual los colores percibidos tienden a variar de manera proporcional a la distancia dentro de una determinada región de interes en la escena. + +## Background + +Por otra parte desde la perspectiva de la fisica, la coherencia espacial es la relación cruzada entre dos puntos en una onda en todo momento. Además de tambien ser una fuerte correlación entre los campos electricos en diferentes lugares, los cuales oscilan de forma correlacionada incluso si la estructura temporal se complica por una superposición de diferentes componentes de frecuencia. Este es un requisito fundamental para la direccionalidad de los rayos laser. + +### Ejemplo +![](/visual_computing/imgs/resultado.JPG) + +## Codigo + +https://editor.p5js.org/acardenaso/sketches/KHkc3J1pF + +{{< details "**CODIGO:** sketch.js" close >}} +**C**odigo generado usando el editor web de **P5.js**. +```javascript +let myShader +let img; + +function preload(){ +myShader = loadShader('shader.vert', 'shader.frag'); + let num = int(random(1, 31)); + //if(num == 1){ + img = loadImage('1.jpg'); + //} + + /*if(num == 2){ + img = loadImage('2.jpg'); + } + + if(num == 3){ + img = loadImage('3.jpg'); + }*/ +} + +function setup() { + createCanvas(windowWidth, windowHeight, WEBGL); + noStroke(); +} + +function draw() { + background(220); + + myShader.setUniform('tex', img); + myShader.setUniform('tiles', map(mouseX, 0, width, 100, 1)); + + shader(myShader); + rect(0, 0, width, height); +} +``` +{{< /details >}} + +{{< details "**CODIGO:** shader.js" close >}} +**C**odigo generado usando el editor web de **P5.js**. +```javascript +precision highp float; + +varying vec2 vUV; + +uniform sampler2D tex; +uniform float tiles; + +void main() { + vec2 uv = vUV; + uv.y = 1.0 - uv.y; + + uv *= tiles; + + uv = floor(uv); + + uv /= tiles; + + vec4 texColor = texture2D(tex, uv); + + gl_FragColor = texColor; +} +``` +{{< /details >}} + +## Referencias + +https://editor.p5js.org/oshoham/sketches/aAc4D3BBma + +https://byjus.com/jee/coherence-and-coherent-sources/#:~:text=Spatial%20coherence%20can%2C%20therefore%2C%20be,a%20wave%20at%20all%20times. + +https://www.rp-photonics.com/coherence.html \ No newline at end of file diff --git a/content/docs/shortcodes/Taller 3/Texturing/_index.md b/content/docs/shortcodes/Taller 3/Texturing/_index.md new file mode 100644 index 00000000..3b11298d --- /dev/null +++ b/content/docs/shortcodes/Taller 3/Texturing/_index.md @@ -0,0 +1,476 @@ +## Texturing + +La **texturizacion** es el proceso por el cual una imagen o mapa de bits es **mapeado** sobre un objeto 3D o una superficie, esto se logra trabajando con los sistemas coorddenados de las figuras y de la textura, la cual mediante el **shader** y la **GPU** son procesados haciendo uso de **GLSL** y algunos paradigmas de programacion, como programacion en paralelo. + +### 1. **Visualizacion UV** + +La visualizacion UV nos permite mostrar una textura sobre un espacio particular. + +{{< hint info >}} +**Ejercicio 1:** +Redefinir las coordenas de la figura texturizada para invertir la orientacion vertical de la imagen. +{{< /hint >}} + +{{< p5-iframe sketch="/visual_computing/sketches/uvoriginal.js" width="325" height="325" >}} + +{{< hint warning >}} +**Solucion Ejercicio 1:** +Redefinir las coordenadas [u] y [v] de los vertex definidos en uv.js para que cada punto del clip space mapeara a su inverso en el texture space. +{{< /hint >}} + +{{< details "**CODIGO:** uv_inverse.js" close >}} +```javascript +let uvShader; + +function preload() { + uvShader = readShader('/visual_computing/sketches/shaders/uv.frag', { matrices: Tree.NONE, varyings: Tree.texcoords2 }); +} + +function setup() { + createCanvas(300, 300, WEBGL); + noStroke(); + shader(uvShader); + textureMode(NORMAL); +} + +function draw() { + background(0); + beginShape(); + vertex(-1, -1, 0, 0, 1); + vertex( 1, -1, 0, 1, 1); + vertex( 1, 1, 0, 1, 0); + vertex(-1, 1, 0, 0, 0); + endShape(); +} +``` +{{< /details >}} + +{{< details "**CODIGO:** uv.frag" close >}} +```glsl +precision mediump float; +varying vec2 texcoords2; + +void main() { + gl_FragColor = vec4(texcoords2.xy, 0.0, 1.0); +} +``` +{{< /details >}} + +{{< p5-iframe sketch="/visual_computing/sketches/uv_inverse.js" width="325" height="325" >}} + +--- + +### 2. **3D** + +La visualizacion 3D de espaciosUV nos permite mostrar una textura sobre un objeto particular en un espacio que permite la interaccion **3D**, sin embargo esto no altera en demasia . + + +{{< hint info >}} +**Ejercicio 2.1:** +Incluir el canal **azul** en la visualizacion UV, ya sea **Azul + Verde** ó **Azul + Rojo**. +{{< /hint >}} + +{{< hint warning >}} +**Solucion Ejercicio 2.1:** +Modificar el shader para que evalue 2 variables y reajuste el color dependiendo de una de las opciones seleccionadas, modificando uno de los canales dependiendo de la opcion. +{{< /hint >}} + +{{< p5-iframe sketch="/visual_computing/sketches/uvplus.js" width="325" height="340" >}} + + +{{< details "**CODIGO:** uvplus.js" close >}} +```javascript +let easycam; +let uvShader; +let c1, c2; + +let rtb = false, gtb = false; + +function preload() { + uvShader = readShader('/visual_computing/sketches/shaders/uvplus.frag',{ matrices: Tree.pmvMatrix, varyings: Tree.texcoords2 }); +} + +function setup() { + createCanvas(300, 300, WEBGL); + textureMode(NORMAL); + c1 = createCheckbox('Red To Blue', false); + c2 = createCheckbox('Green To Blue', false); + c1.position(10, 310); + c2.position(150, 310); + shader(uvShader); +} + +function draw() { + background(200); + orbitControl(); + axes(); + push(); + noStroke(); + quad(-width / 2, -height / 2, width / 2, -height / 2, + width / 2, height / 2, -width / 2, height / 2); + pop(); + + if(c1.checked()){ + uvShader.setUniform('rtb',true) + uvShader.setUniform('gtb',false) + }else if(c2.checked()){ + uvShader.setUniform('rtb',false) + uvShader.setUniform('gtb',true) + }else{ + uvShader.setUniform('rtb',false) + uvShader.setUniform('gtb',false) + } +} + +function mouseWheel(event) { + return false; +} +``` +{{< /details >}} + +{{< details "**CODIGO:** uvplus.frag" close >}} +```glsl +precision mediump float; + +uniform bool rtb; +uniform bool gtb; +varying vec2 texcoords2; + +void main() { + if(rtb==true){ + gl_FragColor = vec4(0.0 ,texcoords2.y,texcoords2.x, 1.0); + }else if(gtb==true){ + gl_FragColor = vec4(texcoords2.x , 0.0, texcoords2.y, 1.0); + }else{ + gl_FragColor = vec4(texcoords2.xy, 0.0, 1.0); + } +} +``` +{{< /details >}} + +--- + +{{< hint info >}} +**Ejercicio 2.2:** +Utilizar figuras diferentes a **Quad** como filtros de pantalla. +{{< /hint >}} + +{{< hint warning >}} +**Solucion Ejercicio 2.2:** +Modificar las figuras mediante la definicion de metodos y figuras de P5, añadir el control de opacidad y el cambio de canales **[RGB]**. +{{< /hint >}} + +{{< p5-iframe sketch="/visual_computing/sketches/screen.js" width="475" height="475" >}} + + +{{< details "**CODIGO:** screen.js" close >}} +```javascript +let easycam; +let uvShader; +let opacity; + +let c1, c2; + +let rtb = false, gtb = false; + +function preload() { + uvShader = readShader('/visual_computing/sketches/shaders/screen.frag',{ matrices: Tree.pmvMatrix, varyings: Tree.texcoords2 }); +} + +function setup() { + createCanvas(450, 450, WEBGL); + + // easycam stuff + let state = { + distance: 250, + center: [0, 0, 0], + rotation: [0, 0, 0, 1], + }; + easycam = createEasyCam(); + easycam.state_reset = state; + easycam.setState(state, 2000); + textureMode(NORMAL); + opacity = createSlider(0, 1, 0.5, 0.01); + opacity.position(10, 25); + opacity.style('width', '280px'); + + c1 = createCheckbox('R To B', false); + c2 = createCheckbox('G To B', false); + c1.position(100, 10); + c2.position(200, 10); + + sel = createSelect(); + sel.position(10, 10); + sel.option('Quad'); + sel.option('Triangle'); + sel.option('Circle'); + sel.selected('Quad'); + +} + +function draw() { + background(200); + + resetShader(); + + axes(); + grid(); + translate(0, -70); + rotateY(0.5); + fill(color(255, 0, 255, 125)); + box(30, 50); + translate(70, 70); + fill(color(0, 255, 255, 125)); + sphere(30, 50); + + shader(uvShader); + + uvShader.setUniform('opacity', opacity.value()); + + beginHUD(); + + noStroke(); + + if(sel.value() == "Quad"){ + quad(0, 0, width, 0, width, height, 0, height); + }else if(sel.value() == "Triangle"){ + triangle(0,0,width,0,width/2,height) + }else if (sel.value() == "Circle"){ + circle(width/2,height/2,width) + } + + if(c1.checked()){ + uvShader.setUniform('rtb',true) + uvShader.setUniform('gtb',false) + }else if(c2.checked()){ + uvShader.setUniform('rtb',false) + uvShader.setUniform('gtb',true) + }else{ + uvShader.setUniform('rtb',false) + uvShader.setUniform('gtb',false) + } + + endHUD(); +} + +function mouseWheel(event) { + //comment to enable page scrolling + return false; +} +``` +{{< /details >}} + +{{< details "**CODIGO:** screen.frag" close >}} +```glsl +precision mediump float; + +uniform bool rtb; +uniform bool gtb; +uniform float opacity; +varying vec2 texcoords2; + +void main() { + if(rtb==true){ + gl_FragColor = vec4(0.0 ,texcoords2.y,texcoords2.x, opacity); + }else if(gtb==true){ + gl_FragColor = vec4(texcoords2.x , 0.0, texcoords2.y, opacity); + }else{ + gl_FragColor = vec4(texcoords2.xy, 0.0, opacity); + } +} +``` +{{< /details >}} + +--- +### 3. **Muestreo de Texturas** + +Los efectos que puedan aplicarse a una imagen requieren utilizar coordenaddas dadas, las coordenadas **texcoords2** y los **texels** permiten realizar operaciones pixel a pixel haciendo uso de la GPU . + +{{< hint info >}} +**Ejercicio 3.1 y 3.2:** +* Implementar heraamientas de iluminacion i color tales como *HSV valor V, HSL luminancia L, Promedio de componentes*. +* Implementar el tintado de texturas mezclando el colo y los datos interpolados de los texeles. +{{< /hint >}} + +{{< hint warning >}} +**Solucion Ejercicio 3.1 y 3.2:** +Para modificar la imagen se opera matematicamente los valores que se obtienen en los texels **[Canales RGBA]** , o se modifican de plano para que el shader los procese nuevamente. +{{< /hint >}} + +{{< p5-iframe sketch="/visual_computing/sketches/tools.js" width="725" height="525" >}} + +{{< details "**CODIGO:** tools.js" close >}} +```javascript +let lumaShader; +let img; +let grey_scale; +let average; +let HSVV; +let Tint; +let ColorT; + +function preload() { + lumaShader = readShader('/visual_computing/sketches/shaders/colors.frag',{ varyings: Tree.texcoords2}); + img = loadImage('/visual_computing/imgs/car.jpg'); +} + +function drawControls(enabled){ + if(enabled){ + colorT = createColorPicker(color(255,255,255)); + colorT.position(125, 10); + } +} + +function setup() { + createCanvas(700, 500, WEBGL); + noStroke(); + textureMode(NORMAL); + + sel = createSelect(); + sel.position(10, 10); + sel.option('None'); + sel.option('Luma'); + sel.option('Average'); + sel.option('HSV Value V'); + sel.option('HSL Value L'); + sel.option('Tint'); + + sel.selected('None'); + + drawControls(true); + + + +} + +function draw() { + background(0); + + if(sel.value()=="None"){ + shader(lumaShader); + lumaShader.setUniform('texture', img); + lumaShader.setUniform('HSVV',false); + lumaShader.setUniform('HSLL',false); + lumaShader.setUniform('grey_scale',false); + lumaShader.setUniform('average',false); + + }else if(sel.value()=="Luma"){ + shader(lumaShader); + lumaShader.setUniform('grey_scale',true); + lumaShader.setUniform('average',false); + lumaShader.setUniform('HSVV',false); + lumaShader.setUniform('HSLL',false); + lumaShader.setUniform('texture', img); + + }else if(sel.value()=="Average"){ + shader(lumaShader); + lumaShader.setUniform('average',true); + lumaShader.setUniform('grey_scale',false); + lumaShader.setUniform('HSVV',false); + lumaShader.setUniform('HSLL',false); + lumaShader.setUniform('texture', img); + + }else if(sel.value() =="HSV Value V"){ + shader(lumaShader); + lumaShader.setUniform('HSVV',true); + lumaShader.setUniform('HSLL',false); + lumaShader.setUniform('average',false); + lumaShader.setUniform('grey_scale',false); + lumaShader.setUniform('texture', img); + + }else if(sel.value() =="HSL Value L"){ + shader(lumaShader); + lumaShader.setUniform('HSLL',true); + lumaShader.setUniform('HSVV',false); + lumaShader.setUniform('average',false); + lumaShader.setUniform('grey_scale',false); + lumaShader.setUniform('texture', img); + + }else if(sel.value() =="Tint"){ + shader(lumaShader); + lumaShader.setUniform('Tint',true); + lumaShader.setUniform('HSLL',false); + lumaShader.setUniform('HSVV',false); + lumaShader.setUniform('average',false); + lumaShader.setUniform('grey_scale',false); + lumaShader.setUniform('texture', img); + + let RC = colorT.color(); + lumaShader.setUniform('colorT',[red(RC),green(RC),blue(RC),1.0]); + + } + + quad(-width / 2, -height / 2, width / 2, -height / 2, width / 2, height / 2, -width / 2, height / 2); +} +``` +{{< /details >}} + +{{< details "**CODIGO:** colors.frag" close >}} +```glsl +precision mediump float; + +uniform bool grey_scale; +uniform bool average; +uniform bool HSVV; +uniform bool HSLL; +uniform bool Tint; + +uniform vec4 colorT; + +uniform sampler2D texture; + +varying vec2 texcoords2; + +float luma(vec3 texel) { + return 0.299 * texel.r + 0.587 * texel.g + 0.114 * texel.b; +} + +float favg(vec3 texel){ + return (texel.r + texel.g + texel.b ) / 3.0; +} + +float HSV (vec3 texel){ + return max(max(texel.r,texel.g),texel.b); ; +} + +float HSL (vec3 texel){ + float CMax = max(max(texel.r,texel.g),texel.b); + float CMin = min(min(texel.r,texel.g),texel.b); + return (CMax + CMin) / 2.0 ; +} + +float Ftint(float channel, float color){ + float N = channel * (color / 255.0); + return N; +} + + +void main() { + + vec4 texel = texture2D(texture, texcoords2); + + if(grey_scale == true){ + gl_FragColor = vec4((vec3(luma(texel.rgb))), 1.0); + }else if(average == true){ + gl_FragColor = vec4((vec3(favg(texel.rgb))), 1.0); + }else if(HSVV== true){ + gl_FragColor = vec4((vec3(HSV(texel.rgb))), 1.0); + }else if(HSLL== true){ + gl_FragColor = vec4((vec3(HSL(texel.rgb))), 1.0); + }else if(Tint == true){ + gl_FragColor = vec4(Ftint(texel.r,colorT.x),Ftint(texel.g,colorT.y),Ftint(texel.b,colorT.z),1.0); + }else{ + gl_FragColor = texel; + } + +} +``` +{{< /details >}} + +{{< hint danger >}} +**Referencias:** +* **[Speeding Up tint() in p5]:** https://www.davepagurek.com/blog/p5-tint/ +* **[HSL & HSV]:** https://en.wikipedia.org/wiki/HSL_and_HSV#Disadvantages +* **[Blend Modes]:** https://en.wikipedia.org/wiki/Blend_modes#Overlay +* **[P5.js]:** https://p5js.org/es/reference/ +{{< /hint >}} diff --git a/content/docs/shortcodes/Taller 3/_index.md b/content/docs/shortcodes/Taller 3/_index.md new file mode 100644 index 00000000..65cdaac8 --- /dev/null +++ b/content/docs/shortcodes/Taller 3/_index.md @@ -0,0 +1,11 @@ +--- +bookCollapseSection: true +--- + +# Shaders + +## Objetivo + +X + +{{
}} diff --git a/content/docs/shortcodes/buttons.md b/content/docs/shortcodes/buttons.md deleted file mode 100644 index c2ef1e75..00000000 --- a/content/docs/shortcodes/buttons.md +++ /dev/null @@ -1,13 +0,0 @@ -# Buttons - -Buttons are styled links that can lead to local page or external link. - -## Example - -```tpl -{{}}Get Home{{}} -{{}}Contribute{{}} -``` - -{{< button relref="/" >}}Get Home{{< /button >}} -{{< button href="https://github.com/alex-shpak/hugo-book" >}}Contribute{{< /button >}} diff --git a/content/docs/shortcodes/columns.md b/content/docs/shortcodes/columns.md deleted file mode 100644 index 0b8fde83..00000000 --- a/content/docs/shortcodes/columns.md +++ /dev/null @@ -1,45 +0,0 @@ -# Columns - -Columns help organize shorter pieces of content horizontally for readability. - - -```html -{{}} -# Left Content -Lorem markdownum insigne... - -<---> - -# Mid Content -Lorem markdownum insigne... - -<---> - -# Right Content -Lorem markdownum insigne... -{{}} -``` - -## Example - -{{< columns >}} -## Left Content -Lorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat -stringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa -protulit, sed sed aere valvis inhaesuro Pallas animam: qui _quid_, ignes. -Miseratus fonte Ditis conubia. - -<---> - -## Mid Content -Lorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat -stringit, frustra Saturnius uteroque inter! - -<---> - -## Right Content -Lorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat -stringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa -protulit, sed sed aere valvis inhaesuro Pallas animam: qui _quid_, ignes. -Miseratus fonte Ditis conubia. -{{< /columns >}} diff --git a/content/docs/shortcodes/details.md b/content/docs/shortcodes/details.md deleted file mode 100644 index 3d5aedc4..00000000 --- a/content/docs/shortcodes/details.md +++ /dev/null @@ -1,22 +0,0 @@ -# Details - -Details shortcode is a helper for `details` html5 element. It is going to replace `expand` shortcode. - -## Example - -```tpl -{{}} -## Markdown content -Lorem markdownum insigne... -{{}} -``` - -{{< details "Title" open >}} -## Markdown content -Lorem markdownum insigne... -{{< /details >}} - -{{< details "Title" >}} -## Markdown content -Lorem markdownum insigne... -{{< /details >}} diff --git a/content/docs/shortcodes/hints.md b/content/docs/shortcodes/hints.md deleted file mode 100644 index 3477113d..00000000 --- a/content/docs/shortcodes/hints.md +++ /dev/null @@ -1,32 +0,0 @@ -# Hints - -Hint shortcode can be used as hint/alerts/notification block. -There are 3 colors to choose: `info`, `warning` and `danger`. - -```tpl -{{}} -**Markdown content** -Lorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat -stringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa -{{}} -``` - -## Example - -{{< hint info >}} -**Markdown content** -Lorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat -stringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa -{{< /hint >}} - -{{< hint warning >}} -**Markdown content** -Lorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat -stringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa -{{< /hint >}} - -{{< hint danger >}} -**Markdown content** -Lorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat -stringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa -{{< /hint >}} diff --git a/content/docs/shortcodes/katex.md b/content/docs/shortcodes/katex.md deleted file mode 100644 index dd0a8591..00000000 --- a/content/docs/shortcodes/katex.md +++ /dev/null @@ -1,25 +0,0 @@ -# KaTeX - -KaTeX shortcode let you render math typesetting in markdown document. See [KaTeX](https://katex.org/) - -## Example - -{{< columns >}} -{{< highlight latex >}} -{{}} -f(x) = \int_{-\infty}^\infty\hat f(\xi)\,e^{2 \pi i \xi x}\,d\xi -{{}} -{{< /highlight >}} -<---> -{{< katex display >}} -f(x) = \int_{-\infty}^\infty\hat f(\xi)\,e^{2 \pi i \xi x}\,d\xi -{{< /katex >}} -{{< /columns >}} - -## Display Mode Example - -Here is some inline example: {{< katex >}}\pi(x){{< /katex >}}, rendered in the same line. And below is `display` example, having `display: block` -{{< katex display >}} -f(x) = \int_{-\infty}^\infty\hat f(\xi)\,e^{2 \pi i \xi x}\,d\xi -{{< /katex >}} -Text continues here. diff --git a/content/docs/shortcodes/mermaid.md b/content/docs/shortcodes/mermaid.md deleted file mode 100644 index a8819d9f..00000000 --- a/content/docs/shortcodes/mermaid.md +++ /dev/null @@ -1,41 +0,0 @@ -# Mermaid Chart - -[MermaidJS](https://mermaid-js.github.io/) is library for generating svg charts and diagrams from text. - -{{< hint info >}} -**Override Mermaid Initialization Config** - -To override the [initialization config](https://mermaid-js.github.io/mermaid/#/Setup) for Mermaid, -create a `mermaid.json` file in your `assets` folder! -{{< /hint >}} - -## Example - -{{< columns >}} -{{< highlight tpl1 >}} -{{}} -stateDiagram-v2 - State1: The state with a note - note right of State1 - Important information! You can write - notes. - end note - State1 --> State2 - note left of State2 : This is the note to the left. -{{}} -{{< /highlight >}} - -<---> - -{{< mermaid >}} -stateDiagram-v2 - State1: The state with a note - note right of State1 - Important information! You can write - notes. - end note - State1 --> State2 - note left of State2 : This is the note to the left. -{{< /mermaid >}} - -{{< /columns >}} diff --git a/content/docs/shortcodes/p5/_index.md b/content/docs/shortcodes/p5/_index.md deleted file mode 100644 index 0cf152de..00000000 --- a/content/docs/shortcodes/p5/_index.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -bookCollapseSection: true ---- - -# p5 - -`p5` helps add [p5 sketches](https://p5js.org/) into your book. There are two types of `p5` [shortcodes](https://gohugo.io/content-management/shortcodes/) according to the html element used to embed them. - -## Types - -{{
}} diff --git a/content/docs/shortcodes/p5/div.md b/content/docs/shortcodes/p5/div.md deleted file mode 100644 index 2277ea5f..00000000 --- a/content/docs/shortcodes/p5/div.md +++ /dev/null @@ -1,206 +0,0 @@ -p5 `div` [shortcodes](https://gohugo.io/content-management/shortcodes/) embed [p5.js](https://p5js.org/) code within a [div element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div). There are two p5 `div` shortcodes: [p5-div](#p5-div) and [p5-instance-div](#p5-instance-div). - -# p5-div - -```html -{{}} -``` - -All parameters are optional but `sketch`. Default values are shown in the above snippet but for `libs*`. Up to `lib5` libs may be specified. - -## Scintillating grid - -Look at [this](https://mathworld.wolfram.com/ScintillatingGridIllusion.html) and also [this](https://www.illusionsindex.org/i/scintillating-grid) among many more references there are. - -{{< details title="p5-div markdown" open=false >}} -{{< highlight html >}} -{{}} -{{< /highlight >}} -{{< /details >}} - -{{< p5-div sketch="/showcase/sketches/scintillating.js" >}} - -# p5-instance-div - -```html -{{}} - // inline sketch code -{{< /p5-instance-div */>}} -``` - -{{< hint warning >}} -Note that the inline `sketch` should be coded in [p5 instance mode](https://github.com/processing/p5.js/wiki/Global-and-instance-mode) syntax. -{{< /hint >}} - -All parameters are optional but `id`. Default values are shown in the above snippet but for `libs*`. Up to `lib5` libs may be specified. - -## Lilac chaser - -Look at [this](https://en.wikipedia.org/wiki/Lilac_chaser) introductory reference. - -{{< details title="p5-instance-div markdown" open=false >}} -{{< highlight md >}} -{{}} - // Adapted from [this](https://github.com/VisualComputing/Cognitive/blob/gh-pages/sketches/lilacChaser.js) - let jump = 0; - let count = 0; - - p5.setup = function() { - p5.createCanvas(400, 400); - p5.frameRate(7); - }; - - function drawBlurCircles(x, y, r) { - p5.push(); - p5.noStroke(); - var opc = 0.4; - var step = 3.0/r; - - for (var i = r; i > 0; i-=1.5) { - if (opc < 5) { - opc += step; - p5.fill(255, 20, 180, opc); - } - p5.ellipse(x, y, i, i); - } - p5.pop(); - }; - - p5.draw = function() { - p5.background(200); - var numCircles = 12; - var stepAngle = 360.0/numCircles; - p5.push(); - p5.translate(p5.width/2.0, p5.height/2.0); - for (var i = 0; i < 360; i = i + stepAngle) { - if (i != jump) { - p5.push(); - p5.rotate(p5.radians(i)); - drawBlurCircles(120, 0, 60); - p5.pop(); - } - } - if( !p5.mouseIsPressed ) { - jump = (jump + stepAngle)%360; - } - p5.push(); - p5.strokeWeight(1.5); - p5.line(-7, 0, 7, 0); - p5.line(0, -7, 0, 7); - p5.pop(); - p5.pop(); - } -{{< /p5-instance-div */>}} -{{< /highlight >}} -{{< hint warning >}} -Note that `p5` should be the name to be used for the sketch object variable. -{{< /hint >}} -{{< /details >}} - -{{< p5-instance-div id="pacman" >}} - let jump = 0; - let count = 0; - - p5.setup = function() { - p5.createCanvas(380, 380); - p5.frameRate(7); - }; - - function drawBlurCircles(x, y, r) { - p5.push(); - p5.noStroke(); - var opc = 0.4; - var step = 3.0/r; - - for (var i = r; i > 0; i-=1.5) { - if (opc < 5) { - opc += step; - p5.fill(255, 20, 180, opc); - } - p5.ellipse(x, y, i, i); - } - p5.pop(); - }; - - p5.draw = function() { - p5.background(200); - var numCircles = 12; - var stepAngle = 360.0/numCircles; - p5.push(); - p5.translate(p5.width/2.0, p5.height/2.0); - for (var i = 0; i < 360; i = i + stepAngle) { - if (i != jump) { - p5.push(); - p5.rotate(p5.radians(i)); - drawBlurCircles(120, 0, 60); - p5.pop(); - } - } - if( !p5.mouseIsPressed ) { - jump = (jump + stepAngle)%360; - } - p5.push(); - p5.strokeWeight(1.5); - p5.line(-7, 0, 7, 0); - p5.line(0, -7, 0, 7); - p5.pop(); - p5.pop(); - } -{{< /p5-instance-div >}} - -## Video on canvas - -Adapted from [here](https://p5js.org/examples/dom-video-canvas.html). Don't forget to checkout also the [video on dom](https://p5js.org/examples/dom-video.html) example. - -{{< details title="p5-instance-div markdown" open=false >}} -{{< highlight md >}} -{{}} - let fingers; - - p5.setup = function() { - p5.createCanvas(710, 400); - // specify multiple formats for different browsers - fingers = p5.createVideo(['/showcase/sketches/fingers.mov', '/showcase/sketches/fingers.webm']); - fingers.hide(); // by default video shows up in separate dom - // element. hide it and draw it to the canvas instead - }; - - p5.draw = function() { - p5.background(150); - p5.image(fingers, 10, 10); // draw the video frame to canvas - p5.filter(p5.GRAY); - p5.image(fingers, 150, 150); // draw a second copy to canvas - }; - - p5.mousePressed = function() { - fingers.loop(); // set the video to loop and start playing - } -{{< /p5-instance-div */>}} -{{< /highlight >}} -{{< hint warning >}} -Note that `p5` should be the name to be used for the sketch object variable. -{{< /hint >}} -{{< /details >}} - -{{< p5-instance-div id="video" >}} - let fingers; - - p5.setup = function() { - p5.createCanvas(710, 400); - // specify multiple formats for different browsers - fingers = p5.createVideo(['/showcase/sketches/fingers.mov', '/showcase/sketches/fingers.webm']); - fingers.hide(); // by default video shows up in separate dom - // element. hide it and draw it to the canvas instead - }; - - p5.draw = function() { - p5.background(150); - p5.image(fingers, 10, 10); // draw the video frame to canvas - p5.filter(p5.GRAY); - p5.image(fingers, 150, 150); // draw a second copy to canvas - }; - - p5.mousePressed = function() { - fingers.loop(); // set the video to loop and start playing - } -{{< /p5-instance-div >}} \ No newline at end of file diff --git a/content/docs/shortcodes/p5/iframe.md b/content/docs/shortcodes/p5/iframe.md deleted file mode 100644 index 93dbe5a7..00000000 --- a/content/docs/shortcodes/p5/iframe.md +++ /dev/null @@ -1,176 +0,0 @@ -p5 `iframe` [shortcodes](https://gohugo.io/content-management/shortcodes/) embed [p5.js](https://p5js.org/) code within an [iframe element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe). There are two p5 `iframe` shortcodes: [p5-iframe](#p5-iframe) and [p5-global-iframe](#p5-global-iframe). - -# p5-iframe - -```html -{{}} -``` - -All parameters are optional but `sketch`. Default values are shown in the above snippet but for `libs*`. Up to `lib5` libs may be specified. - -## Color relativity - -Look at this [brief explanation](https://p5js.org/examples/color-relativity.html) about what color relativity is. - -{{< details title="p5-iframe markdown" open=false >}} -{{< highlight html >}} -{{}} -{{< /highlight >}} -{{< /details >}} - -{{< p5-iframe sketch="/showcase/sketches/colors.js" width="725" height="425" >}} - -## Third party libraries - -Example adapted from [p5.EasyCam](https://github.com/freshfork/p5.EasyCam/blob/master/examples/QuickStart/QuickStart.js). - -{{< details title="p5-iframe markdown" open=false >}} -{{< highlight html >}} -{{}} -{{< /highlight >}} -{{< /details >}} - -{{< p5-iframe sketch="/showcase/sketches/quick_easycam.js" lib1="https://cdn.jsdelivr.net/gh/freshfork/p5.EasyCam@1.2.1/p5.easycam.min.js" width="525" height="525" >}} - -## Sound - -Example took from the [p5 examples](https://p5js.org/examples/sound-sound-effect.html). - -{{< details title="p5-iframe markdown" open=false >}} -{{< highlight html >}} -{{}} -{{< /highlight >}} -{{< /details >}} - -{{< p5-iframe sketch="/showcase/sketches/sound.js" width="225" height="225" >}} - -# p5-global-iframe - -```html -{{}} - // inline sketch code -{{< /p5-global-iframe */>}} -``` - -{{< hint warning >}} -Note that the inline `sketch` should be coded in [p5 global mode](https://github.com/processing/p5.js/wiki/Global-and-instance-mode) syntax. -{{< /hint >}} - -All parameters are optional but `id`. Default values are shown in the above snippet but for `libs*`. Up to `lib5` libs may be specified. - -## Breathing square - -Look at [this reference](https://michaelbach.de/ot/mot-breathingSquare/) for an explanation and further parameterization of the illusion. - -{{< details title="p5-global-iframe markdown" open=false >}} -{{< highlight html >}} -{{}} - // Coded as `global mode` of [this](https://github.com/VisualComputing/Cognitive/blob/gh-pages/sketches/rotateSquare.js) - let angle = 0; - let speed = 0.06; - - function setup() { - createCanvas(600, 600); - } - - function draw() { - background(255, 255, 255); - rotateSquare(); - if (!mouseIsPressed) { - strokeWeight(0); - stroke(0); - fill(255, 140, 0); - rect(0, 0, 281, 281); - rect(318, 0, 281, 281); - rect(0, 318, 281, 281); - rect(318, 318, 281, 281); - } - } - - function rotateSquare() { - push(); - angle += speed; - strokeWeight(0); - stroke(0); - fill(0, 0, 255); - translate(width / 2, height / 2); - rotate(angle); - rect(-187.5, -187.5, 375, 375); - pop(); - } -{{< /p5-global-iframe */>}} -{{< /highlight >}} -{{< /details >}} - -{{< p5-global-iframe id="breath" width="625" height="625" >}} - let angle = 0; - let speed = 0.06; - - function setup() { - createCanvas(600, 600); - } - - function draw() { - background(255, 255, 255); - rotateSquare(); - if (!mouseIsPressed) { - strokeWeight(0); - stroke(0); - fill(255, 140, 0); - rect(0, 0, 281, 281); - rect(318, 0, 281, 281); - rect(0, 318, 281, 281); - rect(318, 318, 281, 281); - } - } - - function rotateSquare() { - push(); - angle += speed; - strokeWeight(0); - stroke(0); - fill(0, 0, 255); - translate(width / 2, height / 2); - rotate(angle); - rect(-187.5, -187.5, 375, 375); - pop(); - } -{{< /p5-global-iframe >}} - -# p5-widget - -The `p5-widget` [shortcode](https://gohugo.io/content-management/shortcodes/) embed [p5.js](https://p5js.org/) code within an [p5-widget](https://toolness.github.io/p5.js-widget/). - -```html -{{}} - // inline sketch code -{{< /p5-widget */>}} -``` - -All parameters are optional. Default `ver` is `1.4.2`. For example: - -## Widget example - -{{< details title="p5-widget markdown" open=false >}} -{{< highlight html >}} -{{}} -function setup() { - createCanvas(300, 300); -} - -function draw() { - background(255, 0, 255); -} -{{< /p5-widget */>}} -{{< /highlight >}} -{{< /details >}} - -{{< p5-widget autoplay=true height="400" width="400" ver="1.4.2" >}} -function setup() { - createCanvas(300, 300); -} - -function draw() { - background(255, 0, 255); -} -{{< /p5-widget >}} \ No newline at end of file diff --git a/content/docs/shortcodes/tabs.md b/content/docs/shortcodes/tabs.md deleted file mode 100644 index 096892c6..00000000 --- a/content/docs/shortcodes/tabs.md +++ /dev/null @@ -1,50 +0,0 @@ -# Tabs - -Tabs let you organize content by context, for example installation instructions for each supported platform. - -```tpl -{{}} -{{}} # MacOS Content {{}} -{{}} # Linux Content {{}} -{{}} # Windows Content {{}} -{{}} -``` - -## Example - -{{< tabs "uniqueid" >}} -{{< tab "MacOS" >}} -# MacOS - -This is tab **MacOS** content. - -Lorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat -stringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa -protulit, sed sed aere valvis inhaesuro Pallas animam: qui _quid_, ignes. -Miseratus fonte Ditis conubia. -{{< /tab >}} - -{{< tab "Linux" >}} - -# Linux - -This is tab **Linux** content. - -Lorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat -stringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa -protulit, sed sed aere valvis inhaesuro Pallas animam: qui _quid_, ignes. -Miseratus fonte Ditis conubia. -{{< /tab >}} - -{{< tab "Windows" >}} - -# Windows - -This is tab **Windows** content. - -Lorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat -stringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa -protulit, sed sed aere valvis inhaesuro Pallas animam: qui _quid_, ignes. -Miseratus fonte Ditis conubia. -{{< /tab >}} -{{< /tabs >}} diff --git a/content/imgs/car.jpg b/content/imgs/car.jpg new file mode 100644 index 00000000..012b7455 Binary files /dev/null and b/content/imgs/car.jpg differ diff --git a/content/imgs/cars/000001.jpg b/content/imgs/cars/000001.jpg new file mode 100644 index 00000000..81c3beca Binary files /dev/null and b/content/imgs/cars/000001.jpg differ diff --git a/content/imgs/cars/000002.jpg b/content/imgs/cars/000002.jpg new file mode 100644 index 00000000..bdc74701 Binary files /dev/null and b/content/imgs/cars/000002.jpg differ diff --git a/content/imgs/cars/000003.jpg b/content/imgs/cars/000003.jpg new file mode 100644 index 00000000..a1f188c6 Binary files /dev/null and b/content/imgs/cars/000003.jpg differ diff --git a/content/imgs/cars/000004.jpg b/content/imgs/cars/000004.jpg new file mode 100644 index 00000000..7c877529 Binary files /dev/null and b/content/imgs/cars/000004.jpg differ diff --git a/content/imgs/cars/000005.jpg b/content/imgs/cars/000005.jpg new file mode 100644 index 00000000..8cecd983 Binary files /dev/null and b/content/imgs/cars/000005.jpg differ diff --git a/content/imgs/cars/000006.jpg b/content/imgs/cars/000006.jpg new file mode 100644 index 00000000..884f1e75 Binary files /dev/null and b/content/imgs/cars/000006.jpg differ diff --git a/content/imgs/cars/000007.jpg b/content/imgs/cars/000007.jpg new file mode 100644 index 00000000..8df38996 Binary files /dev/null and b/content/imgs/cars/000007.jpg differ diff --git a/content/imgs/cars/000008.jpg b/content/imgs/cars/000008.jpg new file mode 100644 index 00000000..ae9b67ce Binary files /dev/null and b/content/imgs/cars/000008.jpg differ diff --git a/content/imgs/cars/000009.jpg b/content/imgs/cars/000009.jpg new file mode 100644 index 00000000..00763ab2 Binary files /dev/null and b/content/imgs/cars/000009.jpg differ diff --git a/content/imgs/cars/000010.jpg b/content/imgs/cars/000010.jpg new file mode 100644 index 00000000..a942fa09 Binary files /dev/null and b/content/imgs/cars/000010.jpg differ diff --git a/content/imgs/cars/000011.jpg b/content/imgs/cars/000011.jpg new file mode 100644 index 00000000..710a1877 Binary files /dev/null and b/content/imgs/cars/000011.jpg differ diff --git a/content/imgs/cars/000012.jpg b/content/imgs/cars/000012.jpg new file mode 100644 index 00000000..713d1f79 Binary files /dev/null and b/content/imgs/cars/000012.jpg differ diff --git a/content/imgs/cars/000013.jpg b/content/imgs/cars/000013.jpg new file mode 100644 index 00000000..d13871d9 Binary files /dev/null and b/content/imgs/cars/000013.jpg differ diff --git a/content/imgs/cars/000014.jpg b/content/imgs/cars/000014.jpg new file mode 100644 index 00000000..7acf986f Binary files /dev/null and b/content/imgs/cars/000014.jpg differ diff --git a/content/imgs/cars/000015.jpg b/content/imgs/cars/000015.jpg new file mode 100644 index 00000000..c534a2aa Binary files /dev/null and b/content/imgs/cars/000015.jpg differ diff --git a/content/imgs/cars/000016.jpg b/content/imgs/cars/000016.jpg new file mode 100644 index 00000000..fba47777 Binary files /dev/null and b/content/imgs/cars/000016.jpg differ diff --git a/content/imgs/cars/000017.jpg b/content/imgs/cars/000017.jpg new file mode 100644 index 00000000..e67e02a6 Binary files /dev/null and b/content/imgs/cars/000017.jpg differ diff --git a/content/imgs/cars/000018.jpg b/content/imgs/cars/000018.jpg new file mode 100644 index 00000000..c8f5a25c Binary files /dev/null and b/content/imgs/cars/000018.jpg differ diff --git a/content/imgs/cars/000019.jpg b/content/imgs/cars/000019.jpg new file mode 100644 index 00000000..d000d1fb Binary files /dev/null and b/content/imgs/cars/000019.jpg differ diff --git a/content/imgs/cars/000020.jpg b/content/imgs/cars/000020.jpg new file mode 100644 index 00000000..d5e93587 Binary files /dev/null and b/content/imgs/cars/000020.jpg differ diff --git a/content/imgs/cars/000021.jpg b/content/imgs/cars/000021.jpg new file mode 100644 index 00000000..7b4db854 Binary files /dev/null and b/content/imgs/cars/000021.jpg differ diff --git a/content/imgs/cars/000022.jpg b/content/imgs/cars/000022.jpg new file mode 100644 index 00000000..b2fd72a9 Binary files /dev/null and b/content/imgs/cars/000022.jpg differ diff --git a/content/imgs/cars/000023.jpg b/content/imgs/cars/000023.jpg new file mode 100644 index 00000000..1e6fbb30 Binary files /dev/null and b/content/imgs/cars/000023.jpg differ diff --git a/content/imgs/cars/000024.jpg b/content/imgs/cars/000024.jpg new file mode 100644 index 00000000..15fbcd3e Binary files /dev/null and b/content/imgs/cars/000024.jpg differ diff --git a/content/imgs/cars/000025.jpg b/content/imgs/cars/000025.jpg new file mode 100644 index 00000000..9207f9b1 Binary files /dev/null and b/content/imgs/cars/000025.jpg differ diff --git a/content/imgs/cars/000026.jpg b/content/imgs/cars/000026.jpg new file mode 100644 index 00000000..3977672b Binary files /dev/null and b/content/imgs/cars/000026.jpg differ diff --git a/content/imgs/cars/000027.jpg b/content/imgs/cars/000027.jpg new file mode 100644 index 00000000..62af1107 Binary files /dev/null and b/content/imgs/cars/000027.jpg differ diff --git a/content/imgs/cars/000028.jpg b/content/imgs/cars/000028.jpg new file mode 100644 index 00000000..e5e14600 Binary files /dev/null and b/content/imgs/cars/000028.jpg differ diff --git a/content/imgs/cars/000029.jpg b/content/imgs/cars/000029.jpg new file mode 100644 index 00000000..466f8d7d Binary files /dev/null and b/content/imgs/cars/000029.jpg differ diff --git a/content/imgs/cars/000030.jpg b/content/imgs/cars/000030.jpg new file mode 100644 index 00000000..c026f8d3 Binary files /dev/null and b/content/imgs/cars/000030.jpg differ diff --git a/content/imgs/cars/000031.jpg b/content/imgs/cars/000031.jpg new file mode 100644 index 00000000..bafef81a Binary files /dev/null and b/content/imgs/cars/000031.jpg differ diff --git a/content/imgs/cars/000032.jpg b/content/imgs/cars/000032.jpg new file mode 100644 index 00000000..f7bb8881 Binary files /dev/null and b/content/imgs/cars/000032.jpg differ diff --git a/content/imgs/cars/000033.jpg b/content/imgs/cars/000033.jpg new file mode 100644 index 00000000..c77c0d83 Binary files /dev/null and b/content/imgs/cars/000033.jpg differ diff --git a/content/imgs/cars/000034.jpg b/content/imgs/cars/000034.jpg new file mode 100644 index 00000000..6de33739 Binary files /dev/null and b/content/imgs/cars/000034.jpg differ diff --git a/content/imgs/cars/000035.jpg b/content/imgs/cars/000035.jpg new file mode 100644 index 00000000..f1005cb0 Binary files /dev/null and b/content/imgs/cars/000035.jpg differ diff --git a/content/imgs/cars/000036.jpg b/content/imgs/cars/000036.jpg new file mode 100644 index 00000000..4d9d6163 Binary files /dev/null and b/content/imgs/cars/000036.jpg differ diff --git a/content/imgs/cars/000037.jpg b/content/imgs/cars/000037.jpg new file mode 100644 index 00000000..25fd38cb Binary files /dev/null and b/content/imgs/cars/000037.jpg differ diff --git a/content/imgs/cars/000038.jpg b/content/imgs/cars/000038.jpg new file mode 100644 index 00000000..bbe4426e Binary files /dev/null and b/content/imgs/cars/000038.jpg differ diff --git a/content/imgs/cars/000039.jpg b/content/imgs/cars/000039.jpg new file mode 100644 index 00000000..95b05329 Binary files /dev/null and b/content/imgs/cars/000039.jpg differ diff --git a/content/imgs/cars/000040.jpg b/content/imgs/cars/000040.jpg new file mode 100644 index 00000000..7ca4e4c5 Binary files /dev/null and b/content/imgs/cars/000040.jpg differ diff --git a/content/imgs/casas/1.jpg b/content/imgs/casas/1.jpg new file mode 100644 index 00000000..58f2e8e8 Binary files /dev/null and b/content/imgs/casas/1.jpg differ diff --git a/content/imgs/casas/2.jpg b/content/imgs/casas/2.jpg new file mode 100644 index 00000000..e6c1d9dc Binary files /dev/null and b/content/imgs/casas/2.jpg differ diff --git a/content/imgs/casas/3.jpg b/content/imgs/casas/3.jpg new file mode 100644 index 00000000..9d952b80 Binary files /dev/null and b/content/imgs/casas/3.jpg differ diff --git a/content/imgs/casas/p5.pixelator.js b/content/imgs/casas/p5.pixelator.js new file mode 100644 index 00000000..daf29ed5 --- /dev/null +++ b/content/imgs/casas/p5.pixelator.js @@ -0,0 +1,409 @@ +/* + + Pixelator + p5.pixelator.js + + a p5.js library, based on the idea of sorting images + by its brightness and using them as pixels + to reproduce the canvas source. + + by: + Ksawery Kirklewski + Marek Pepke + + www.ksawerykomputery.pl/tools/pixelator + +*/ + + +!function () { + 'use strict' + + const count = 64; + const W = 1024; + var H = 1024; + + function getBrightness(r, g, b) { + return Math.sqrt(0.299*r*r + 0.587*g*g + 0.114*b*b ) + } + function compareBrightness(a, b) { + return a.brightness - b.brightness; + } + function calcImageBrightness(img) { + let sum = 0; + img.loadPixels(); + for(let i=0; i maxDif ) return -1; + } + } + return average; + } + + grouper(x, y, w, h) { + if( w > 1 && h > 1 ) { + let m = this.isSimilar(x, y, w, h); + if( m >= 0 ) { + this.drawSprite(x, y, w, h, m); + } else { + let m1 = this.isSimilar(x, y, w, h/2); + let m2 = this.isSimilar(x, y+h/2, w, h/2); + if( m1 >= 0 && m2 >= 0) { + this.drawSprite(x, y, w, h/2, m1); + this.drawSprite(x, y+h/2, w, h/2, m2); + } else { + let m3 = this.isSimilar(x, y, w/2, h); + let m4 = this.isSimilar(x+w/2, y, w/2, h); + if( m3 >= 0 && m4 >= 0) { + this.drawSprite(x, y, w/2, h, m3); + this.drawSprite(x+w/2, y, w/2, h, m4); + } else { + if(m1 >= 0) { + this.drawSprite(x, y, w, h/2, m1); + } else { + this.grouper(x, y, w/2, h/2); + this.grouper(x+w/2, y, w/2, h/2); + } + if(m2 >= 0) { + this.drawSprite(x, y+h/2, w, h/2, m2); + } else { + this.grouper(x, y+h/2, w/2, h/2); + this.grouper(x+w/2, y+h/2, w/2, h/2); + } + } + } + } + } else { + this.drawSprite( x, y, w, h, this.brightnessArr[x][y] ); + } + } + + drawSprite(x, y, w, h, c) { + + let range = this.settings.range * this.settings.range * 255; + let g = 255/range; + c = int( int(map(c, 0, 255, 0, range )) * g ); + c = constrain(c, 0, 255); + + if(this.settings.type) { + this.outGraphics.image(this.sprites[c].img, x * this.bW | 0, y * this.bH | 0, w * this.bW | 0, h * this.bH | 0); + } else { + this.outGraphics.strokeWeight(2) + var hexC = ('0' + (c | 0).toString(16)).slice(-2) + this.outGraphics.drawingContext.fillStyle = '#' + hexC + hexC + hexC + this.outGraphics.drawingContext.fillRect( x * this.bW | 0, y * this.bH | 0, w * this.bW | 0, h * this.bH | 0); + this.outGraphics.drawingContext.strokeRect( x * this.bW | 0, y * this.bH | 0, w * this.bW | 0, h * this.bH | 0); + } + } + + generateSprites() { + let arr = []; + for(let i=0; i<256; i++) { + arr[i] = {}; + arr[i].img = this.newSprite(i); + arr[i].brightness = calcImageBrightness(arr[i].img); + } + arr.sort(compareBrightness); + return arr; + } + + newSprite(i) { + + let img; + + if(this.settings.type == "image") { + + let x = i % 16; + let y = floor( i / 16 ); + let tW = this.settings.image.width / 16; + let tH = this.settings.image.height / 16; + img = this.settings.image.get(x * tW, y * tH, tW, tH); + img.resize(128,128); + + } else if(this.settings.type == "gradients") { + + let c1 = random( this.settings.palette ); + let c2 = random( this.settings.palette ); + let s = random(0.3); + let e = random(0.6,1); + + let R1 = red(c1); + let G1 = green(c1); + let B1 = blue(c1); + let R2 = red(c2); + let G2 = green(c2); + let B2 = blue(c2); + let dR = R2 - R1; + let dG = G2 - G1; + let dB = B2 - B1; + + img = random(1) > 0.5 ? createGraphics(128,1) : createGraphics(1,128); + img.pixelDensity(1); + img.background(100); + img.noStroke(); + img.loadPixels(); + for(let i=0; i<128; i++) { + let m = constrain(map(i/128, s, e, 0, 1), 0, 1); + img.pixels[4*i] = mix(R1, R2, m); + img.pixels[4*i+1] = mix(G1, G2, m); + img.pixels[4*i+2] = mix(B1, B2, m); + } + img.updatePixels(); + + + } else if(this.settings.type == "blocks") { + + let w = W / 8; + let h = H / 8; + img = createGraphics(w, h); + let r1 = random( this.settings.palette ); + let r2 = random( this.settings.palette ); + let r3 = random( this.settings.palette ); + img.background(r1); + img.noStroke(); + img.fill(r2); + + switch( floor(random(16)) ) { + case 0: + img.beginShape(); + img.vertex(w,0); + img.vertex(w,h); + img.vertex(0,h/2); + img.endShape(CLOSE); + break; + + case 1: + img.ellipse(w/2,h/2,w*0.9,h*0.9); + break; + + case 2: + img.beginShape(); + img.vertex(0,0); + img.vertex(w/2,h/2); + img.vertex(0,h); + img.endShape(CLOSE); + img.fill(r3); + img.beginShape(); + img.vertex(w/2,h/2); + img.vertex(w,h); + img.vertex(w,0); + img.endShape(CLOSE); + break; + + case 3: + img.rect(0,0,w,h/2); + break; + + case 4: + img.rect(0,0,w,h/4); + img.fill(r3); + img.rect(0,h/2,w,h/4); + break; + + case 5: + img.rect(0,0,w/2,h); + break; + + case 6: + img.rect(0,0,w/4,h); + img.fill(r3); + img.rect(w/2,0,w/4,h); + break; + + case 7: + img.beginShape(); + img.vertex(w/2,0); + img.vertex(w,h/2); + img.vertex(w/2,h); + img.vertex(0,h/2); + img.endShape(CLOSE); + break; + + case 8: + img.beginShape(); + img.vertex(0,0); + img.vertex(w,h); + img.vertex(0,h); + img.endShape(CLOSE); + break; + + case 9: + img.beginShape(); + img.vertex(w,0); + img.vertex(w,h); + img.vertex(0,h); + img.endShape(CLOSE); + break; + + case 10: + img.beginShape(); + img.vertex(w/2,0); + img.vertex(w,h/2); + img.vertex(0,h/2); + img.endShape(CLOSE); + img.beginShape(); + img.vertex(w/2,h/2); + img.vertex(w,h); + img.vertex(0,h); + img.endShape(CLOSE); + break; + + case 11: + img.beginShape(); + img.vertex(0,0); + img.vertex(w,0); + img.vertex(w/2,h/2); + img.endShape(CLOSE); + img.beginShape(); + img.vertex(0,h/2); + img.vertex(w,h/2); + img.vertex(w/2,h); + img.endShape(CLOSE); + break; + + case 12: + img.beginShape(); + img.vertex(0,0); + img.vertex(w/2,0); + img.vertex(w/4,h); + img.endShape(CLOSE); + img.beginShape(); + img.vertex(w/2,0); + img.vertex(w,0); + img.vertex(w*3/4,h); + img.endShape(CLOSE); + break; + + case 13: + img.rect(0,0,w/2,h/2); + img.rect(w/2,h/2,w/2,h/2); + break; + + case 14: + img.beginShape(); + img.vertex(0,0); + img.vertex(w,h/2); + img.vertex(0,h/2); + img.endShape(CLOSE); + img.beginShape(); + img.vertex(0,h/2); + img.vertex(w,h); + img.vertex(0,h); + img.endShape(CLOSE); + break; + + case 15: + img.beginShape(); + img.vertex(w,0); + img.vertex(w,h/2); + img.vertex(0,h/2); + img.endShape(CLOSE); + img.beginShape(); + img.vertex(w,h/2); + img.vertex(w,h); + img.vertex(0,h); + img.endShape(CLOSE); + break; + } + + } + if (img.canvas.parentElement) img.canvas.parentElement.removeChild(img.canvas) + return img; + } + + constructor(p, graphics, settings = {}) { + this.inGraphicsRaw = graphics + this.settings = settings + this.settings.range = this.settings.range || 1 + this.settings.tolerance = this.settings.tolerance || 0.2 + this.p = p + this.inGraphics = this.p.createGraphics(count, count) + this.inGraphics.pixelDensity(1) + this.bW = W / count; + this.bH = Math.round(this.bW * this.inGraphicsRaw.height / this.inGraphicsRaw.width); + H = this.bH * count; + this.width = W; + this.height = H; + this.outGraphics = this.p.createGraphics(W, H) + this.outGraphics.pixelDensity(1) + if (this.settings.type) this.sprites = this.generateSprites(); + this.outGraphics.canvas.style.display = 'block'; + } + + parent(p) { + document.querySelector('#'+p).appendChild(this.outGraphics.canvas); + } + + hide() { + this.outGraphics.canvas.style.display = 'none'; + } + + remove() { + this.outGraphics.canvas.remove(); + } + + changeSource(src) { + this.inGraphicsRaw = src; + } + + set(settings = {}) { + if (settings.range != null) this.settings.range = settings.range; + if (settings.tolerance != null) this.settings.tolerance = settings.tolerance; + if (settings.type) { + this.settings.type = settings.type; + this.settings.palette = settings.palette || this.settings.palette; + this.settings.image = settings.image || this.settings.image; + this.sprites = this.generateSprites(); + } + } + + clear() { + this.settings.type = ''; + } + + update() { + this.inGraphics.image(this.inGraphicsRaw, 0, 0, count, count) + this.inGraphics.loadPixels() + this.calcBrightness() + this.grouper(0, 0, count, count) + this.mouseX = ( mouseX - this.outGraphics.canvas.offsetLeft ) / this.outGraphics.canvas.offsetWidth; + this.mouseY = ( mouseY + document.body.scrollTop - this.outGraphics.canvas.offsetTop ) / this.outGraphics.canvas.offsetHeight; + } + + get graphics() { + return this.outGraphics + } + } + + window.Pixelator = Pixelator +}(); diff --git a/content/imgs/madusa.jpeg b/content/imgs/madusa.jpeg new file mode 100644 index 00000000..ade5de93 Binary files /dev/null and b/content/imgs/madusa.jpeg differ diff --git a/content/imgs/patron.JPG b/content/imgs/patron.JPG new file mode 100644 index 00000000..4c854835 Binary files /dev/null and b/content/imgs/patron.JPG differ diff --git a/content/imgs/resultado.JPG b/content/imgs/resultado.JPG new file mode 100644 index 00000000..633a61ca Binary files /dev/null and b/content/imgs/resultado.JPG differ diff --git a/content/menu/index.md b/content/menu/index.md index dc3c1e8d..0977e140 100644 --- a/content/menu/index.md +++ b/content/menu/index.md @@ -11,4 +11,4 @@ headless: true - [Katex]({{< relref "/docs/shortcodes/katex" >}}) - [Mermaid]({{< relref "/docs/shortcodes/mermaid" >}}) - [Tabs]({{< relref "/docs/shortcodes/tabs" >}}) -
+
diff --git a/content/posts/_index.md b/content/posts/_index.md deleted file mode 100644 index 001ae24e..00000000 --- a/content/posts/_index.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -menu: - after: - name: blog - weight: 5 -title: Blog ---- diff --git a/content/posts/creating-a-new-theme.md b/content/posts/creating-a-new-theme.md deleted file mode 100644 index f8230a17..00000000 --- a/content/posts/creating-a-new-theme.md +++ /dev/null @@ -1,1150 +0,0 @@ ---- -author: "Michael Henderson" -date: 2014-09-28 -linktitle: Creating a New Theme -menu: - main: - parent: tutorials -next: /tutorials/github-pages-blog -prev: /tutorials/automated-deployments -title: Creating a New Theme -weight: 10 ---- - - -## Introduction - -This tutorial will show you how to create a simple theme in Hugo. I assume that you are familiar with HTML, the bash command line, and that you are comfortable using Markdown to format content. I'll explain how Hugo uses templates and how you can organize your templates to create a theme. I won't cover using CSS to style your theme. - -We'll start with creating a new site with a very basic template. Then we'll add in a few pages and posts. With small variations on that, you will be able to create many different types of web sites. - -In this tutorial, commands that you enter will start with the "$" prompt. The output will follow. Lines that start with "#" are comments that I've added to explain a point. When I show updates to a file, the ":wq" on the last line means to save the file. - -Here's an example: - -``` -## this is a comment -$ echo this is a command -this is a command - -## edit the file -$ vi foo.md -+++ -date = "2014-09-28" -title = "creating a new theme" -+++ - -bah and humbug -:wq - -## show it -$ cat foo.md -+++ -date = "2014-09-28" -title = "creating a new theme" -+++ - -bah and humbug -$ -``` - - -## Some Definitions - -There are a few concepts that you need to understand before creating a theme. - -### Skins - -Skins are the files responsible for the look and feel of your site. It’s the CSS that controls colors and fonts, it’s the Javascript that determines actions and reactions. It’s also the rules that Hugo uses to transform your content into the HTML that the site will serve to visitors. - -You have two ways to create a skin. The simplest way is to create it in the ```layouts/``` directory. If you do, then you don’t have to worry about configuring Hugo to recognize it. The first place that Hugo will look for rules and files is in the ```layouts/``` directory so it will always find the skin. - -Your second choice is to create it in a sub-directory of the ```themes/``` directory. If you do, then you must always tell Hugo where to search for the skin. It’s extra work, though, so why bother with it? - -The difference between creating a skin in ```layouts/``` and creating it in ```themes/``` is very subtle. A skin in ```layouts/``` can’t be customized without updating the templates and static files that it is built from. A skin created in ```themes/```, on the other hand, can be and that makes it easier for other people to use it. - -The rest of this tutorial will call a skin created in the ```themes/``` directory a theme. - -Note that you can use this tutorial to create a skin in the ```layouts/``` directory if you wish to. The main difference will be that you won’t need to update the site’s configuration file to use a theme. - -### The Home Page - -The home page, or landing page, is the first page that many visitors to a site see. It is the index.html file in the root directory of the web site. Since Hugo writes files to the public/ directory, our home page is public/index.html. - -### Site Configuration File - -When Hugo runs, it looks for a configuration file that contains settings that override default values for the entire site. The file can use TOML, YAML, or JSON. I prefer to use TOML for my configuration files. If you prefer to use JSON or YAML, you’ll need to translate my examples. You’ll also need to change the name of the file since Hugo uses the extension to determine how to process it. - -Hugo translates Markdown files into HTML. By default, Hugo expects to find Markdown files in your ```content/``` directory and template files in your ```themes/``` directory. It will create HTML files in your ```public/``` directory. You can change this by specifying alternate locations in the configuration file. - -### Content - -Content is stored in text files that contain two sections. The first section is the “front matter,” which is the meta-information on the content. The second section contains Markdown that will be converted to HTML. - -#### Front Matter - -The front matter is information about the content. Like the configuration file, it can be written in TOML, YAML, or JSON. Unlike the configuration file, Hugo doesn’t use the file’s extension to know the format. It looks for markers to signal the type. TOML is surrounded by “`+++`”, YAML by “`---`”, and JSON is enclosed in curly braces. I prefer to use TOML, so you’ll need to translate my examples if you prefer YAML or JSON. - -The information in the front matter is passed into the template before the content is rendered into HTML. - -#### Markdown - -Content is written in Markdown which makes it easier to create the content. Hugo runs the content through a Markdown engine to create the HTML which will be written to the output file. - -### Template Files - -Hugo uses template files to render content into HTML. Template files are a bridge between the content and presentation. Rules in the template define what content is published, where it's published to, and how it will rendered to the HTML file. The template guides the presentation by specifying the style to use. - -There are three types of templates: single, list, and partial. Each type takes a bit of content as input and transforms it based on the commands in the template. - -Hugo uses its knowledge of the content to find the template file used to render the content. If it can’t find a template that is an exact match for the content, it will shift up a level and search from there. It will continue to do so until it finds a matching template or runs out of templates to try. If it can’t find a template, it will use the default template for the site. - -Please note that you can use the front matter to influence Hugo’s choice of templates. - -#### Single Template - -A single template is used to render a single piece of content. For example, an article or post would be a single piece of content and use a single template. - -#### List Template - -A list template renders a group of related content. That could be a summary of recent postings or all articles in a category. List templates can contain multiple groups. - -The homepage template is a special type of list template. Hugo assumes that the home page of your site will act as the portal for the rest of the content in the site. - -#### Partial Template - -A partial template is a template that can be included in other templates. Partial templates must be called using the “partial” template command. They are very handy for rolling up common behavior. For example, your site may have a banner that all pages use. Instead of copying the text of the banner into every single and list template, you could create a partial with the banner in it. That way if you decide to change the banner, you only have to change the partial template. - -## Create a New Site - -Let's use Hugo to create a new web site. I'm a Mac user, so I'll create mine in my home directory, in the Sites folder. If you're using Linux, you might have to create the folder first. - -The "new site" command will create a skeleton of a site. It will give you the basic directory structure and a useable configuration file. - -``` -$ hugo new site ~/Sites/zafta -$ cd ~/Sites/zafta -$ ls -l -total 8 -drwxr-xr-x 7 quoha staff 238 Sep 29 16:49 . -drwxr-xr-x 3 quoha staff 102 Sep 29 16:49 .. -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 archetypes --rw-r--r-- 1 quoha staff 82 Sep 29 16:49 config.toml -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 content -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 layouts -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 static -$ -``` - -Take a look in the content/ directory to confirm that it is empty. - -The other directories (archetypes/, layouts/, and static/) are used when customizing a theme. That's a topic for a different tutorial, so please ignore them for now. - -### Generate the HTML For the New Site - -Running the `hugo` command with no options will read all the available content and generate the HTML files. It will also copy all static files (that's everything that's not content). Since we have an empty site, it won't do much, but it will do it very quickly. - -``` -$ hugo --verbose -INFO: 2014/09/29 Using config file: config.toml -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ -WARN: 2014/09/29 Unable to locate layout: [index.html _default/list.html _default/single.html] -WARN: 2014/09/29 Unable to locate layout: [404.html] -0 draft content -0 future content -0 pages created -0 tags created -0 categories created -in 2 ms -$ -``` - -The "`--verbose`" flag gives extra information that will be helpful when we build the template. Every line of the output that starts with "INFO:" or "WARN:" is present because we used that flag. The lines that start with "WARN:" are warning messages. We'll go over them later. - -We can verify that the command worked by looking at the directory again. - -``` -$ ls -l -total 8 -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 archetypes --rw-r--r-- 1 quoha staff 82 Sep 29 16:49 config.toml -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 content -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 layouts -drwxr-xr-x 4 quoha staff 136 Sep 29 17:02 public -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 static -$ -``` - -See that new public/ directory? Hugo placed all generated content there. When you're ready to publish your web site, that's the place to start. For now, though, let's just confirm that we have what we'd expect from a site with no content. - -``` -$ ls -l public -total 16 --rw-r--r-- 1 quoha staff 416 Sep 29 17:02 index.xml --rw-r--r-- 1 quoha staff 262 Sep 29 17:02 sitemap.xml -$ -``` - -Hugo created two XML files, which is standard, but there are no HTML files. - - - -### Test the New Site - -Verify that you can run the built-in web server. It will dramatically shorten your development cycle if you do. Start it by running the "server" command. If it is successful, you will see output similar to the following: - -``` -$ hugo server --verbose -INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ -WARN: 2014/09/29 Unable to locate layout: [index.html _default/list.html _default/single.html] -WARN: 2014/09/29 Unable to locate layout: [404.html] -0 draft content -0 future content -0 pages created -0 tags created -0 categories created -in 2 ms -Serving pages from /Users/quoha/Sites/zafta/public -Web Server is available at http://localhost:1313 -Press Ctrl+C to stop -``` - -Connect to the listed URL (it's on the line that starts with "Web Server"). If everything is working correctly, you should get a page that shows the following: - -``` -index.xml -sitemap.xml -``` - -That's a listing of your public/ directory. Hugo didn't create a home page because our site has no content. When there's no index.html file in a directory, the server lists the files in the directory, which is what you should see in your browser. - -Let’s go back and look at those warnings again. - -``` -WARN: 2014/09/29 Unable to locate layout: [index.html _default/list.html _default/single.html] -WARN: 2014/09/29 Unable to locate layout: [404.html] -``` - -That second warning is easier to explain. We haven’t created a template to be used to generate “page not found errors.” The 404 message is a topic for a separate tutorial. - -Now for the first warning. It is for the home page. You can tell because the first layout that it looked for was “index.html.” That’s only used by the home page. - -I like that the verbose flag causes Hugo to list the files that it's searching for. For the home page, they are index.html, _default/list.html, and _default/single.html. There are some rules that we'll cover later that explain the names and paths. For now, just remember that Hugo couldn't find a template for the home page and it told you so. - -At this point, you've got a working installation and site that we can build upon. All that’s left is to add some content and a theme to display it. - -## Create a New Theme - -Hugo doesn't ship with a default theme. There are a few available (I counted a dozen when I first installed Hugo) and Hugo comes with a command to create new themes. - -We're going to create a new theme called "zafta." Since the goal of this tutorial is to show you how to fill out the files to pull in your content, the theme will not contain any CSS. In other words, ugly but functional. - -All themes have opinions on content and layout. For example, Zafta uses "post" over "blog". Strong opinions make for simpler templates but differing opinions make it tougher to use themes. When you build a theme, consider using the terms that other themes do. - - -### Create a Skeleton - -Use the hugo "new" command to create the skeleton of a theme. This creates the directory structure and places empty files for you to fill out. - -``` -$ hugo new theme zafta - -$ ls -l -total 8 -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 archetypes --rw-r--r-- 1 quoha staff 82 Sep 29 16:49 config.toml -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 content -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 layouts -drwxr-xr-x 4 quoha staff 136 Sep 29 17:02 public -drwxr-xr-x 2 quoha staff 68 Sep 29 16:49 static -drwxr-xr-x 3 quoha staff 102 Sep 29 17:31 themes - -$ find themes -type f | xargs ls -l --rw-r--r-- 1 quoha staff 1081 Sep 29 17:31 themes/zafta/LICENSE.md --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/archetypes/default.md --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/_default/list.html --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/_default/single.html --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/index.html --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/partials/footer.html --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/partials/header.html --rw-r--r-- 1 quoha staff 93 Sep 29 17:31 themes/zafta/theme.toml -$ -``` - -The skeleton includes templates (the files ending in .html), license file, a description of your theme (the theme.toml file), and an empty archetype. - -Please take a minute to fill out the theme.toml and LICENSE.md files. They're optional, but if you're going to be distributing your theme, it tells the world who to praise (or blame). It's also nice to declare the license so that people will know how they can use the theme. - -``` -$ vi themes/zafta/theme.toml -author = "michael d henderson" -description = "a minimal working template" -license = "MIT" -name = "zafta" -source_repo = "" -tags = ["tags", "categories"] -:wq - -## also edit themes/zafta/LICENSE.md and change -## the bit that says "YOUR_NAME_HERE" -``` - -Note that the the skeleton's template files are empty. Don't worry, we'll be changing that shortly. - -``` -$ find themes/zafta -name '*.html' | xargs ls -l --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/_default/list.html --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/_default/single.html --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/index.html --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/partials/footer.html --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/partials/header.html -$ -``` - - - -### Update the Configuration File to Use the Theme - -Now that we've got a theme to work with, it's a good idea to add the theme name to the configuration file. This is optional, because you can always add "-t zafta" on all your commands. I like to put it the configuration file because I like shorter command lines. If you don't put it in the configuration file or specify it on the command line, you won't use the template that you're expecting to. - -Edit the file to add the theme, add a title for the site, and specify that all of our content will use the TOML format. - -``` -$ vi config.toml -theme = "zafta" -baseurl = "" -languageCode = "en-us" -title = "zafta - totally refreshing" -MetaDataFormat = "toml" -:wq - -$ -``` - -### Generate the Site - -Now that we have an empty theme, let's generate the site again. - -``` -$ hugo --verbose -INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/ -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ -WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] -0 draft content -0 future content -0 pages created -0 tags created -0 categories created -in 2 ms -$ -``` - -Did you notice that the output is different? The warning message for the home page has disappeared and we have an additional information line saying that Hugo is syncing from the theme's directory. - -Let's check the public/ directory to see what Hugo's created. - -``` -$ ls -l public -total 16 -drwxr-xr-x 2 quoha staff 68 Sep 29 17:56 css --rw-r--r-- 1 quoha staff 0 Sep 29 17:56 index.html --rw-r--r-- 1 quoha staff 407 Sep 29 17:56 index.xml -drwxr-xr-x 2 quoha staff 68 Sep 29 17:56 js --rw-r--r-- 1 quoha staff 243 Sep 29 17:56 sitemap.xml -$ -``` - -Notice four things: - -1. Hugo created a home page. This is the file public/index.html. -2. Hugo created a css/ directory. -3. Hugo created a js/ directory. -4. Hugo claimed that it created 0 pages. It created a file and copied over static files, but didn't create any pages. That's because it considers a "page" to be a file created directly from a content file. It doesn't count things like the index.html files that it creates automatically. - -#### The Home Page - -Hugo supports many different types of templates. The home page is special because it gets its own type of template and its own template file. The file, layouts/index.html, is used to generate the HTML for the home page. The Hugo documentation says that this is the only required template, but that depends. Hugo's warning message shows that it looks for three different templates: - -``` -WARN: 2014/09/29 Unable to locate layout: [index.html _default/list.html _default/single.html] -``` - -If it can't find any of these, it completely skips creating the home page. We noticed that when we built the site without having a theme installed. - -When Hugo created our theme, it created an empty home page template. Now, when we build the site, Hugo finds the template and uses it to generate the HTML for the home page. Since the template file is empty, the HTML file is empty, too. If the template had any rules in it, then Hugo would have used them to generate the home page. - -``` -$ find . -name index.html | xargs ls -l --rw-r--r-- 1 quoha staff 0 Sep 29 20:21 ./public/index.html --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 ./themes/zafta/layouts/index.html -$ -``` - -#### The Magic of Static - -Hugo does two things when generating the site. It uses templates to transform content into HTML and it copies static files into the site. Unlike content, static files are not transformed. They are copied exactly as they are. - -Hugo assumes that your site will use both CSS and JavaScript, so it creates directories in your theme to hold them. Remember opinions? Well, Hugo's opinion is that you'll store your CSS in a directory named css/ and your JavaScript in a directory named js/. If you don't like that, you can change the directory names in your theme directory or even delete them completely. Hugo's nice enough to offer its opinion, then behave nicely if you disagree. - -``` -$ find themes/zafta -type d | xargs ls -ld -drwxr-xr-x 7 quoha staff 238 Sep 29 17:38 themes/zafta -drwxr-xr-x 3 quoha staff 102 Sep 29 17:31 themes/zafta/archetypes -drwxr-xr-x 5 quoha staff 170 Sep 29 17:31 themes/zafta/layouts -drwxr-xr-x 4 quoha staff 136 Sep 29 17:31 themes/zafta/layouts/_default -drwxr-xr-x 4 quoha staff 136 Sep 29 17:31 themes/zafta/layouts/partials -drwxr-xr-x 4 quoha staff 136 Sep 29 17:31 themes/zafta/static -drwxr-xr-x 2 quoha staff 68 Sep 29 17:31 themes/zafta/static/css -drwxr-xr-x 2 quoha staff 68 Sep 29 17:31 themes/zafta/static/js -$ -``` - -## The Theme Development Cycle - -When you're working on a theme, you will make changes in the theme's directory, rebuild the site, and check your changes in the browser. Hugo makes this very easy: - -1. Purge the public/ directory. -2. Run the built in web server in watch mode. -3. Open your site in a browser. -4. Update the theme. -5. Glance at your browser window to see changes. -6. Return to step 4. - -I’ll throw in one more opinion: never work on a theme on a live site. Always work on a copy of your site. Make changes to your theme, test them, then copy them up to your site. For added safety, use a tool like Git to keep a revision history of your content and your theme. Believe me when I say that it is too easy to lose both your mind and your changes. - -Check the main Hugo site for information on using Git with Hugo. - -### Purge the public/ Directory - -When generating the site, Hugo will create new files and update existing ones in the ```public/``` directory. It will not delete files that are no longer used. For example, files that were created in the wrong directory or with the wrong title will remain. If you leave them, you might get confused by them later. I recommend cleaning out your site prior to generating it. - -Note: If you're building on an SSD, you should ignore this. Churning on a SSD can be costly. - -### Hugo's Watch Option - -Hugo's "`--watch`" option will monitor the content/ and your theme directories for changes and rebuild the site automatically. - -### Live Reload - -Hugo's built in web server supports live reload. As pages are saved on the server, the browser is told to refresh the page. Usually, this happens faster than you can say, "Wow, that's totally amazing." - -### Development Commands - -Use the following commands as the basis for your workflow. - -``` -## purge old files. hugo will recreate the public directory. -## -$ rm -rf public -## -## run hugo in watch mode -## -$ hugo server --watch --verbose -``` - -Here's sample output showing Hugo detecting a change to the template for the home page. Once generated, the web browser automatically reloaded the page. I've said this before, it's amazing. - - -``` -$ rm -rf public -$ hugo server --watch --verbose -INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/ -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ -WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] -0 draft content -0 future content -0 pages created -0 tags created -0 categories created -in 2 ms -Watching for changes in /Users/quoha/Sites/zafta/content -Serving pages from /Users/quoha/Sites/zafta/public -Web Server is available at http://localhost:1313 -Press Ctrl+C to stop -INFO: 2014/09/29 File System Event: ["/Users/quoha/Sites/zafta/themes/zafta/layouts/index.html": MODIFY|ATTRIB] -Change detected, rebuilding site - -WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] -0 draft content -0 future content -0 pages created -0 tags created -0 categories created -in 1 ms -``` - -## Update the Home Page Template - -The home page is one of a few special pages that Hugo creates automatically. As mentioned earlier, it looks for one of three files in the theme's layout/ directory: - -1. index.html -2. _default/list.html -3. _default/single.html - -We could update one of the default templates, but a good design decision is to update the most specific template available. That's not a hard and fast rule (in fact, we'll break it a few times in this tutorial), but it is a good generalization. - -### Make a Static Home Page - -Right now, that page is empty because we don't have any content and we don't have any logic in the template. Let's change that by adding some text to the template. - -``` -$ vi themes/zafta/layouts/index.html - - - -

hugo says hello!

- - -:wq - -$ -``` - -Build the web site and then verify the results. - -``` -$ hugo --verbose -INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/ -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ -WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] -0 draft content -0 future content -0 pages created -0 tags created -0 categories created -in 2 ms - -$ find public -type f -name '*.html' | xargs ls -l --rw-r--r-- 1 quoha staff 78 Sep 29 21:26 public/index.html - -$ cat public/index.html - - - -

hugo says hello!

- -``` - -#### Live Reload - -Note: If you're running the server with the `--watch` option, you'll see different content in the file: - -``` -$ cat public/index.html - - - -

hugo says hello!

- - -``` - -When you use `--watch`, the Live Reload script is added by Hugo. Look for live reload in the documentation to see what it does and how to disable it. - -### Build a "Dynamic" Home Page - -"Dynamic home page?" Hugo's a static web site generator, so this seems an odd thing to say. I mean let's have the home page automatically reflect the content in the site every time Hugo builds it. We'll use iteration in the template to do that. - -#### Create New Posts - -Now that we have the home page generating static content, let's add some content to the site. We'll display these posts as a list on the home page and on their own page, too. - -Hugo has a command to generate a skeleton post, just like it does for sites and themes. - -``` -$ hugo --verbose new post/first.md -INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml -INFO: 2014/09/29 attempting to create post/first.md of post -INFO: 2014/09/29 curpath: /Users/quoha/Sites/zafta/themes/zafta/archetypes/default.md -ERROR: 2014/09/29 Unable to Cast to map[string]interface{} - -$ -``` - -That wasn't very nice, was it? - -The "new" command uses an archetype to create the post file. Hugo created an empty default archetype file, but that causes an error when there's a theme. For me, the workaround was to create an archetypes file specifically for the post type. - -``` -$ vi themes/zafta/archetypes/post.md -+++ -Description = "" -Tags = [] -Categories = [] -+++ -:wq - -$ find themes/zafta/archetypes -type f | xargs ls -l --rw-r--r-- 1 quoha staff 0 Sep 29 21:53 themes/zafta/archetypes/default.md --rw-r--r-- 1 quoha staff 51 Sep 29 21:54 themes/zafta/archetypes/post.md - -$ hugo --verbose new post/first.md -INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml -INFO: 2014/09/29 attempting to create post/first.md of post -INFO: 2014/09/29 curpath: /Users/quoha/Sites/zafta/themes/zafta/archetypes/post.md -INFO: 2014/09/29 creating /Users/quoha/Sites/zafta/content/post/first.md -/Users/quoha/Sites/zafta/content/post/first.md created - -$ hugo --verbose new post/second.md -INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml -INFO: 2014/09/29 attempting to create post/second.md of post -INFO: 2014/09/29 curpath: /Users/quoha/Sites/zafta/themes/zafta/archetypes/post.md -INFO: 2014/09/29 creating /Users/quoha/Sites/zafta/content/post/second.md -/Users/quoha/Sites/zafta/content/post/second.md created - -$ ls -l content/post -total 16 --rw-r--r-- 1 quoha staff 104 Sep 29 21:54 first.md --rw-r--r-- 1 quoha staff 105 Sep 29 21:57 second.md - -$ cat content/post/first.md -+++ -Categories = [] -Description = "" -Tags = [] -date = "2014-09-29T21:54:53-05:00" -title = "first" - -+++ -my first post - -$ cat content/post/second.md -+++ -Categories = [] -Description = "" -Tags = [] -date = "2014-09-29T21:57:09-05:00" -title = "second" - -+++ -my second post - -$ -``` - -Build the web site and then verify the results. - -``` -$ rm -rf public -$ hugo --verbose -INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/ -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ -INFO: 2014/09/29 found taxonomies: map[string]string{"category":"categories", "tag":"tags"} -WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] -0 draft content -0 future content -2 pages created -0 tags created -0 categories created -in 4 ms -$ -``` - -The output says that it created 2 pages. Those are our new posts: - -``` -$ find public -type f -name '*.html' | xargs ls -l --rw-r--r-- 1 quoha staff 78 Sep 29 22:13 public/index.html --rw-r--r-- 1 quoha staff 0 Sep 29 22:13 public/post/first/index.html --rw-r--r-- 1 quoha staff 0 Sep 29 22:13 public/post/index.html --rw-r--r-- 1 quoha staff 0 Sep 29 22:13 public/post/second/index.html -$ -``` - -The new files are empty because because the templates used to generate the content are empty. The homepage doesn't show the new content, either. We have to update the templates to add the posts. - -### List and Single Templates - -In Hugo, we have three major kinds of templates. There's the home page template that we updated previously. It is used only by the home page. We also have "single" templates which are used to generate output for a single content file. We also have "list" templates that are used to group multiple pieces of content before generating output. - -Generally speaking, list templates are named "list.html" and single templates are named "single.html." - -There are three other types of templates: partials, content views, and terms. We will not go into much detail on these. - -### Add Content to the Homepage - -The home page will contain a list of posts. Let's update its template to add the posts that we just created. The logic in the template will run every time we build the site. - -``` -$ vi themes/zafta/layouts/index.html - - - - {{ range first 10 .Data.Pages }} -

{{ .Title }}

- {{ end }} - - -:wq - -$ -``` - -Hugo uses the Go template engine. That engine scans the template files for commands which are enclosed between "{{" and "}}". In our template, the commands are: - -1. range -2. .Title -3. end - -The "range" command is an iterator. We're going to use it to go through the first ten pages. Every HTML file that Hugo creates is treated as a page, so looping through the list of pages will look at every file that will be created. - -The ".Title" command prints the value of the "title" variable. Hugo pulls it from the front matter in the Markdown file. - -The "end" command signals the end of the range iterator. The engine loops back to the top of the iteration when it finds "end." Everything between the "range" and "end" is evaluated every time the engine goes through the iteration. In this file, that would cause the title from the first ten pages to be output as heading level one. - -It's helpful to remember that some variables, like .Data, are created before any output files. Hugo loads every content file into the variable and then gives the template a chance to process before creating the HTML files. - -Build the web site and then verify the results. - -``` -$ rm -rf public -$ hugo --verbose -INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/ -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ -INFO: 2014/09/29 found taxonomies: map[string]string{"tag":"tags", "category":"categories"} -WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] -0 draft content -0 future content -2 pages created -0 tags created -0 categories created -in 4 ms -$ find public -type f -name '*.html' | xargs ls -l --rw-r--r-- 1 quoha staff 94 Sep 29 22:23 public/index.html --rw-r--r-- 1 quoha staff 0 Sep 29 22:23 public/post/first/index.html --rw-r--r-- 1 quoha staff 0 Sep 29 22:23 public/post/index.html --rw-r--r-- 1 quoha staff 0 Sep 29 22:23 public/post/second/index.html -$ cat public/index.html - - - - -

second

- -

first

- - - -$ -``` - -Congratulations, the home page shows the title of the two posts. The posts themselves are still empty, but let's take a moment to appreciate what we've done. Your template now generates output dynamically. Believe it or not, by inserting the range command inside of those curly braces, you've learned everything you need to know to build a theme. All that's really left is understanding which template will be used to generate each content file and becoming familiar with the commands for the template engine. - -And, if that were entirely true, this tutorial would be much shorter. There are a few things to know that will make creating a new template much easier. Don't worry, though, that's all to come. - -### Add Content to the Posts - -We're working with posts, which are in the content/post/ directory. That means that their section is "post" (and if we don't do something weird, their type is also "post"). - -Hugo uses the section and type to find the template file for every piece of content. Hugo will first look for a template file that matches the section or type name. If it can't find one, then it will look in the _default/ directory. There are some twists that we'll cover when we get to categories and tags, but for now we can assume that Hugo will try post/single.html, then _default/single.html. - -Now that we know the search rule, let's see what we actually have available: - -``` -$ find themes/zafta -name single.html | xargs ls -l --rw-r--r-- 1 quoha staff 132 Sep 29 17:31 themes/zafta/layouts/_default/single.html -``` - -We could create a new template, post/single.html, or change the default. Since we don't know of any other content types, let's start with updating the default. - -Remember, any content that we haven't created a template for will end up using this template. That can be good or bad. Bad because I know that we're going to be adding different types of content and we're going to end up undoing some of the changes we've made. It's good because we'll be able to see immediate results. It's also good to start here because we can start to build the basic layout for the site. As we add more content types, we'll refactor this file and move logic around. Hugo makes that fairly painless, so we'll accept the cost and proceed. - -Please see the Hugo documentation on template rendering for all the details on determining which template to use. And, as the docs mention, if you're building a single page application (SPA) web site, you can delete all of the other templates and work with just the default single page. That's a refreshing amount of joy right there. - -#### Update the Template File - -``` -$ vi themes/zafta/layouts/_default/single.html - - - - {{ .Title }} - - -

{{ .Title }}

- {{ .Content }} - - -:wq - -$ -``` - -Build the web site and verify the results. - -``` -$ rm -rf public -$ hugo --verbose -INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/ -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ -INFO: 2014/09/29 found taxonomies: map[string]string{"tag":"tags", "category":"categories"} -WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] -0 draft content -0 future content -2 pages created -0 tags created -0 categories created -in 4 ms - -$ find public -type f -name '*.html' | xargs ls -l --rw-r--r-- 1 quoha staff 94 Sep 29 22:40 public/index.html --rw-r--r-- 1 quoha staff 125 Sep 29 22:40 public/post/first/index.html --rw-r--r-- 1 quoha staff 0 Sep 29 22:40 public/post/index.html --rw-r--r-- 1 quoha staff 128 Sep 29 22:40 public/post/second/index.html - -$ cat public/post/first/index.html - - - - first - - -

first

-

my first post

- - - - -$ cat public/post/second/index.html - - - - second - - -

second

-

my second post

- - - -$ -``` - -Notice that the posts now have content. You can go to localhost:1313/post/first to verify. - -### Linking to Content - -The posts are on the home page. Let's add a link from there to the post. Since this is the home page, we'll update its template. - -``` -$ vi themes/zafta/layouts/index.html - - - - {{ range first 10 .Data.Pages }} -

{{ .Title }}

- {{ end }} - - -``` - -Build the web site and verify the results. - -``` -$ rm -rf public -$ hugo --verbose -INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/ -INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/ -INFO: 2014/09/29 found taxonomies: map[string]string{"tag":"tags", "category":"categories"} -WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html] -0 draft content -0 future content -2 pages created -0 tags created -0 categories created -in 4 ms - -$ find public -type f -name '*.html' | xargs ls -l --rw-r--r-- 1 quoha staff 149 Sep 29 22:44 public/index.html --rw-r--r-- 1 quoha staff 125 Sep 29 22:44 public/post/first/index.html --rw-r--r-- 1 quoha staff 0 Sep 29 22:44 public/post/index.html --rw-r--r-- 1 quoha staff 128 Sep 29 22:44 public/post/second/index.html - -$ cat public/index.html - - - - -

second

- -

first

- - - - -$ -``` - -### Create a Post Listing - -We have the posts displaying on the home page and on their own page. We also have a file public/post/index.html that is empty. Let's make it show a list of all posts (not just the first ten). - -We need to decide which template to update. This will be a listing, so it should be a list template. Let's take a quick look and see which list templates are available. - -``` -$ find themes/zafta -name list.html | xargs ls -l --rw-r--r-- 1 quoha staff 0 Sep 29 17:31 themes/zafta/layouts/_default/list.html -``` - -As with the single post, we have to decide to update _default/list.html or create post/list.html. We still don't have multiple content types, so let's stay consistent and update the default list template. - -## Creating Top Level Pages - -Let's add an "about" page and display it at the top level (as opposed to a sub-level like we did with posts). - -The default in Hugo is to use the directory structure of the content/ directory to guide the location of the generated html in the public/ directory. Let's verify that by creating an "about" page at the top level: - -``` -$ vi content/about.md -+++ -title = "about" -description = "about this site" -date = "2014-09-27" -slug = "about time" -+++ - -## about us - -i'm speechless -:wq -``` - -Generate the web site and verify the results. - -``` -$ find public -name '*.html' | xargs ls -l --rw-rw-r-- 1 mdhender staff 334 Sep 27 15:08 public/about-time/index.html --rw-rw-r-- 1 mdhender staff 527 Sep 27 15:08 public/index.html --rw-rw-r-- 1 mdhender staff 358 Sep 27 15:08 public/post/first-post/index.html --rw-rw-r-- 1 mdhender staff 0 Sep 27 15:08 public/post/index.html --rw-rw-r-- 1 mdhender staff 342 Sep 27 15:08 public/post/second-post/index.html -``` - -Notice that the page wasn't created at the top level. It was created in a sub-directory named 'about-time/'. That name came from our slug. Hugo will use the slug to name the generated content. It's a reasonable default, by the way, but we can learn a few things by fighting it for this file. - -One other thing. Take a look at the home page. - -``` -$ cat public/index.html - - - -

creating a new theme

-

about

-

second

-

first

- - -``` - -Notice that the "about" link is listed with the posts? That's not desirable, so let's change that first. - -``` -$ vi themes/zafta/layouts/index.html - - - -

posts

- {{ range first 10 .Data.Pages }} - {{ if eq .Type "post"}} -

{{ .Title }}

- {{ end }} - {{ end }} - -

pages

- {{ range .Data.Pages }} - {{ if eq .Type "page" }} -

{{ .Title }}

- {{ end }} - {{ end }} - - -:wq -``` - -Generate the web site and verify the results. The home page has two sections, posts and pages, and each section has the right set of headings and links in it. - -But, that about page still renders to about-time/index.html. - -``` -$ find public -name '*.html' | xargs ls -l --rw-rw-r-- 1 mdhender staff 334 Sep 27 15:33 public/about-time/index.html --rw-rw-r-- 1 mdhender staff 645 Sep 27 15:33 public/index.html --rw-rw-r-- 1 mdhender staff 358 Sep 27 15:33 public/post/first-post/index.html --rw-rw-r-- 1 mdhender staff 0 Sep 27 15:33 public/post/index.html --rw-rw-r-- 1 mdhender staff 342 Sep 27 15:33 public/post/second-post/index.html -``` - -Knowing that hugo is using the slug to generate the file name, the simplest solution is to change the slug. Let's do it the hard way and change the permalink in the configuration file. - -``` -$ vi config.toml -[permalinks] - page = "/:title/" - about = "/:filename/" -``` - -Generate the web site and verify that this didn't work. Hugo lets "slug" or "URL" override the permalinks setting in the configuration file. Go ahead and comment out the slug in content/about.md, then generate the web site to get it to be created in the right place. - -## Sharing Templates - -If you've been following along, you probably noticed that posts have titles in the browser and the home page doesn't. That's because we didn't put the title in the home page's template (layouts/index.html). That's an easy thing to do, but let's look at a different option. - -We can put the common bits into a shared template that's stored in the themes/zafta/layouts/partials/ directory. - -### Create the Header and Footer Partials - -In Hugo, a partial is a sugar-coated template. Normally a template reference has a path specified. Partials are different. Hugo searches for them along a TODO defined search path. This makes it easier for end-users to override the theme's presentation. - -``` -$ vi themes/zafta/layouts/partials/header.html - - - - {{ .Title }} - - -:wq - -$ vi themes/zafta/layouts/partials/footer.html - - -:wq -``` - -### Update the Home Page Template to Use the Partials - -The most noticeable difference between a template call and a partials call is the lack of path: - -``` -{{ template "theme/partials/header.html" . }} -``` -versus -``` -{{ partial "header.html" . }} -``` -Both pass in the context. - -Let's change the home page template to use these new partials. - -``` -$ vi themes/zafta/layouts/index.html -{{ partial "header.html" . }} - -

posts

- {{ range first 10 .Data.Pages }} - {{ if eq .Type "post"}} -

{{ .Title }}

- {{ end }} - {{ end }} - -

pages

- {{ range .Data.Pages }} - {{ if or (eq .Type "page") (eq .Type "about") }} -

{{ .Type }} - {{ .Title }} - {{ .RelPermalink }}

- {{ end }} - {{ end }} - -{{ partial "footer.html" . }} -:wq -``` - -Generate the web site and verify the results. The title on the home page is now "your title here", which comes from the "title" variable in the config.toml file. - -### Update the Default Single Template to Use the Partials - -``` -$ vi themes/zafta/layouts/_default/single.html -{{ partial "header.html" . }} - -

{{ .Title }}

- {{ .Content }} - -{{ partial "footer.html" . }} -:wq -``` - -Generate the web site and verify the results. The title on the posts and the about page should both reflect the value in the markdown file. - -## Add “Date Published” to Posts - -It's common to have posts display the date that they were written or published, so let's add that. The front matter of our posts has a variable named "date." It's usually the date the content was created, but let's pretend that's the value we want to display. - -### Add “Date Published” to the Template - -We'll start by updating the template used to render the posts. The template code will look like: - -``` -{{ .Date.Format "Mon, Jan 2, 2006" }} -``` - -Posts use the default single template, so we'll change that file. - -``` -$ vi themes/zafta/layouts/_default/single.html -{{ partial "header.html" . }} - -

{{ .Title }}

-

{{ .Date.Format "Mon, Jan 2, 2006" }}

- {{ .Content }} - -{{ partial "footer.html" . }} -:wq -``` - -Generate the web site and verify the results. The posts now have the date displayed in them. There's a problem, though. The "about" page also has the date displayed. - -As usual, there are a couple of ways to make the date display only on posts. We could do an "if" statement like we did on the home page. Another way would be to create a separate template for posts. - -The "if" solution works for sites that have just a couple of content types. It aligns with the principle of "code for today," too. - -Let's assume, though, that we've made our site so complex that we feel we have to create a new template type. In Hugo-speak, we're going to create a section template. - -Let's restore the default single template before we forget. - -``` -$ mkdir themes/zafta/layouts/post -$ vi themes/zafta/layouts/_default/single.html -{{ partial "header.html" . }} - -

{{ .Title }}

- {{ .Content }} - -{{ partial "footer.html" . }} -:wq -``` - -Now we'll update the post's version of the single template. If you remember Hugo's rules, the template engine will use this version over the default. - -``` -$ vi themes/zafta/layouts/post/single.html -{{ partial "header.html" . }} - -

{{ .Title }}

-

{{ .Date.Format "Mon, Jan 2, 2006" }}

- {{ .Content }} - -{{ partial "footer.html" . }} -:wq - -``` - -Note that we removed the date logic from the default template and put it in the post template. Generate the web site and verify the results. Posts have dates and the about page doesn't. - -### Don't Repeat Yourself - -DRY is a good design goal and Hugo does a great job supporting it. Part of the art of a good template is knowing when to add a new template and when to update an existing one. While you're figuring that out, accept that you'll be doing some refactoring. Hugo makes that easy and fast, so it's okay to delay splitting up a template. diff --git a/content/posts/goisforlovers.md b/content/posts/goisforlovers.md deleted file mode 100644 index df125d82..00000000 --- a/content/posts/goisforlovers.md +++ /dev/null @@ -1,344 +0,0 @@ -+++ -title = "(Hu)go Template Primer" -description = "" -tags = [ - "go", - "golang", - "templates", - "themes", - "development", -] -date = "2014-04-02" -categories = [ - "Development", - "golang", -] -menu = "main" -+++ - -Hugo uses the excellent [Go][] [html/template][gohtmltemplate] library for -its template engine. It is an extremely lightweight engine that provides a very -small amount of logic. In our experience that it is just the right amount of -logic to be able to create a good static website. If you have used other -template systems from different languages or frameworks you will find a lot of -similarities in Go templates. - -This document is a brief primer on using Go templates. The [Go docs][gohtmltemplate] -provide more details. - -## Introduction to Go Templates - -Go templates provide an extremely simple template language. It adheres to the -belief that only the most basic of logic belongs in the template or view layer. -One consequence of this simplicity is that Go templates parse very quickly. - -A unique characteristic of Go templates is they are content aware. Variables and -content will be sanitized depending on the context of where they are used. More -details can be found in the [Go docs][gohtmltemplate]. - -## Basic Syntax - -Golang templates are HTML files with the addition of variables and -functions. - -**Go variables and functions are accessible within {{ }}** - -Accessing a predefined variable "foo": - - {{ foo }} - -**Parameters are separated using spaces** - -Calling the add function with input of 1, 2: - - {{ add 1 2 }} - -**Methods and fields are accessed via dot notation** - -Accessing the Page Parameter "bar" - - {{ .Params.bar }} - -**Parentheses can be used to group items together** - - {{ if or (isset .Params "alt") (isset .Params "caption") }} Caption {{ end }} - - -## Variables - -Each Go template has a struct (object) made available to it. In hugo each -template is passed either a page or a node struct depending on which type of -page you are rendering. More details are available on the -[variables](/layout/variables) page. - -A variable is accessed by referencing the variable name. - - {{ .Title }} - -Variables can also be defined and referenced. - - {{ $address := "123 Main St."}} - {{ $address }} - - -## Functions - -Go template ship with a few functions which provide basic functionality. The Go -template system also provides a mechanism for applications to extend the -available functions with their own. [Hugo template -functions](/layout/functions) provide some additional functionality we believe -are useful for building websites. Functions are called by using their name -followed by the required parameters separated by spaces. Template -functions cannot be added without recompiling hugo. - -**Example:** - - {{ add 1 2 }} - -## Includes - -When including another template you will pass to it the data it will be -able to access. To pass along the current context please remember to -include a trailing dot. The templates location will always be starting at -the /layout/ directory within Hugo. - -**Example:** - - {{ template "chrome/header.html" . }} - - -## Logic - -Go templates provide the most basic iteration and conditional logic. - -### Iteration - -Just like in Go, the Go templates make heavy use of range to iterate over -a map, array or slice. The following are different examples of how to use -range. - -**Example 1: Using Context** - - {{ range array }} - {{ . }} - {{ end }} - -**Example 2: Declaring value variable name** - - {{range $element := array}} - {{ $element }} - {{ end }} - -**Example 2: Declaring key and value variable name** - - {{range $index, $element := array}} - {{ $index }} - {{ $element }} - {{ end }} - -### Conditionals - -If, else, with, or, & and provide the framework for handling conditional -logic in Go Templates. Like range, each statement is closed with `end`. - - -Go Templates treat the following values as false: - -* false -* 0 -* any array, slice, map, or string of length zero - -**Example 1: If** - - {{ if isset .Params "title" }}

{{ index .Params "title" }}

{{ end }} - -**Example 2: If -> Else** - - {{ if isset .Params "alt" }} - {{ index .Params "alt" }} - {{else}} - {{ index .Params "caption" }} - {{ end }} - -**Example 3: And & Or** - - {{ if and (or (isset .Params "title") (isset .Params "caption")) (isset .Params "attr")}} - -**Example 4: With** - -An alternative way of writing "if" and then referencing the same value -is to use "with" instead. With rebinds the context `.` within its scope, -and skips the block if the variable is absent. - -The first example above could be simplified as: - - {{ with .Params.title }}

{{ . }}

{{ end }} - -**Example 5: If -> Else If** - - {{ if isset .Params "alt" }} - {{ index .Params "alt" }} - {{ else if isset .Params "caption" }} - {{ index .Params "caption" }} - {{ end }} - -## Pipes - -One of the most powerful components of Go templates is the ability to -stack actions one after another. This is done by using pipes. Borrowed -from unix pipes, the concept is simple, each pipeline's output becomes the -input of the following pipe. - -Because of the very simple syntax of Go templates, the pipe is essential -to being able to chain together function calls. One limitation of the -pipes is that they only can work with a single value and that value -becomes the last parameter of the next pipeline. - -A few simple examples should help convey how to use the pipe. - -**Example 1 :** - - {{ if eq 1 1 }} Same {{ end }} - -is the same as - - {{ eq 1 1 | if }} Same {{ end }} - -It does look odd to place the if at the end, but it does provide a good -illustration of how to use the pipes. - -**Example 2 :** - - {{ index .Params "disqus_url" | html }} - -Access the page parameter called "disqus_url" and escape the HTML. - -**Example 3 :** - - {{ if or (or (isset .Params "title") (isset .Params "caption")) (isset .Params "attr")}} - Stuff Here - {{ end }} - -Could be rewritten as - - {{ isset .Params "caption" | or isset .Params "title" | or isset .Params "attr" | if }} - Stuff Here - {{ end }} - - -## Context (aka. the dot) - -The most easily overlooked concept to understand about Go templates is that {{ . }} -always refers to the current context. In the top level of your template this -will be the data set made available to it. Inside of a iteration it will have -the value of the current item. When inside of a loop the context has changed. . -will no longer refer to the data available to the entire page. If you need to -access this from within the loop you will likely want to set it to a variable -instead of depending on the context. - -**Example:** - - {{ $title := .Site.Title }} - {{ range .Params.tags }} -
  • {{ . }} - {{ $title }}
  • - {{ end }} - -Notice how once we have entered the loop the value of {{ . }} has changed. We -have defined a variable outside of the loop so we have access to it from within -the loop. - -# Hugo Parameters - -Hugo provides the option of passing values to the template language -through the site configuration (for sitewide values), or through the meta -data of each specific piece of content. You can define any values of any -type (supported by your front matter/config format) and use them however -you want to inside of your templates. - - -## Using Content (page) Parameters - -In each piece of content you can provide variables to be used by the -templates. This happens in the [front matter](/content/front-matter). - -An example of this is used in this documentation site. Most of the pages -benefit from having the table of contents provided. Sometimes the TOC just -doesn't make a lot of sense. We've defined a variable in our front matter -of some pages to turn off the TOC from being displayed. - -Here is the example front matter: - -``` ---- -title: "Permalinks" -date: "2013-11-18" -aliases: - - "/doc/permalinks/" -groups: ["extras"] -groups_weight: 30 -notoc: true ---- -``` - -Here is the corresponding code inside of the template: - - {{ if not .Params.notoc }} -
    - {{ .TableOfContents }} -
    - {{ end }} - - - -## Using Site (config) Parameters -In your top-level configuration file (eg, `config.yaml`) you can define site -parameters, which are values which will be available to you in chrome. - -For instance, you might declare: - -```yaml -params: - CopyrightHTML: "Copyright © 2013 John Doe. All Rights Reserved." - TwitterUser: "spf13" - SidebarRecentLimit: 5 -``` - -Within a footer layout, you might then declare a `