Published
Edited
Mar 4, 2021
4 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
maxCO2 = d3.max(envData.filter(x => countries.features.some(f => f.properties.name === x.country)), x => +x.co2_per_capita)
Insert cell
Insert cell
data = {
const position = []
const cdata = []
let maxCO2 = 40;

for (const feature of countries.features) {
let coordinates;
if (feature.geometry.type == "Polygon") {
coordinates = feature.geometry.coordinates
} else if (feature.geometry.type == "MultiPolygon") {
coordinates = feature.geometry.coordinates[0]
} else {
throw `All elements must be polygons or multipolgyons. ${feature.geometry}`
}
const center = (() => {
const centers = coordinates.map(coords =>
[
d3.mean(coords, x => x[0]),
d3.mean(coords, x => x[1]),
]
)
return centers[0]
})();
if (feature.id) {
const { cenv: envData } = countryLookupTable.get(+feature.id) ?? { cenv: [] }
const cenv = envData.filter(x => +x.year === year);
const scale = (() => {
if (cenv.length === 0) {
return 0;
}

const obs = cenv[cenv.length - 1];
// console.log(obs)

const v = +obs.co2_per_capita;
// const scale = v / maxCO2
// console.log(feature.properties.name, v)
// maxCO2 = Math.max(maxCO2, v)
return v;
})();
// console.log(scale)
// console.log(color.r, color.g, color.b)

cdata.push({ center, id: +feature.id, scale })
}
}
// console.log({ maxCO2 })
return {
position: gl.regl.buffer(cdata.map(x => polarToCartesian(x.center[0], x.center[1], 1 + 0.01))),
countryIndex: gl.regl.buffer({
data: cdata.map(x => {
const u = Math.floor(x.id / 32)
const v = x.id - (u * 32)
const e = 1 / 32 / 2
return [v / 32 + e, u / 32 + e]
})
}),
count: cdata.length,
offset: gl.regl.buffer(cdata.map(x => {
return polarToCartesian(x.center[0], x.center[1], 1)
})),
rotation: gl.regl.buffer(cdata.map((x, i) => {
// return [0, 0, 0, 0];
// center: [lon, lat]
// console.log(x.center[0])
// 0 -> 90, 20 -> 70, -20 -> 110
const q = quat.fromEuler([], 0, -x.center[1] + 90, x.center[0]);
// if (i < 3) {
// console.log(x.center[1], -x.center[1] + 90, q)
// }
return q
})),
scale: gl.regl.buffer(cdata.map(x => Math.max(0.01, x.scale / maxCO2))),
color: gl.regl.buffer(cdata.map(x => {
const v = Math.max(0.01, x.scale / maxCO2)
const color = d3.color(interpolateColor(v))
// console.log(x.scale)
return [color.r / 255, color.g / 255, color.b / 255, 1]
})),
}
}
Insert cell
Insert cell
Insert cell
drawCountry = gl.regl({
vert: `
precision mediump float;

uniform mat4 model, view, projection;

attribute vec3 position;

void main () {
gl_Position = projection * view * model * vec4(position, 1);
}
`,
frag: `
precision mediump float;

void main () {
gl_FragColor = vec4(0, 0, 0, 0.5);
}
`,
attributes: {
position: gl.regl.prop("position")
},
uniforms: {
model: gl.regl.prop("model"),
},
elements: gl.regl.prop("elements"),
})
Insert cell
drawCountryData = gl.regl({
vert: `
precision mediump float;

uniform mat4 model, view, projection;

attribute vec3 position;
attribute vec2 countryIndex;

varying vec2 uv;

void main () {
gl_PointSize = 4.;
uv = countryIndex;
gl_Position = projection * view * model * vec4(position, 1);
}
`,
frag: `
precision mediump float;

uniform sampler2D texture;

varying vec2 uv;

void main () {
gl_FragColor = texture2D(texture, uv);
}
`,
attributes: {
position: gl.regl.prop("position"),
countryIndex: gl.regl.prop("countryIndex"),
},
uniforms: {
model: gl.regl.prop("model"),
texture: gl.regl.prop("texture"),
},
primitive: 'points',
count: gl.regl.prop("count"),
})
Insert cell
setupCamera = gl.regl({
context: {
projection: (context, props) =>
mat4.perspective(
[],
Math.PI / 4,
context.viewportWidth / context.viewportHeight,
0.01,
4 * 0.92 * Math.sqrt(Math.pow(3 * Math.cos(props.time), 2) + Math.pow(3 * Math.sin(props.time), 2)),
),

view: (context, props) =>
mat4.lookAt(
[],
[
3 * Math.cos(props.time),
3 * Math.sin(props.time),
0.6,
],
[0, 0, 0],
[0, 0, 1],
)
},

uniforms: {
view: gl.regl.context('view'),
projection: gl.regl.context('projection')
}
})
Insert cell
function draw(time) {
gl.regl.clear({
color: [1, 1, 1, 1],
depth: 1,
})
setupCamera({ time }, () => {
const model = mat4.identity([])

const { position, elements } = features
drawCountry({
model,
position,
elements
})
const texture = mkTexture(year);
// drawCountryData({
// model,
// position: data.position,
// countryIndex: data.countryIndex,
// count: data.count,
// texture,
// })
drawCylinder({
model,
countryIndex: data.countryIndex,
texture,
})

// drawGraticule(graticule.map(points => ({
// model,
// position: points,
// count: points.length,
// })))
})
}
Insert cell
draw(now / 5000)
Insert cell
function polarToCartesian(lon0, lat0, R) {
const lat = lat0 * Math.PI / 180
const lon = lon0 * Math.PI / 180
const x = R * Math.cos(lat) * Math.cos(lon)
const y = R * Math.cos(lat) * Math.sin(lon)
const z = R * Math.sin(lat)

return [x, y, z];
}
Insert cell
interpolateColor = d3.interpolatePlasma
Insert cell
envData = d3.csvParse(await fetch("https://raw.githubusercontent.com/owid/co2-data/master/owid-co2-data.csv").then(res => res.text()))
Insert cell
envData.sort((a, b) => +b.co2_per_capita - +a.co2_per_capita).map(x => ({ country: x.country, co2: +x.co2_per_capita }))
Insert cell
cylinder = createCylinderMesh(0.005, 0.005, 0.6, 16, 1)
Insert cell
function createCylinderMesh(
radiusTop = 1,
radiusBottom = 1,
height = 5,
radialSegments = 64,
heightSegments = 8
) {
var index = 0
var indexOffset = 0
var indexArray = []

var capCount = 0
if (radiusTop > 0) {
capCount++
}
if (radiusBottom > 0) {
capCount++
}

var vertexCount = ((radialSegments + 1) * (heightSegments + 1)) +
((radialSegments + 2) * capCount)
var cellCount = (radialSegments * heightSegments * 2) + (radialSegments * capCount)

var normals = new Array(vertexCount)
var vertices = new Array(vertexCount)
var uvs = new Array(vertexCount)
var cells = new Array(cellCount)

var slope = (radiusBottom - radiusTop) / height
var thetaLength = 2.0 * Math.PI

for (var zz = 0; zz <= heightSegments; zz++) {
var indexRow = []
var v = zz / heightSegments
var radius = v * (radiusBottom - radiusTop) + radiusTop

for (var xx = 0; xx <= radialSegments; xx++) {
var u = xx / radialSegments
var theta = u * thetaLength
var sinTheta = Math.sin(theta)
var cosTheta = Math.cos(theta)
vertices[index] = [radius * sinTheta, radius * cosTheta, -v * height + (height)]
normals[index] = [sinTheta, slope, cosTheta]
uvs[index] = [u, 1 - v]

indexRow.push(index)
index++
}

indexArray.push(indexRow)
}

for (var xx = 0; xx < radialSegments; xx++) {
for (var zz = 0; zz < heightSegments; zz++) {
var i1 = indexArray[zz][xx]
var i2 = indexArray[zz + 1][xx]
var i3 = indexArray[zz + 1][xx + 1]
var i4 = indexArray[zz][xx + 1]

// face one
cells[indexOffset] = [i1, i2, i4]
indexOffset++

// face two
cells[indexOffset] = [i2, i3, i4]
indexOffset++
}
}

var generateCap = function (top) {
var vertex = new Array(3).fill(0)

var radius = (top === true) ? radiusTop : radiusBottom
var sign = (top === true) ? 1 : 0

var centerIndexStart = index

for (var x = 1; x <= radialSegments; x++) {
vertices[index] = [0, 0, height * sign]
normals[index] = [0, sign, 0]
uvs[index] = [0.5, 0.5]
index++
}

var centerIndexEnd = index

for (var x = 0; x <= radialSegments; x++) {
var u = x / radialSegments
var theta = u * thetaLength
var cosTheta = Math.cos(theta)
var sinTheta = Math.sin(theta)
vertices[index] = [radius * sinTheta, radius * cosTheta, height * sign]
normals[index] = [0, sign, 0]
uvs[index] = [(cosTheta * 0.5) + 0.5, (sinTheta * 0.5 * sign) + 0.5]
index++
}

for (var xx = 0; xx < radialSegments; xx++) {
var c = centerIndexStart + xx
var i = centerIndexEnd + xx

if ( top === true ) {
// face top
cells[indexOffset] = [i, i + 1, c]
indexOffset++
} else {
// face bottom
cells[indexOffset] = [i + 1, i, c]
indexOffset++
}
}
}

if (radiusTop > 0) {
generateCap(true)
}

if (radiusBottom > 0) {
generateCap(false)
}

return {
uvs: uvs,
cells: cells,
normals: normals,
positions: vertices
}
}
Insert cell
Insert cell
countries = {
const world = await fetch("https://cdn.jsdelivr.net/npm/world-atlas@2/countries-10m.json")
.then(res => res.json())
return topojson.feature(world, world.objects.countries)
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more