Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save robertleeplummerjr/878fa3d9bbefde1e6bb111e27c0b04bc to your computer and use it in GitHub Desktop.
Save robertleeplummerjr/878fa3d9bbefde1e6bb111e27c0b04bc to your computer and use it in GitHub Desktop.
// taken from examples at gpu.js: https://github.com/gpujs/gpu.js/blob/develop/examples/mandelbrot-set.html
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { GLView } from 'expo-gl';
import { GPU } from '@gpujs/expo-gl';
export default function App() {
createKernel();
return (
<View style={styles.container}>
<Text>Open up App.js to start working on your app!</Text>
</View>
);
}
function createKernel(img) {
GLView.createContextAsync()
.then(context => {
function f(x, c) {
return [
(x[0] * x[0]) - (x[1] * x[1]) + c[0],
(x[0] * x[1]) + (x[0] * x[1]) + c[1],
];
}
function palette(t, a, b, c, d) {
return [
a[0] + b[0] * Math.cos(6.28318 * (c[0] * t + d[0])),
a[1] + b[1] * Math.cos(6.28318 * (c[1] * t + d[1])),
a[2] + b[2] * Math.cos(6.28318 * (c[2] * t + d[2]))
];
}
function vectorLength(vector) {
return Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]);
}
const gpu = new GPU({ context });
gpu
.addFunction(f)
.addFunction(palette)
.addFunction(vectorLength);
const calculateMandelbrotSet = gpu.createKernel(function(zoomCenter, zoomSize, maxIterations) {
let x = [0, 0];
let c = [
zoomCenter[0] + ((this.thread.x / this.output.x) * 4 - 2) * (zoomSize / 4),
zoomCenter[1] + ((this.thread.y / this.output.y) * 4 - 2) * (zoomSize / 4)
];
let escaped = false;
let iterations = 0;
for (let i = 0; i < maxIterations; i++) {
iterations = i;
x = f(x, c);
if (vectorLength(x) > 2) {
escaped = true;
break;
}
}
if (escaped) {
const pixel = palette(iterations / maxIterations, [0, 0, 0], [.59, .55, .75], [.1, .2, .3], [.75, .75, .75]);
return [pixel[0], pixel[1], pixel[2], 1];
} else {
return [.85, .99, 1, 1];
}
})
.setDebug(true)
.setOutput([800, 800]);
let targetZoomCenter = [0, 0],
zoomFactor = 1,
zoomCenter = [0, 0],
zoomSize = 4,
maxIterations = 500,
stopZooming = true;
const result = calculateMandelbrotSet(zoomCenter, zoomSize, maxIterations);
gpu.destroy();
});
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment