Skip to content

Instantly share code, notes, and snippets.

@iacore
Forked from demotomohiro/testimg.nim
Created June 30, 2022 09:40
Show Gist options
  • Save iacore/716cc62c2a81848735fefe107413794f to your computer and use it in GitHub Desktop.
Save iacore/716cc62c2a81848735fefe107413794f to your computer and use it in GitHub Desktop.
Realtime pixel drawing
import std/[strformat, strutils, bitops]
import pixie, chroma
# define `nort` when opengl or windows system is not available.
when not defined(nort):
import nimgl/[glfw, opengl]
proc `{}`(image: var Image, x, y: int): var ColorRGBX =
## Accessing any pixels outside the bounds of the image is error
when not defined(danger):
if not image.inside(x, y):
raise newException(IndexDefect, &"({x}, {y}) not in range ({image.width - 1}, {image.height - 1})")
image.unsafe[x, y]
proc `{}=`(image: var Image, x, y: int; c: ColorRGBX) =
`{}`(image, x, y) = c
template drawToFile(img: Image; numFrames: int; filename: string; body: untyped): untyped =
for i in 0 .. numFrames:
body
img.writeFile(filename % ["frameNo", intToStr(i, 5)])
# These variable can be changed with '0'~'9' keys on keyboard.
# You can use them to change values in your code quickly with keyboard.
# Push shift key to change tuneKey2
var tuneKey, tuneKey2 = 0
when not defined(nort):
proc keyProc(window: GLFWWindow, key: int32, scancode: int32,
action: int32, mods: int32): void {.cdecl.} =
if key == GLFWKey.ESCAPE and action == GLFWPress:
window.setWindowShouldClose(true)
if action == GLFWPress and key in GLFWKey.K0 .. GLFWKey.K9:
let n = key - GLFWKey.K0
if (mods and GLFWModShift) == 1:
tuneKey2 = n
else:
tuneKey = n
template realtimeDraw(img: Image; body: untyped): untyped =
assert glfwInit()
glfwWindowHint(GLFWResizable, GLFW_FALSE)
let w: GLFWWindow = glfwCreateWindow(img.width.int32, img.height.int32,
"Window Title")
if w == nil:
quit(-1)
discard w.setKeyCallback(keyProc)
w.makeContextCurrent()
assert glInit()
glRasterPos2f(-1.0, 1.0)
glPixelZoom(1.0, -1.0)
echo "Entering main loop"
while not w.windowShouldClose:
glfwPollEvents()
body
glDrawPixels(img.width.GLsizei, img.height.GLsizei,
GL_RGBA, GL_UNSIGNED_BYTE,
img.data[0].addr)
w.swapBuffers()
w.destroyWindow()
glfwTerminate()
#drawToFile(image, 1024, "testout$frameNo.png"):
var image = newImage(512, 512)
image.fill(rgba(255, 255, 255, 255))
let ctx = newContext(image)
ctx.strokeStyle = "#FF5C00"
ctx.lineWidth = 10
let
start = vec2(25, 25)
stop = vec2(175, 175)
ctx.strokeSegment(segment(start, stop))
proc main =
var
frameN = 0
frameN2 = 0
realtimeDraw(image): discard
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment