A growing three.js helper library.

Overview

Version License: MIT Twitter: alphardex007

kokomi.js

A growing three.js helper library.

Install

npm i kokomi.js

Hello world

With just several lines, you can make a most basic 3D scene :d

index.html

<div id="sketch" class="bg-black w-screen h-screen overflow-hidden"></div>

script.ts

import * as kokomi from "kokomi.js";

class Sketch extends kokomi.Base {
  create() {
    new kokomi.OrbitControls(this);

    const box = new kokomi.Box(this);
    box.addExisting();

    this.update((time: number) => {
      box.spin(time);
    });
  }
}

const createSketch = () => {
  const sketch = new Sketch();
  sketch.create();
  return sketch;
};

createSketch();

Demo (Also can be used as a template): https://codesandbox.io/s/kokomi-js-starter-tjh29w?file=/src/app.ts

Features

  • You can simply extend kokomi.Base class to kickstart a simple scene without writing any boilerplate codes.
  • Either you can write all your three.js code in a single file, or encapsulate your code into individual classes in a large project. By extending kokomi.Component, you can make your components keep their own state and animation.
  • kokomi.AssetManager can handle the preloads of assets (gltfModel, texture, cubeTexture, font, etc). You can just write a simple json file to config your assets without caring about various loaders.
  • Integrated with three.interactive, which can handle mouse and touch interactions easily.
  • Almost every class and function have online demo.

Previews

Basic Scene

1

Asset Manage

2

Util Geometry

3

Shadertoy Integration

4

Credit: https://www.shadertoy.com/view/XtyXzW

Index

API

Base

Base

By extending this class, you can kickstart a basic three.js scene easily.

class Sketch extends kokomi.Base {
  create() {
    // Write your own awesome code here...
  }
}

Demo: https://codesandbox.io/s/kokomi-js-starter-tjh29w?file=/src/app.ts

Camera

ScreenCamera

This camera can make the pixel unit of a WebGL element equals with one of a HTML Element. If combined with maku.js, you can easily merge HTML with WebGL!

class Sketch extends kokomi.Base {
  create() {
    const screenCamera = new kokomi.ScreenCamera(this);
    screenCamera.addExisting();
  }
}

Demo: https://codesandbox.io/s/kokomi-js-screen-camera-hpx78s?file=/src/app.ts

Components

AssetManager

This class can handle the preloads of assets (gltfModel, texture, cubeTexture, font, etc). You can just write a simple js file to config your assets without caring about various loaders.

import foxModel from "/models/Fox/glTF/Fox.gltf";

const resourceList: kokomi.ResourceItem[] = [
  {
    name: "foxModel",
    type: "gltfModel",
    path: foxModel,
  },
];

class Sketch extends kokomi.Base {
  assetManager: kokomi.AssetManager;
  constructor(sel = "#sketch") {
    super(sel);

    const assetManager = new kokomi.AssetManager(this, resourceList);
    this.assetManager = assetManager;
  }
  create() {
    this.assetManager.emitter.on("ready", () => {
      const fox = new Fox(this, this.assetManager.items.foxModel);
      fox.addExisting();
      fox.playAction("idle");
    });
  }
}

Demo: https://codesandbox.io/s/kokomi-js-asset-manager-13008e?file=/src/app.ts

Component

By extending this class, you can make your components keep their own state and animation.

class MyBox extends kokomi.Component {
  box: kokomi.Box;
  // component's own state
  constructor(base: kokomi.Base) {
    super(base);

    const box = new kokomi.Box(base);
    box.addExisting();
    this.box = box;
  }
  // component's own animation
  update(time: number): void {
    this.box.mesh.rotation.y = time / 1000;
  }
}

Demo: https://codesandbox.io/s/kokomi-js-component-wi812m?file=/src/app.ts

Physics

kokomi.js uses cannon.js for physics. Just create mesh and body, and add it to base's physics!

import * as THREE from "three";
import * as kokomi from "kokomi.js";
import * as CANNON from "cannon-es";

class Box extends kokomi.Component {
  mesh: THREE.Mesh;
  body: CANNON.Body;
  constructor(base: kokomi.Base) {
    super(base);

    const geometry = new THREE.BoxGeometry(2, 2, 0.5);
    const material = new THREE.MeshStandardMaterial({
      metalness: 0.3,
      roughness: 0.4,
    });
    const mesh = new THREE.Mesh(geometry, material);
    this.mesh = mesh;

    const shape = new CANNON.Box(new CANNON.Vec3(1, 1, 0.25));
    const body = new CANNON.Body({
      mass: 1,
      shape,
      position: new CANNON.Vec3(0, 1, 0),
    });
    this.body = body;
  }
  addExisting(): void {
    const { base, mesh, body } = this;
    const { scene, physics } = base;

    scene.add(mesh);
    physics.add({ mesh, body });
  }
}

Demo: https://codesandbox.io/s/kokomi-js-physics-tffxge?file=/src/app.ts

Stats

A drop-in fps meter powered by stats.js

class Sketch extends kokomi.Base {
  create() {
    new kokomi.Stats(this);
  }
}

Demo: https://codesandbox.io/s/kokomi-js-stats-zwhev9?file=/src/app.ts

Controls

OrbitControls

A drop-in orbitControls

class Sketch extends kokomi.Base {
  create() {
    new kokomi.OrbitControls(this);
  }
}

Demo: https://codesandbox.io/s/kokomi-js-starter-tjh29w?file=/src/app.ts

Geometries

HyperbolicHelicoid

A HyperbolicHelicoid geometry

class Sketch extends kokomi.Base {
  create() {
    const geometry = new kokomi.HyperbolicHelicoidGeometry(64, 64);
    const material = new THREE.MeshBasicMaterial();
    const mesh = new THREE.Mesh(geometry, material);
    this.scene.add(mesh);
  }
}

Demo: https://codesandbox.io/s/kokomi-js-geometry-hyperbolichelicoid-so35fy?file=/src/app.ts

Sphube

A Sphube geometry

class Sketch extends kokomi.Base {
  create() {
    const geometry = new kokomi.SphubeGeometry(64, 64);
    const material = new THREE.MeshBasicMaterial();
    const mesh = new THREE.Mesh(geometry, material);
    this.scene.add(mesh);
  }
}

Demo: https://codesandbox.io/s/kokomi-js-geometry-sphube-57x9k6?file=/src/app.ts

Shapes

Box

A cute box mesh that we can see everywhere

class Sketch extends kokomi.Base {
  create() {
    const box = new kokomi.Box(this);
    box.addExisting();
  }
}

Demo: https://codesandbox.io/s/kokomi-js-starter-tjh29w?file=/src/app.ts

ScreenQuad

A fullsceen plane with which you can create fullscreen effects such as raymarching.

By default, it has almost all the uniforms that shadertoy has: iTime, iResolution, iMouse, etc

If you just want to run your shadertoy shader locally, you can turn on shadertoyMode, which will inject all the shadertoy uniforms into the fragment shader as well as main() function for three.js. Thus, you can just copy & paste your shadertoy shader and run!

class Sketch extends kokomi.Base {
  create() {
    const screenQuad = new kokomi.ScreenQuad(this, {
      shadertoyMode: true,
      fragmentShader: `your fragment shader here`,
      uniforms: {},
    });
    screenQuad.addExisting();
  }
}

Demo (Also template): https://codesandbox.io/s/kokomi-js-screenquad-254wl8?file=/src/app.ts

Shadertoy: https://codesandbox.io/s/kokomi-js-shape-screenquad-gkxfxd?file=/src/app.ts

Utils

DOM

preloadImages

preload all the img element, powered by imagesloaded

class Sketch extends kokomi.Base {
  async create() {
    await kokomi.preloadImages();
  }
}

Demo: https://codesandbox.io/s/kokomi-js-screen-camera-hpx78s?file=/src/app.ts

GL

makeBuffer

A shortcut function to make a Float32Array buffer

class Sketch extends kokomi.Base {
  create() {
    const geometry = new THREE.BufferGeometry();
    const buffer = kokomi.makeBuffer(
      50,
      () => THREE.MathUtils.randFloat(-0.5, 0.5) * 4
    );
    geometry.setAttribute("position", new THREE.BufferAttribute(buffer, 3));
    // produced 50 random position triangles
  }
}

Demo: https://codesandbox.io/s/kokomi-js-makebuffer-11975d?file=/src/app.ts

iterateBuffer

A shortcut function to iterate through a Float32Array buffer

class Sketch extends kokomi.Base {
  create() {
    const geometry = new THREE.BufferGeometry();
    const count = 20000;
    const buffer = kokomi.makeBuffer(
      count,
      () => THREE.MathUtils.randFloat(-0.5, 0.5) * 10
    );

    kokomi.iterateBuffer(
      buffer,
      count,
      (arr: number[], axis: THREE.Vector3) => {
        arr[axis.y] = Math.sin(arr[axis.x]);
      }
    );
    geometry.setAttribute("position", new THREE.BufferAttribute(buffer, 3));
  }
}

Demo: https://codesandbox.io/s/kokomi-js-iteratebuffer-hycutz?file=/src/app.ts

Misc

enableRealisticRender

Give the three.js renderer some default parameters so that it can produce a realistic effect

class Sketch extends kokomi.Base {
  create() {
    kokomi.enableRealisticRender(this.renderer);
  }
}

Demo: https://codesandbox.io/s/kokomi-js-asset-manager-13008e?file=/src/app.ts

End

Author

👤 alphardex

Show your support

Give a ⭐️ if this project helped you!


This README was generated with ❤️ by readme-md-generator

You might also like...

A set of useful helper methods for writing functions to handle Cloudflare Pub/Sub messages (https://developers.cloudflare.com/pub-sub/)

pubsub A set of useful helper methods for writing functions to handle Cloudflare Pub/Sub messages. This includes: A isValidBrokerRequest helper for au

Dec 4, 2022

Elrond blockchain CLI helper tools - interaction with APIs, smart contracts and protocol

Buildo Begins 👷 Meet Buildo. He is here to help you start creating in the Elrond blockchain ecosystem. Here is where everything begins. I'm going on

Dec 30, 2022

A REST helper for Next.js APIs

REST controller for Next.js How does it work? Create restful controllers in Next.js Example: Inside /pages/api/auth/[...handler] (filename must be a r

Jul 30, 2022

Stumble Helper

Stumble Helper

How to get auth token ? Download : HTTP Cannary Install HTTP Cannary or any Traffic Intercept apk to your phone Intercept Stumble Guys ! Then play the

Oct 7, 2022

Helper package to handle requests to a jschan api instance.

jschan-api-sdk Helper package to handle requests to a jschan api instance. How to use npm install ussaohelcim/jschan-api-sdk const { jschan } = requir

Jun 30, 2022

A helper CLI for Plutus-Light

Hyperion This is a CLI meant to accompany the Plutus Light compiler. Installation [WIP] The end goal is to host Hyperion on NPM and make it available

Jul 27, 2022

A simple step by step tooltip helper for any site

A simple step by step tooltip helper for any site

Tooltip Sequence A minimalistic set of tooltips on your app. What it does So suppose you create a Web Application and you want to take your users or a

Dec 21, 2022

DALL-E 2 prompt helper browser extension

DALL-E 2 prompt helper browser extension

DALL-E prompt helper chrome extension Have you got access to the amazing DALL-E interface but struggling creating high quality renders? Looking for a

Sep 18, 2022

Shizuku Launcher is a simple AWS Virtual Machine helper.

shizuku-launcher-web Shizuku Launcher is a simple AWS Virtual Machine helper. Shizuku Launcher offers multiple solutions to keep your credential secur

Oct 11, 2022
Owner
Nameless God
I don't know everything, I just know what I know.
Nameless God
Um bot de suporte feito usando threads para o Discord, 100% customizável, feito em JavaScript e inspirado no Rio Helper do servidor Elixir Lab e na Loritta Helper do serivdor de suporte da Loritta.

Ticket Bot Um bot de suporte feito usando threads para o Discord, 100% customizável, feito em JavaScript e inspirado no Rio Helper do servidor Elixir

ADG 6 Dec 21, 2022
three.js examples. if you are first in learning three.js , this will give you much help.

three-projected-material Three.js Material which lets you do Texture Projection on a 3d Model. Installation After having installed three.js, install i

null 22 Nov 2, 2022
Text Engraving & Extrusion demo based on Three.js is implemented with Typescript and webpack5. Used THREE-CSGMesh as the core tech to achieve engraving and extrusion results

Text Engraving & Extrusion Text Engraving & Extrusion demo is implemented using Three.js, with Typescript and webpack5. Used THREE-CSGMesh as the core

Jiahong Li 3 Oct 12, 2022
A JavaScript Library for things I use often, as well as some helper functions

Elements A JavaScript Library for things I use often, as well as some helper functions. Full documentation below. Inspired by Habitat, another library

Magnogen 3 Apr 21, 2022
The Easel Javascript library provides a full, hierarchical display list, a core interaction model, and helper classes to make working with the HTML5 Canvas element much easier.

EaselJS EaselJS is a library for building high-performance interactive 2D content in HTML5. It provides a feature-rich display list to allow you to ma

CreateJS 8k Dec 29, 2022
Framework agnostic CLI tool for routes parsing and generation of a type-safe helper for safe route usage. 🗺️ Remix driver included. 🤟

About routes-gen is a framework agnostic CLI tool for routes parsing and generation of a type-safe helper for safe route usage. Think of it as Prisma,

Stratulat Alexandru 192 Jan 2, 2023
Babel plugin and helper functions for interoperation between Node.js native ESM and Babel ESM

babel-plugin-node-cjs-interop and node-cjs-interop: fix the default import interoperability issue in Node.js The problem to solve Consider the followi

Masaki Hara 15 Nov 6, 2022
A visual helper in vscode to use github's workflow 'hubflow'

vscode-hubflow README This is the README for your extension "vscode-hubflow". After writing up a brief description, we recommend including the followi

Jannik Ramrath 1 Feb 7, 2022
A helper to use immer as Solid.js Signal to drive state

Solid Immer A helper to use immer as Solid.js Signal to drive state. Installation $ npm install solid-immer Usage Use createImmerSignal to create a im

Shuaiqi Wang 67 Nov 22, 2022
A small helper package for discord.js users

helper-djs Helper Djs is a powerful Node.js module Features Error Handler Auto Meme Requirement node v16.14 Installation npm install helper-djs Bot Se

Aadhu 4 Aug 9, 2022