id
int64 0
45.1k
| file_name
stringlengths 4
68
| file_path
stringlengths 14
193
| content
stringlengths 32
9.62M
| size
int64 32
9.62M
| language
stringclasses 1
value | extension
stringclasses 6
values | total_lines
int64 1
136k
| avg_line_length
float64 3
903k
| max_line_length
int64 3
4.51M
| alphanum_fraction
float64 0
1
| repo_name
stringclasses 779
values | repo_stars
int64 0
882
| repo_forks
int64 0
108
| repo_open_issues
int64 0
90
| repo_license
stringclasses 8
values | repo_extraction_date
stringclasses 146
values | sha
stringlengths 64
64
| __index_level_0__
int64 0
45.1k
| exdup_ids_cmlisp_stkv2
sequencelengths 1
47
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9,003 | core.lisp | kat-co_openapi2cl/tests/core.lisp | (in-package :cl-user)
(defpackage :openapi2cl/tests/core
(:use :cl :rove :openapi2cl/core))
(in-package :openapi2cl/tests/core)
(deftest media-type-p-tests
(testing "should validate `application/json` as valid"
(ok (openapi2cl/core::media-type-p '("application/json"))))
(testing "should validate `text/json` as valid"
(ok (openapi2cl/core::media-type-p '("text/json"))))
(testing "should validate `application/foo+json` as valid"
(ok (openapi2cl/core::media-type-p '("application/foo+json"))))
(testing "should validate `applications/yaml` as valid"
(ok (openapi2cl/core::media-type-p '("application/yaml")))))
| 642 | Common Lisp | .lisp | 13 | 46.076923 | 67 | 0.7136 | kat-co/openapi2cl | 16 | 5 | 4 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 1c5455f31e0cbe8d41475032a0624cb9bfc1edf8ddf3911b1121073426830221 | 9,003 | [
-1
] |
9,004 | openapi2cl.asd | kat-co_openapi2cl/openapi2cl.asd | #-asdf3.1 (error "openapi2cl requires >= ASDF 3.1")
(asdf:defsystem :openapi2cl
:description "A library to generate a common-lisp client from OpenAPI files."
:author "Katherine Cox-Buday <[email protected]>"
:license "GNU GPL v3"
:version "0.0.1"
:class :package-inferred-system
:depends-on ("openapi2cl/core")
:in-order-to ((test-op (test-op "openapi2cl/tests"))))
(asdf:defsystem :openapi2cl/tests
:class :package-inferred-system
:depends-on ("rove"
"openapi2cl/tests/core")
:perform (test-op (op c) (symbol-call :rove '#:run c)))
| 579 | Common Lisp | .asd | 14 | 37.714286 | 79 | 0.699822 | kat-co/openapi2cl | 16 | 5 | 4 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 5ad58924992a1756e6f1c0eecfa1319be4215ad066b58cb2da6509dd3fa1a747 | 9,004 | [
-1
] |
9,008 | Makefile | kat-co_openapi2cl/Makefile | LISP ?= guix environment --pure -lguix.scm -- sbcl --non-interactive
.PHONY: test
test:
$(LISP) --eval "(asdf:test-system :openapi2cl)"
% : %.asd
$(LISP) --eval "(require :cffi)"\
--eval '(pushnew (format nil "~a/lib/" (uiop:getenv "GUIX_ENVIRONMENT")) cffi:*foreign-library-directories*)'\
--eval "(asdf:make :$@)"
| 324 | Common Lisp | .l | 8 | 38.5 | 112 | 0.656051 | kat-co/openapi2cl | 16 | 5 | 4 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 09e052cdd18480a9007154492e3847efbf32910dc5606e1b564c086ed016f784 | 9,008 | [
-1
] |
9,025 | package.lisp | azimut_shiny/package.lisp | (uiop:define-package #:shiny
(:shadowing-import-from #:cm #:between) ;; between is in tmp-func but undef
(:shadowing-import-from #:incudine #:buffer-data #:buffer #:sample)
(:use #:cl
#:cl-ppcre
#:incudine)
(:import-from #:alexandria
#:switch
#:eswitch
#:flatten
#:when-let
#:when-let*
#:iota
#:sequence-of-length-p
#:last-elt
#:first-elt
#:length=
#:extremum
#:ensure-list
#:appendf
#:lastcar)
(:import-from #:cm
#:eop?
#:rhythm
;; modify a list, like a chord
#:invert
#:transpose
#:shuffle
;; lazy evaluation, can be next'd
#:pval
;; random boolean
#:odds
;; random "single element" picker, still you can use lists of lists
#:pick
#:pickl
;; random distribution helper
#:ran
#:drunk ;; brownian noise
#:between
#:ransegs ;; list of ran
#:vary ;; nr around
;; patterns
#:next
#:new
#:weighting
#:markov ;; higher order explicit transition, than nesting patterns
#:cycle
#:palindrome
#:heap)
(:import-from #:incudine.vug
#:maybe-expand
#:define-vug
#:define-ugen
#:make-frame
#:frame-ref
#:delay1
#:cout
#:vuglet
#:current-channel
#:current-frame
#:buffer-play
#:foreach-channel
#:foreach-frame
#:pan2
#:with
#:delay-s
#:envgen
#:vdelay
#:stereo
#:midi-note-on-p
#:midi-note-off-p
#:midi-program-p
;; #:mouse-button
#:with-control-period
#:white-noise
#:samphold
#:pole
#:make-local-adsr
#:make-local-perc
#:phasor
#:make-f32-array
#:phasor-loop
#:bpf
#:lpf
#:hpf
#:buffer-read
#:butter-lp
#:fractal-noise
#:out
#:~
#:rand
#:sine
#:pulse
#:line
#:pink-noise
#:dsp!)
(:import-from #:incudine.util
#:dochannels
#:with-samples
#:f32-ref
#:db->lin
#:+twopi+
#:rt-eval
; #:barrier
#:return-value-p
#:sample->fixnum
#:non-negative-sample
#:lin->db
#:SAMPLE
#:*SAMPLE-DURATION*
#:*SAMPLE-RATE*
#:*twopi-div-sr*
#:+sample-zero+))
(in-package :shiny)
;; cl-collider like
(defun quant (beats)
"returns the time (+ (now) beats), sc-collider like thing"
(+ (now) (* *sample-rate* (* (sample beats) (spb *tempo*)))))
| 3,631 | Common Lisp | .lisp | 118 | 15.271186 | 83 | 0.367806 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | f32786006a8a55912d523c25e45b6cc0ed162df93b5dd0e225e9bc92392b1a02 | 9,025 | [
-1
] |
9,026 | fluid.lisp | azimut_shiny/instruments/fluid.lisp | (in-package :shiny)
;; Incudine
;; OPTIONAL
;;(set-rt-block-size 64)
;; --------------------------------------------------
;; Incudine replaced macro, using bare beat call instead of #[] (less clutter)
(defmacro aat (time function &rest arguments)
(let* ((it (intern "IT"))
(delta (caddr time))
(real (cadr time))
(next `(+ ,real #[,delta b])))
`(let ((,it ,next))
(at ,it ,function ,@arguments))))
;; --------------------------------------------------
| 505 | Common Lisp | .lisp | 14 | 31.714286 | 78 | 0.460744 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 9a513a9c571c19e4f27c4024982bba5902483837ed09943cc0dcb2c891b88bf2 | 9,026 | [
-1
] |
9,027 | drumerino.lisp | azimut_shiny/instruments/drumerino.lisp | (in-package :shiny)
(make-instrument 'drum "/home/sendai/Downloads/sample/OH/")
(push-note 'drum *gm-kick* "kick_OH_F_9.wav")
(push-note 'drum *gm-side-stick* "snareStick_OH_F_9.wav")
(push-note 'drum *gm-snare* "snare_OH_FF_9.wav")
(push-note 'drum *gm-closed-hi-hat* "hihatClosed_OH_F_20.wav")
(push-note 'drum *gm-pedal-hi-hat* "hihatFoot_OH_MP_12.wav")
(push-note 'drum *gm-open-hi-hat* "hihatOpen_OH_FF_6.wav")
(push-note 'drum *gm-low-floor-tom* "loTom_OH_FF_8.wav")
(push-note 'drum *gm-hi-floor-tom* "hiTom_OH_FF_9.wav")
(push-note 'drum *gm-crash* "crash1_OH_FF_6.wav")
(push-note 'drum *gm-ride* "ride1_OH_FF_4.wav")
(push-note 'drum *gm-chinese* "china1_OH_FF_8.wav")
(push-note 'drum *gm-cowbell* "cowbell_FF_9.wav")
(push-note 'drum *gm-open-triangle* "bellchime_F_3.wav")
(push-note 'drum *gm-ride-bell* "ride1Bell_OH_F_6.wav")
| 843 | Common Lisp | .lisp | 16 | 51.625 | 62 | 0.692494 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 0ac03a45f5fff8b821ea507da05269e27564761cdd747b0f12302ca07b554cf3 | 9,027 | [
-1
] |
9,028 | fluid-fast.lisp | azimut_shiny/instruments/fluid-fast.lisp | (in-package :shiny)
;;(pa (now) '(60 62 64) 60 1 1)
(defmacro arpegg (time pitches velocity channel duration lnotes offsets)
`(with-schedule
(loop
:for i :from 1 :upto ,lnotes
:for p :in ,pitches
:for o :in ,offsets :do
(at (+ ,time #[o b]) #'fluidsynth:noteon *synth* ,channel p ,velocity)
(at (+ ,time #[(* i ,duration) b]) #'fluidsynth:noteoff *synth* ,channel p))))
(defmacro chor (time pitches velocity channel duration)
`(loop :for p :in ,pitches :do
(fluidsynth:noteon *synth* ,channel p ,velocity)
(at (+ ,time #[,duration b]) #'fluidsynth:noteoff *synth* ,channel p)))
;;(chor (now) '(60 62 64) 60 1 1)
;; (defgeneric pa (time pitches offset velocity channel duration)
;; (:method (time pitches offset velocity channel duration)
;; (p time (first pitches) velocity duration channel)
;; (loop :for p :in (cdr pitches) :do
;; (p (+ time #[b]) p velocity 1 ))))
(defgeneric pa (time pitches offset velocity channel &key duration)
(:method (time pitches (offset number) (velocity integer) (channel integer)
&key (duration offset))
"Play arpeggio, with a constant offset and velocity"
(let* ((lnotes (length pitches))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(arpegg time pitches velocity channel duration lnotes offsets))))
;;(arpegg (now) '(60 64 66) 60 1 1 3 '(.2 .4 .6))
| 1,433 | Common Lisp | .lisp | 28 | 46.321429 | 86 | 0.645669 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | c79acfb5df64bfe116f0082d37ccaa6d5c4def5237cb2a494624ab5235cab50d | 9,028 | [
-1
] |
9,029 | sample-loop.lisp | azimut_shiny/instruments/sample-loop.lisp | (in-package :shiny)
(defvar *brain*
(buffer-load "/home/sendai/Downloads/177479__unfa__slowly-raining-loop.flac"))
(dsp! bplay ((buf buffer) rate start-pos (loop-p boolean))
(foreach-channel
(cout (incudine.vug:buffer-play buf rate start-pos loop-p #'stop))))
(bplay *brain* 1 0 t :id 3)
(set-control 3 :rate 1)
(set-control 3 :loop-p nil)
| 351 | Common Lisp | .lisp | 9 | 36.777778 | 80 | 0.707965 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | cb756dac09c19c7691ba361be8498ed5369f07c81e97d71aea1db8d1a209b59a | 9,029 | [
-1
] |
9,030 | fluid-standalone.lisp | azimut_shiny/instruments/fluid-standalone.lisp | (in-package :shiny)
;; Use this with https://github.com/zazzerino/cl-fluidsynth
;; This version of cl-fluidsynth adds the standalone audio-driver support
(defvar *settings* (fluidsynth:new-settings
`(("synth.polyphony" 128)
("synth.midi-channels" 32)
("audio.driver" "alsa")
("synth.sample-rate" ,*sample-rate*)
("audio.sample-format" "float"))))
(defvar *synth* (fluidsynth:new-synth *settings*))
(defvar *audio-driver* (fluidsynth:new-audio-driver *settings* *synth*))
;; Incudine like macro, using callback instead (less clutter)
(defmacro aat (time function &rest arguments)
(let ((it (intern "IT")))
`(let ((,it ,time))
(callback ,it ,function ,@arguments))))
;; TODO: complete time list param (use pa instead)
;; use pan
(defgeneric p (time pitch velocity duration channel &key pan)
;; (:method ((time list) (pitch integer) (velocity integer) (duration number) (channel integer) &key pan)
;; (mapcar (lambda (istime) (p istime pitch velocity duration channel))
;; time))
;; (:method ((time list) (pitch list) (velocity integer) (duration number) (channel integer) &key pan)
;; (mapcar (lambda (istime ispitch) (p istime ispitch velocity duration channel))
;; time
;; pitch))
(:method ((time double-float) (pitch list) (velocity integer) (duration number) (channel integer) &key pan)
"Play chord of notes"
(if pan
(mapcar (lambda (x) (p time x velocity duration channel :pan pan))
pitch)
(mapcar (lambda (x) (p time x velocity duration channel))
pitch)))
(:method ((time double-float) (pitch list) (velocity integer) (duration number) (channel list) &key pan)
"Play chord of notes, on provided channels"
(mapcar (lambda (x y) (p time x velocity duration y))
pitch
channel))
(:method ((time double-float) (pitch integer) (velocity integer) (duration number) (channel integer) &key pan)
"Play given pitch"
(when (and (> pitch 0)
(< pitch 127)
(> duration 0))
(when pan
(fluidsynth:cc *synth* channel 10 pan))
(callback time #'fluidsynth:noteon *synth* channel pitch velocity)
(callback (+ time duration) #'fluidsynth:noteoff *synth* channel pitch)))
(:method ((time double-float) (pitch integer) (velocity integer) (duration symbol) (channel integer) &key pan)
"Play given pitch, at CM rythm"
(let ((d (cm:rhythm duration)))
(when (> d 0)
(callback time #'fluidsynth:noteon *synth* channel pitch velocity)
(callback (+ time d) #'fluidsynth:noteoff *synth* channel pitch))))
(:method ((time double-float) (pitch symbol) (velocity integer) (duration symbol) (channel integer) &key pan)
"Play given note on american notation, at CM rhythm"
(unless (eql :_ pitch)
(let ((n (note pitch))
(d (cm:rhythm duration)))
(when (> d 0)
(callback time #'fluidsynth:noteon
*synth* channel n velocity)
(callback (+ time d) #'fluidsynth:noteoff
*synth* channel n)))))
(:method ((time double-float) (pitch symbol) (velocity integer) (duration number) (channel integer) &key pan)
"Play given note on american notation"
(when (and (> duration 0)
(not (eql :_ pitch)))
(let ((n (note pitch)))
(callback time #'fluidsynth:noteon
*synth* channel n velocity)
(callback (+ time duration) #'fluidsynth:noteoff
*synth* channel n)))))
;; --------------------------------------------------
| 3,717 | Common Lisp | .lisp | 73 | 42.890411 | 112 | 0.610179 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 46a3b91b11c1d9e3a5754dcc3be61fa7ee9861b799abeec5361da35467e00a1f | 9,030 | [
-1
] |
9,031 | samples.lisp | azimut_shiny/instruments/samples.lisp | (in-package :shiny)
;; TODO: look at implementations:
;; - overtone/src/overtone/sc/sample.clj
;; - extempore/libs/external/instruments_ext-scm.xtm
;; Currently, this uses phasor-loop as the phase function
;; for buffer-read
(declaim (inline get-lsample))
(defun get-lsample (pitch map)
(aref map (min pitch 127)))
(declaim (inline ct->fv))
(defun ct->fv (steps)
"halfsteps to ratio"
(expt #.(coerce 2.0 'incudine.util:sample)
(* steps #.(coerce 1/12 'incudine.util:sample))))
(defparameter *env1* (make-envelope '(0 1 1 0) '(0 .9 .1)))
(defstruct lsample
"structure for a sample with two loop-points. The structure also
contains a slot for the sample buffer data."
file
buffer
(keynum +sample-zero+ :type incudine.util:sample)
(loopstart +sample-zero+ :type incudine.util:sample)
(loopend +sample-zero+ :type incudine.util:sample))
(defun generate-lsample-map (waves keynums)
"map a list of sample defs of the form (filename keymap-upper-bound
original-keynum loopstart loopend) into a freshly allocated lookup
array containing an lsample-struct entry for 127 keynums. The buffer
slots of the lsamples are filled with the sample data. The array is
returned."
(let* ((tuple (loop
:for w :in waves
:for k :in keynums
:collect (list w k k)))
(stuple (sort tuple (lambda (a b) (< (caddr a) (caddr b)))))
(lsample-map (make-array 128 :adjustable nil
:element-type 'lsample)))
(setf (caddar (last stuple)) 127)
(loop
:for lsample-def :in stuple
:with array-idx = -1
:do (destructuring-bind
(wave-path keynum lastkeynum)
lsample-def
(let ((lsample ;;; make lsample from lsample-def and fill slots
(let ((buf (buffer-load wave-path)))
(make-lsample :file (pathname-name wave-path)
:buffer (buffer-load wave-path)
:keynum (incudine.util:sample keynum)
:loopstart (incudine.util:sample 1)
:loopend (incudine.util:sample
(buffer-size buf))))))
(do () ;;; fill array with references to the lsample
((>= array-idx lastkeynum))
(setf (aref lsample-map (incf array-idx)) lsample)))))
(values lsample-map)))
(defun load-wav-samples (dir &optional keynums)
(declare (type list keynums))
(let ((wav-files (directory (merge-pathnames dir "/*.wav"))))
(unless wav-files
(error "No WAV files"))
(unless keynums
(setf keynums
(mapcar (lambda (x) (note-name-to-midi-number (file-namestring x)))
wav-files)))
(unless (= (length keynums) (length wav-files))
(error "Wrong number of keynums"))
(generate-lsample-map wav-files keynums)))
#|
(defparameter *sam2*
(load-wav-samples "/home/sendai/samples/piano/bosen/"))
|#
;; --------------------
;; Helpers
;; --------------------
(defun set-start (keynum map value)
"sets the loop startime on lsample map with value <=1d0"
(assert (and (typep value 'double-float) (<= value 1d0)
(typep keynum 'integer) (<= keynum 128)))
(with-slots (loopstart loopend) (aref map keynum)
(let ((real-value (* value loopend)))
(setf loopstart real-value))))
(defun get-start (keynum map)
(lsample-loopstart (aref map keynum)))
;; ------------------------
;; Players
;; -----------------------
(define-vug buffer-loop-play ((buffer buffer)
rate
start-pos
loopstart
loopend)
(buffer-read buffer
(phasor-loop rate start-pos loopstart loopend)
:interpolation :cubic))
(dsp! pf (pitch velocity duration)
(with ((lsample (get-lsample (sample->fixnum pitch) *sam2*)))
(with-samples ((rate (ct->fv (- pitch (lsample-keynum lsample))))
(loopstart (lsample-loopstart lsample))
(velocity (/ velocity 128d0))
(loopend (lsample-loopend lsample)))
(with ((buffer (lsample-buffer lsample)))
(stereo (* velocity
(envelope *env1* 1 duration #'incudine:stop)
(buffer-loop-play buffer rate 0 loopstart loopend)))))))
;; --------------------------------------------------
;; NOTE: the idea for now is send the lsample hash as the channel
;; this is not backwards compatible :|
(defgeneric p (time pitch velocity duration channel)
(:method (time (pitch list) velocity duration channel)
"Play chord of notes"
(mapcar (lambda (x) (p time x velocity duration channel))
pitch))
(:method (time (pitch list) velocity duration (channel list))
"Play chord of notes, on provided channels"
(mapcar (lambda (x y) (p time x velocity duration y))
pitch
channel))
(:method (time (pitch integer) velocity (duration number) channel)
"Play given numerical pitch"
(at time #'pf pitch velocity duration))
(:method (time (pitch integer) velocity (duration symbol) channel)
"Play given numerial pitch, at CM rythm"
(let ((d (cm:rhythm duration)))
(at time #'pf pitch velocity d)))
(:method (time (pitch symbol) velocity (duration symbol) channel)
"Play given note, at CM rhythm"
(unless (eql :_ pitch)
(let ((n (note pitch))
(d (cm:rhythm duration)))
(at time #'pf n velocity d))))
(:method (time (pitch symbol) velocity duration channel)
"Play given note"
(unless (eql :_ pitch)
(let ((n (note pitch)))
(at time #'pf n velocity duration)))))
| 5,875 | Common Lisp | .lisp | 135 | 34.814815 | 79 | 0.5884 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 6aeb00c9dc58d8809948f14e0093cd11feb6fd146ca78e72aa7e697985a5cea1 | 9,031 | [
-1
] |
9,032 | collider-foxdot.lisp | azimut_shiny/instruments/collider-foxdot.lisp | (in-package :shiny)
(named-readtables:in-readtable :sc)
;; (filter (b-hipass.ar osc 200))
;; (vib 0)
(defsynth ambi ((amp 1) (sus 1) (pan 0) (freq 1)
(fmod 0) (rate 0) (bus 0))
(let* (;;(freq (+ fmod (in.kr bus 1)))
(freq [freq (+ fmod freq)])
(freq (+ freq (* (x-line.kr (* freq rate) (+ freq (lf-noise2.ar 4 1 sus)))
(sin-osc.ar (+ freq (lf-noise2.ar 4 2)))) ))
(osc (sin-osc.ar (+ freq (rand.ir .99 1.01)) (rand.ir 0 2)))
(env (env-gen.ar (env [0 (* amp .5) (* amp .5) 0]
[(/ sus 4) sus (/ sus 4)])
:act :free))
(osc (* osc env .25))
(osc (pan2.ar osc pan)))
(out.ar bus osc)))
(defparameter *some* (synth 'ambi :freq 230 :sus 2 :amp .3))
(free *some*)
(defsynth soprano ((amp 1) (sus 1) (pan 0) (freq 0)
(vib 0) (fmod 0) (rate 0) (bus 0))
(let* ((freq [freq (+ fmod freq) ])
(sus (* sus 1.75))
(amp (/ amp 2))
(freq (vibrato.kr freq (+ 4 rate)))
(osc (+ (sin-osc.ar (* 3 freq) 0 amp)
(sin-osc-fb.ar (* 3 freq) 0 (/ amp 2))))
(env (env-gen.ar (env [0 amp 0] [ (/ sus 2) (/ sus 2) ]) :act :free))
(osc (* osc env))
(osc (* .5 (mix osc)))
(osc (pan2.ar osc pan)))
(out.ar bus osc)))
(defparameter *some* (synth 'soprano :freq 430 :sus 2 :fmod .1 :amp .5 :rate 0))
(free *some*)
| 1,488 | Common Lisp | .lisp | 34 | 34.411765 | 83 | 0.456055 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 754b8b120aa90863ce65c8759e54852e3bc5f94c1db56c9736f3cc67f239716e | 9,032 | [
-1
] |
9,033 | helpers_all.lisp | azimut_shiny/instruments/helpers_all.lisp | (in-package :shiny)
;;(fluidsynth:sfload *synth* "/usr/share/sounds/sf2/FluidR3_GM.sf2" 1)
;;(fluidsynth:sfload *synth* "/home/sendai/Downloads/Nice-Keys-Suite-V1.0.sf2" 1)
;;(fluidsynth:sfload *synth* "/home/sendai/Downloads/sf2/CTK-230_SoundFont.sf2" 1)
;;(fluidsynth:sfload *synth* "/home/sendai/Downloads/sf2/The_Ultimate Megadrive_Soundfont.sf2" 1)
;;(fluidsynth:sfload *synth* "/home/sendai/Downloads/sf2/999/Imaginary.sf2" 1)
;;(fluidsynth:sfload *synth* "/usr/share/sounds/sf2/FluidR3_GM.sf2" 1)
;;(fluidsynth:sfload *synth* "/home/sendai/samples/Touhou.sf2" 1)
;;(fluidsynth:sfload *synth* "/home/sendai/Touhou.sf2.sf2" 1)
;;(fluidsynth:sfload *synth* "/home/sendai/Downloads/KBH_Real_and_Swell_Choir.sf2" 1)
;;(fluidsynth:sfload *synth* "/home/sendai/Downloads/Majora_s_Mask_N64_Soundfont.sf2" 1)
;;(fluidsynth:sfload *synth* "/home/sendai/Downloads/sf2/Super_Nintendo_Unofficial_update.sf2" 1)
;;(fluidsynth:sfload *synth* "/home/sendai/Downloads/Nice-Keys-Suite-V1.0.sf2" 1)
;;(fluidsynth:delete *synth*)
;; (defgeneric pa (time notes offset velocity channel duration &key pan)
;; (:documentation "Play the given notes as an arpeggio")
;; (:method ((time double-float) (notes number) (offset number) (velocity integer) (channel integer) (duration number) &key pan)
;; (if pan
;; (p time notes velocity offset channel :pan pan)
;; (p time notes velocity offset channel)))
;; (:method ((time double-float) (notes list) (offset number) (velocity integer) (channel integer) (duration number) &key pan)
;; (let* ((lnotes (length notes))
;; (offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
;; (when pan
;; (fluidsynth:cc *synth* channel 10 pan))
;; (mapcar (lambda (n o) (p (+ time o) n velocity duration channel))
;; notes
;; offsets)))
;; (:method ((time double-float) (notes list) (offset number) (velocity integer) (channel list) (duration number) &key pan)
;; (let* ((lnotes (length notes))
;; (offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
;; (mapcar (lambda (n o c) (p (+ time o) n velocity duration c))
;; notes
;; offsets
;; channel)))
;; (:method ((time double-float) (notes list) (offset number) (velocity list) (channel integer) (duration number) &key pan)
;; (let* ((lnotes (length notes))
;; (offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
;; (mapcar (lambda (n o v) (p (+ time o) n v duration channel))
;; notes
;; offsets
;; velocity)))
;; (:method ((time double-float) (notes list) (offset number) (velocity list) (channel list) (duration number) &key pan)
;; (let* ((lnotes (length notes))
;; (offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
;; (mapcar (lambda (n o v c) (p (+ time o) n v duration c))
;; notes
;; offsets
;; velocity
;; channel)))
;; (:method ((time double-float) (notes list) (offset number) (velocity integer) (channel integer) (duration list) &key pan)
;; (let* ((lnotes (length notes))
;; (offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
;; (mapcar (lambda (n o d) (p (+ time o) n velocity d channel))
;; notes
;; offsets
;; duration)))
;; (:method ((time double-float) (notes list) (offset number) (velocity integer) (channel list) (duration list) &key pan)
;; (let* ((lnotes (length notes))
;; (offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
;; (mapcar (lambda (n o c d) (p (+ time o) n velocity d c))
;; notes
;; offsets
;; channel
;; duration)))
;; (:method ((time double-float) (notes list) (offset number) (velocity list) (channel integer) (duration list) &key pan)
;; (let* ((lnotes (length notes))
;; (offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
;; (mapcar (lambda (n o v d) (p (+ time o) n v d channel))
;; notes
;; offsets
;; velocity
;; duration)))
;; (:method ((time double-float) (notes list) (offset number) (velocity list) (channel list) (duration list) &key pan)
;; (let* ((lnotes (length notes))
;; (offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
;; (mapcar (lambda (n o v c d) (p (+ time o) n v d c))
;; notes
;; offsets
;; velocity
;; channel
;; duration)))
;; (:method ((time double-float) (notes list) (offset list) (velocity integer) (channel integer) (duration number) &key pan)
;; (mapcar (lambda (n o) (p (+ time o) n velocity duration channel))
;; notes
;; offset))
;; (:method ((time double-float) (notes list) (offset list) (velocity integer) (channel list) (duration number) &key pan)
;; (mapcar (lambda (n o c) (p (+ time o) n velocity duration c))
;; notes
;; offset
;; channel))
;; (:method ((time double-float) (notes list) (offset list) (velocity list) (channel integer) (duration number) &key pan)
;; (mapcar (lambda (n o v) (p (+ time o) n v duration channel))
;; notes
;; offset
;; velocity))
;; (:method ((time double-float) (notes list) (offset list) (velocity list) (channel list) (duration number) &key pan)
;; (mapcar (lambda (n o v c) (p (+ time o) n v duration c))
;; notes
;; offset
;; velocity
;; channel))
;; (:method ((time double-float) (notes list) (offset list) (velocity integer) (channel integer) (duration list) &key pan)
;; (mapcar (lambda (n o d) (p (+ time o) n velocity d channel))
;; notes
;; offset
;; duration))
;; (:method ((time double-float) (notes list) (offset list) (velocity integer) (channel list) (duration list) &key pan)
;; (mapcar (lambda (n o c d) (p (+ time o) n velocity d c))
;; notes
;; offset
;; channel
;; duration))
;; (:method ((time double-float) (notes list) (offset list) (velocity list) (channel integer) (duration list) &key pan)
;; (mapcar (lambda (n o v d) (p (+ time o) n v d channel))
;; notes
;; offset
;; velocity
;; duration))
;; (:method ((time double-float) (notes list) (offset list) (velocity list) (channel list) (duration list) &key pan)
;; (mapcar (lambda (n o v c d) (p (+ time o) n v d c))
;; notes
;; offset
;; velocity
;; channel
;; duration)))
| 6,884 | Common Lisp | .lisp | 126 | 53.587302 | 130 | 0.578768 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | ab8d214772092db828e386a0677c784794e667e266cbd80d194502df7903f399 | 9,033 | [
-1
] |
9,034 | fluid-slow.lisp | azimut_shiny/instruments/fluid-slow.lisp | (in-package :shiny)
(defgeneric p (time pitch velocity duration channel)
(:method ((time double-float) (pitch list) velocity duration channel)
"Play chord of notes"
(mapcar (lambda (x) (p time x velocity duration channel))
pitch))
(:method ((time double-float) (pitch list) velocity duration (channel list))
"Play chord of notes, on provided channels"
(mapcar (lambda (x y) (p time x velocity duration y))
pitch
channel))
(:method ((time double-float) (pitch integer) (velocity integer) (duration number) (channel integer))
"Play given numerical pitch"
(at time #'fluidsynth:noteon *synth* channel pitch velocity)
(at (+ time #[duration b]) #'fluidsynth:noteoff *synth* channel pitch))
(:method ((time double-float) (pitch integer) (velocity integer) (duration symbol) (channel integer))
"Play given numerial pitch, at CM rythm"
(let ((d (cm:rhythm duration)))
(at time #'fluidsynth:noteon *synth* channel pitch velocity)
(at (+ time #[d b]) #'fluidsynth:noteoff *synth* channel pitch)))
(:method ((time double-float) (pitch symbol) (velocity integer) (duration symbol) (channel integer))
"Play given note, at CM rhythm"
(unless (eql :_ pitch)
(let ((n (note pitch))
(d (cm:rhythm duration)))
(at time #'fluidsynth:noteon
*synth* channel n velocity)
(at (+ time #[d b]) #'fluidsynth:noteoff
*synth* channel n))))
(:method ((time double-float) (pitch symbol) (velocity integer) (duration number) (channel integer))
"Play given note"
(unless (eql :_ pitch)
(let ((n (note pitch)))
(at time #'fluidsynth:noteon
*synth* channel n velocity)
(at (+ time #[duration b]) #'fluidsynth:noteoff
*synth* channel n)))))
(defun pc (time notes velocity duration channel)
(mapcar (lambda (x) (p time x velocity duration channel))
notes))
(defgeneric pa (time notes offset velocity channel &key dur)
(:method ((time double-float) (notes list) (offset number) (velocity integer) (channel integer)
&key (dur offset))
"Play arpeggio, with a constant offset and velocity"
(let* ((lnotes (length notes))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(with-schedule
(mapcar (lambda (x y) (p (+ time #[y b]) x velocity dur channel))
notes
offsets))))
(:method ((time double-float) (notes list) (offset number) (velocity integer) (channel list)
&key (dur offset))
"Play arpeggio, with a constant offset and velocity"
(let* ((lnotes (length notes))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(mapcar (lambda (x y z) (p (+ time #[y b]) x velocity dur z))
notes
offsets
channel)))
(:method ((time double-float) (notes list) (offset number) (velocity list) (channel integer)
&key (dur offset))
"Play arpeggio, with a constant offset and provided velocities"
(let* ((lnotes (length notes))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(mapcar (lambda (x y z) (p (+ time #[y b]) x z dur channel))
notes
offsets
velocity)))
(:method ((time double-float) (notes list) (offset number) (velocity list) (channel list)
&key (dur offset))
"Play arpeggio, with a constant offset and provided velocities"
(let* ((lnotes (length notes))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(mapcar (lambda (x y z a) (p (+ time #[y b]) x z dur a))
notes
offsets
velocity
channel)))
(:method ((time double-float) (notes list) (offset list) (velocity integer) (channel integer)
&key (dur 1))
"Play arpeggio, with provided offsets and constant velocity"
(mapcar (lambda (x y) (p (+ time #[y b]) x velocity dur channel))
notes
offset))
(:method ((time double-float) (notes list) (offset list) (velocity integer) (channel list)
&key (dur 1))
"Play arpeggio, with provided offsets and constant velocity"
(mapcar (lambda (x y z) (p (+ time #[y b]) x velocity dur z))
notes
offset
channel))
(:method ((time double-float) (notes list) (offset list) (velocity list) (channel integer)
&key (dur 1))
"Play arpeggio, with provided offsets and velocities"
(mapcar (lambda (x y z) (p (+ time #[y b]) x z dur channel))
notes
offset
velocity))
(:method ((time double-float) (notes list) (offset list) (velocity list) (channel list)
&key (dur 1))
"Play arpeggio, with provided offsets and velocities"
(mapcar (lambda (x y z a) (p (+ time #[y b]) x z dur a))
notes
offset
velocity
channel)))
(defun play-midi-note (time pitch velocity dur c)
(when (and pitch (> pitch 2))
(at time #'fluidsynth:noteon *synth* c pitch velocity)
(at (+ time #[dur b]) #'fluidsynth:noteoff *synth* c pitch)))
(defun loop-rhythm (time notes rhythms velocity channel
&optional (hownotes 'cdr) (howrhythms 'cdr))
(let ((note (if (eql hownotes 'next) (cm:next notes) (car notes)))
(rhythm (if (eql howrhythms 'next) (cm:next rhythms) (car rhythms))))
(p time note velocity rhythm channel)
(aat (+ time #[rhythm b]) #'loop-rhythm
it
(case hownotes
(cdr (cdr notes))
(rotate (rotate notes 1))
(rrotate (rotate notes -1))
(next notes))
(case howrhythms
(cdr (cdr rhythms))
(rotate (rotate rhythms 1))
(rrotate (rotate rhythms -1))
(next rhythms))
velocity
channel
hownotes howrhythms)))
| 6,005 | Common Lisp | .lisp | 130 | 37.584615 | 103 | 0.600511 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | d53da0f3e8323a86734f0c77253da41a24ad0e8d0aa9789e680fa80ce09d3cd7 | 9,034 | [
-1
] |
9,035 | incudine-dsps.lisp | azimut_shiny/instruments/incudine-dsps.lisp | (in-package :shiny)
;;--------------------------------------------------
;; Sonic-pi
(define-vug ss (freq mfreq amp)
"helper for square function"
(cond
((> freq 0d0) (* amp mfreq .0001))
((< freq 0d0) (- (* amp mfreq .0001)))
(t (* amp freq .0001))))
(dsp! square (freq amp dur atk)
(:defaults 110 .1 1 .25)
(with-samples ((in (sine freq amp))
(in (ss in freq amp))
(in (* in (envelope (make-perc atk dur)
1 dur #'incudine:free))))
(stereo in)))
;;--------------------------------------------------
;; Sonic-pi
;; Missing sc (normalizer in)
(dsp! dsp-pulse (freq amp dur cutoff-freq)
(:defaults 440 .5 1 1000)
(with-samples ((i (pulse freq amp))
(i (lpf i cutoff-freq 1))
(i (* i (envelope (make-perc 0 dur)
1 dur #'incudine:free))))
(stereo i)))
;;--------------------------------------------------
;; Overtone - Prophet
(dsp! prophet (freq amp dur cutoff-freq rq attack decay)
(:defaults 440 .5 1 12000 .3 1 2)
(with-samples
((i (+
(pulse freq 1 (* .1 (+ 1.2 (sine 1 1))))
(pulse freq 1 (* .8 (/ (+ 1.2 (sine .3 1) .7) 2)))
(pulse freq 1 (* .8 (/ (+ 1.2 (1- (mod (sine .4 1) 2))) 2)))
(pulse freq 1 (* .8 (/ (+ 1.2 (1- (mod (sine .4 1 .19) 2))) 2)))
(* .5 (pulse (/ freq 2)
1
(* .8 (/ (+ 1.2 (1- (mod (sine (+ 2 (white-noise .2)))
2)))
2))))))
(i (incudine.vug:lpf (* i i) cutoff-freq rq))
(i (* amp .01 i))
(i (* i (envelope (make-perc 0 dur)
1 dur #'incudine:free))))
(stereo i)))
;;--------------------------------------------------
;; Overtone - All i wanted
(dsp! green (freq dur amp rms)
(:defaults 440 1 1 0)
(with-samples
((in (incudine.vug:sine (+ freq (* 3 (incudine.vug:sine 3)))))
(in (incudine.vug:clip in -.4d0 .4d0))
(in (incudine.vug:lpf in 800d0 1))
(in (* in (envelope (make-adsr .001 .8 .1 1)
(incudine.vug:line 1 0 dur #'incudine:free))))
(in (* in amp)))
(setf rms in)
(out in in)))
(dsp! keen (freq dur amp rms)
(:defaults 440 1 1 0)
(with-samples
((in (incudine.vug:pulse (+ freq (* 3 (incudine.vug:sine 9)))))
(in (incudine.vug:lpf in 800 1))
(in (* in (envelope (make-adsr .08 .2 .1 1)
(incudine.vug:line 1 0 dur #'incudine:free))))
(in (* in amp)))
(setf rms in)
(out in in)))
(dsp! bass (freq amp dur rms)
(:defaults 110 1 4 0)
(with-samples
((decay (min 2d0 (- dur .5d0)))
(in (sine freq))
(in (+ in (* .1 (white-noise))))
(in (lpf in 700 (line 0.3 .1 4 #'free)))
(in (lpf in 1800 1d0))
(in (+ in (sine (* freq))))
;; (in (* in (signum (sine 1))))
(in (* in (envelope (make-perc .01 decay))))
(in (* in amp)))
(setf rms in)
(out in in)))
;;--------------------------------------------------
;; Overtone - ixi.clj
(define-vug pm-osc (carfreq modfreq pmindex)
(sine carfreq (sine modfreq 0 pmindex)))
;; FIXME!
(dsp! ixi-kick (mod-freq
mod-index
sustain
beater-noise-level
pan
amp)
(:defaults 2.6 5 .4 .025 0 .3)
(with-samples ((freq 80)
(pitch-contour (line (* freq 2) freq .02 #'identity))
(drum-osc (pm-osc pitch-contour mod-freq (/ mod-index 1.3)))
(drum-lpf (lpf drum-osc 1000 1))
(drum-env (* drum-lpf
(envelope (make-perc .005 sustain)
:done-action #'incudine:free)))
(beater-source (* (white-noise) beater-noise-level))
(beater-hpf (hpf beater-source 500 1))
(lpf-cutoff-contour (line 6000 500 .03 #'identity))
(beater-lpf (lpf beater-hpf lpf-cutoff-contour 1))
(beater-env (* beater-lpf
(envelope (make-perc .000001 1)
:done-action #'incudine:free)))
(kick-mix (* (+ drum-env beater-env) 2 amp)))
(stereo kick-mix)))
(define-vug dsp-saw (freq)
(sine freq))
;; https://github.com/supercollider/supercollider/blob/master/SCClassLibrary/Common/Audio/Noise.sc
(define-vug lf-noise0 ()
(white-noise))
(dsp! ixi-snare (drum-mode-level
snare-level
snare-tightness
sustain
amp)
(:defaults 1 50 1200 .04 .3)
(with-samples
((freq 305)
(drum-mode-env (envelope (make-perc .005 sustain)
:done-action #'incudine:free))
(drum-mode-sin-1 (* (sine (* freq .53)) drum-mode-env .5))
(drum-mode-sin-2 (* (sine freq) drum-mode-env .5))
(drum-mode-pmosc (* 5 drum-mode-env (pm-osc (dsp-saw (* freq .085))
184
(/ .5 1.3))))
(drum-mode-mix (* drum-mode-level (+ drum-mode-sin-1
drum-mode-sin-2
drum-mode-pmosc)))
(snare-noise (* amp .8 (lf-noise0)))
(snare-env (envelope (make-perc .0001 sustain)
:done-action #'incudine:free))
(snare-brf-1 (* .5 (incudine.vug:bpf snare-noise 8000 .1)))
(snare-brf-2 (* .5 (incudine.vug:bpf snare-brf-1 5000 .1)))
(snare-brf-3 (* .5 (incudine.vug:bpf snare-brf-2 3600 .1)))
(snare-brf-4 (* snare-env (incudine.vug:bpf snare-brf-3 2000 .1)))
(snare-reson (* snare-level (incudine.vug:resonz snare-brf-4 snare-tightness 1)))
(snare-drum-mix (* amp (+ drum-mode-mix snare-reson))))
(stereo snare-drum-mix)))
| 6,027 | Common Lisp | .lisp | 144 | 30.659722 | 98 | 0.463452 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | fbfe8636f70a15c9c6f7d67eeb08ccb019962054e00ee9567e5fac78b42d85bb | 9,035 | [
-1
] |
9,036 | jackmidi.lisp | azimut_shiny/instruments/jackmidi.lisp | (in-package :shiny)
(defvar *midiout* (jackmidi:open :direction :output))
;; Connect with Carla/qjackctl
;; TODO: I only have 1 "channel", so might be i need to send the *midiout* as a var in place of the channel
;; Although...that will make the code not work with other compositions...
;; ... unless I have some mapping (?
;; http://computermusicresource.com/MIDI.Commands.html
(defun to-channel (code)
(+ code 143))
(defun off-with-the-notes ()
(loop :for c :in (range 20)
:do (mapcar (lambda (x) (jackmidi:write-short *midiout* (jackmidi:message (+ c 143) x 0) 3))
(range 120))))
(defun play-midi-note (time pitch velocity dur &optional (c 1))
(at time #'jackmidi:write-short *midiout*
(jackmidi:message c pitch velocity) 3)
(at (+ time #[dur b]) #'jackmidi:write-short *midiout*
(jackmidi:message c pitch 0) 3))
(defun play-midi-note-loop (time pitch velocity dur &optional (c 1))
(at time #'jackmidi:write-short *midiout*
(jackmidi:message c pitch velocity) 3)
(at (+ time #[dur b]) #'jackmidi:write-short *midiout*
(jackmidi:message c pitch 0) 3))
(defgeneric p (time pitch velocity duration channel)
(:method (time (pitch integer) velocity (duration number) channel)
(at time #'jackmidi:write-short *midiout*
(jackmidi:message 144 pitch velocity) 3)
(at (+ time #[duration b]) #'jackmidi:write-short *midiout*
(jackmidi:message 128 pitch 0) 3))
(:method (time (pitch integer) velocity (duration symbol) channel)
(let ((d (cm:rhythm duration)))
(at time #'jackmidi:write-short *midiout*
(jackmidi:message 144 pitch velocity) 3)
(at (+ time #[d b]) #'jackmidi:write-short *midiout*
(jackmidi:message 128 pitch 0) 3)))
(:method (time (pitch symbol) velocity (duration symbol) channel)
(unless (eql :_ pitch)
(let ((n (note pitch))
(d (cm:rhythm duration)))
(at time #'jackmidi:write-short *midiout*
(jackmidi:message 144 n velocity) 3)
(at (+ time #[d b]) #'jackmidi:write-short *midiout*
(jackmidi:message 128 n 0) 3))))
(:method (time (pitch symbol) velocity duration channel)
(unless (eql :_ pitch)
(let ((n (note pitch)))
(at time #'jackmidi:write-short *midiout*
(jackmidi:message 144 n velocity) 3)
(at (+ time #[duration b]) #'jackmidi:write-short *midiout*
(jackmidi:message 128 n 0) 3)))))
(defun pc (time notes velocity duration channel)
(mapcar (lambda (x) (p time x velocity duration channel))
notes))
(defgeneric pa (time notes offset velocity &key channel dur)
(:method (time notes (offset number) (velocity integer)
&key (channel 1) (dur offset))
"Play arpeggio, with a constant offset and velocity"
(let* ((lnotes (length notes))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(mapcar (lambda (x y) (p (+ time #[y b]) x velocity dur channel))
notes
offsets)))
(:method (time notes (offset number) (velocity list)
&key (channel 1) (dur offset))
"Play arpeggio, with a constant offset and provided velocities"
(let* ((lnotes (length notes))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(mapcar (lambda (x y z) (p (+ time #[y b]) x z dur channel))
notes
offsets
velocity)))
(:method (time notes (offset list) (velocity integer) &key (channel 1) (dur 1))
"Play arpeggio, with provided offsets and constant velocity"
(mapcar (lambda (x y) (p (+ time #[y b]) x velocity dur channel))
notes
offset))
(:method (time notes (offset list) (velocity list) &key (channel 1) (dur 1))
"Play arpeggio, with provided offsets and velocities"
(mapcar (lambda (x y z) (p (+ time #[y b]) x z dur channel))
notes
offset
velocity)))
(defun loop-rhythm (time notes rhythms
&optional (hownotes 'cdr) (howrhythms 'cdr))
(let ((note (if (eql hownotes 'next) (cm:next notes) (car notes)))
(rhythm (if (eql howrhythms 'next) (cm:next rhythms) (car rhythms))))
(p time note 60 rhythm 1)
(aat (+ time #[rhythm b]) #'loop-rhythm
it
(case hownotes
(cdr (cdr notes))
(rotate (rotate notes 1))
(rrotate (rotate notes -1))
(next notes))
(case howrhythms
(cdr (cdr rhythms))
(rotate (rotate rhythms 1))
(rrotate (rotate rhythms -1))
(next rhythms))
hownotes howrhythms)))
| 4,689 | Common Lisp | .lisp | 100 | 39.25 | 107 | 0.614897 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 4cc637deddc60f3cac410a9bdb44681712fc84813ec961f663454a4335f33a7e | 9,036 | [
-1
] |
9,037 | alsaseq.lisp | azimut_shiny/instruments/alsaseq.lisp | (in-package :shiny)
;; (ql:quickload :cl-alsaseq)
;; (midihelper:start-midihelper)
;; (midihelper:send-event (midihelper:ev-pgmchange 1 5))
;; (midihelper:send-event (midihelper:ev-pgmchange 1 52))
;; (midihelper:send-event (midihelper:ev-pgmchange 2 101))
;; (midihelper:send-event (midihelper:ev-cc 0 10 100))
(defgeneric play-midi (time note velocity duration channel))
(defmethod play-midi (time note velocity duration channel))
(defmethod play-midi ((time double-float)
(note fixnum)
(velocity fixnum)
(duration number)
(channel fixnum))
"play note"
(when (> note 0)
(at time #'midihelper:send-event (midihelper:ev-noteon channel note velocity))
(at (+ time (* *sample-rate* (* (sample duration) (spb *tempo*))))
#'midihelper:send-event
(midihelper:ev-noteoff channel note velocity))))
(defmethod play-midi ((time double-float)
(note list)
(velocity fixnum)
(duration number)
(channel fixnum))
"play chord"
(mapcar (lambda (n) (play-midi time n velocity duration channel))
note))
(defmethod play-midi ((time double-float)
(note list)
(velocity fixnum)
(duration list)
(channel fixnum))
"chord, with different durations"
(mapcar (lambda (n d) (play-midi time n velocity d channel))
note
duration))
;;--------------------------------------------------
(defgeneric play-midi-arp (time note velocity duration channel offset))
(defmethod play-midi-arp (time note velocity duration channel offset))
(defmethod play-midi-arp ((time double-float)
(note fixnum)
(velocity fixnum)
(duration number)
(channel fixnum)
(offset number))
"fallback, takes a single note"
(play-midi time note velocity duration channel))
(defmethod play-midi-arp ((time double-float)
(note list)
(velocity fixnum)
(duration number)
(channel fixnum)
(offset number))
"play arpeggio, at uniform times"
(let* ((lnotes (length note))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(mapcar
(lambda (n o) (play-midi (+ time (* *sample-rate* (* (sample o) (spb *tempo*))))
n velocity duration channel))
note
offsets)))
(defmethod play-midi-arp ((time double-float)
(note list)
(velocity fixnum)
(duration list)
(channel fixnum)
(offset list))
"play arpeggio, with provided durations and offsets"
(mapcar
(lambda (n d o) (play-midi (+ time (* *sample-rate* (* (sample o) (spb *tempo*))))
n velocity d channel))
note
duration
offset))
| 3,183 | Common Lisp | .lisp | 75 | 30 | 85 | 0.534666 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 820fbb40dc272ed79a2db6c9e1f17e0cc9fe99d3539925bb053196f4c9d8dac5 | 9,037 | [
-1
] |
9,038 | cryptogram.lisp | azimut_shiny/lib/cryptogram.lisp | (in-package :shiny)
;; http://ericsams.org/index.php/on-music/essays/on-schumann/97-did-schumann-use-cyphers-aug-1965
(defparameter *schumann*
'((d . 0) (i . 0) (q . 0)
(h . 1) (j . 1) (r . 1)
(a . 2) (k . 2) (s . 2)
(b . 3) (l . 3) (t . 3)
(c . 4) (m . 4) (u . 4)
(e . 5) (n . 5) (v . 5)
(f . 6) (o . 6) (w . 6)
(g . 7) (p . 7) (x . 7)))
;; FIXME!!!
(defun crypt-melody (l)
"seemless show the melody meaning"
(declare (list l))
(values
(coerce
(loop :for e :in l :collect
(coerce (cm:note-name e) 'character))
'string)
l))
(defun decrypt-melody (s &optional (dictionary *schumann*))
"returns offsets from a string for a schumann alist"
(declare (string s))
(labels ((f (x y)
(equalp (string x) (symbol-name y))))
(let ((slist (coerce s 'list)))
(loop :for c :in slist :collect
(cdr (assoc c dictionary
:test #'f))))))
| 940 | Common Lisp | .lisp | 30 | 26.3 | 97 | 0.532597 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 6e187911d25a34843437c01b690cafdf19f7c211351529183ece05751cbd1a3e | 9,038 | [
-1
] |
9,039 | csound-live-code.lisp | azimut_shiny/lib/csound-live-code.lisp | (in-package #:shiny)
;; TODO: keep the force 16beat padding (?
;; TODO: function to check if we are in beat N of the hexbeat
;;
;; Ideas took from:
;; https://github.com/kunstmusik/csound-live-code/
;; http://lisptips.com/post/44509805155/formatting-integers-in-different-radixes
;; choose ~ cm:odds
;; cycle - cm:cycle
;; contains - cl-user:position
;; remove - cl-user:remove
;; rand - cm:pickl
;; caose - > velocity 0
(defvar *hexpitch-cache* (make-hash-table :test #'equal))
(defun :bits (number &optional (size 16))
"(:bits 42) => 00101010"
(format NIL "~v,'0B" size number))
(defun %hexbeat (hex)
"takes a string with possible spaces or a single char, returns a binary string
(%hexbeat \"A\") => \"1010\"
(%hexbeat #\\a) => \"1010\""
(declare (type (or character string) hex))
(let* ((hex-string (if (characterp hex) (string hex) hex))
(hex-string (cl-ppcre:regex-replace-all " " hex-string ""))
(decimal (parse-integer hex-string :radix 16))
(bin-length (* 4 (length hex-string)))
(bin-string (:bits decimal bin-length)))
bin-string))
(defun hexpat (s)
"returns a cycle of a list of T or NIL, of hex pattern S, with variable nr of beats"
(declare (type string s))
(make-cycle (parse1 (%hexbeat s))))
(defun choose (prob)
(declare (type (single-float 0f0 1f0) prob))
(if (< (random 1f0) prob) 1 0))
;; aka "p4"
(defun beat ()
"returns the current beat, double precision"
(declare (type double-float *sample-rate*))
(/ (now) (* *sample-rate* (spb *tempo*))))
(defun rbeat ()
"returns the current beat, floor to integer"
(floor (beat)))
(defun 16beat ()
(mod (floor (beat))
16))
(defun nth-beat (beat l)
"something kind of:
xosc(phsb(1.7), array(1,2,3,4))
It changes cycles overtime, producing some kind stutter. Might be math wrong..."
(declare (type list l))
(nth (floor (* (length l)
(/ (mod (beat) (* beat 4 4))
(* beat 4 4))))
l))
;;--------------------------------------------------
;; Helpers for the grammar
(defun safe-length (e)
(if (numberp e)
1
(length e)))
;; AKA numpy roll"ish"
(defun roll (array n)
(declare (type fixnum n))
(let ((indices (cl-arrows:-> (length array)
(iota)
(rotate n))))
(loop :for i :in indices
:collect (aref array i))))
(defun add (&rest rest)
"helper over numcl:+ to allow padding of not equal arrays.
> (add (bit-smasher:hex->bits \"ff\")
(bit-smasher:hex->bits \"a\"))
#(1 1 1 1 2 1 2 1)"
(let* ((max-length (reduce #'max (mapcar #'safe-length rest)))
(same-length-rest
(mapcar (lambda (r) (if (and (not (numberp r))
(not (= max-length (length r))))
(serapeum:pad-start r max-length 0)
r))
rest)))
(apply #'numcl:+ same-length-rest)))
(defun minus (&rest rest)
"helper over numcl:- to allow padding of not equal arrays.
> (minus (bit-smasher:hex->bits \"ff\")
(bit-smasher:hex->bits \"a\"))
#(1 1 1 1 0 1 0 1)"
(let* ((max-length (reduce #'max (mapcar #'safe-length rest)))
(same-length-rest
(mapcar (lambda (r) (if (and (not (numberp r))
(not (= max-length (length r))))
(serapeum:pad-start r max-length 0)
r))
rest)))
(apply #'numcl:- same-length-rest)))
;;--------------------------------------------------
;; Grammar definition
;; TODO: (), & , | , ^, ... -, /
(cl-lex:define-string-lexer hexpitch-lexer
("x[A-Fa-f0-9]+" (return (values :hex (bit-smasher:hex->bits
(subseq $@ 1)))))
("[0-9]+" (return (values :dec (parse-integer $@))))
("-" (return (values :minus :minus)))
("\\(" (return (values :left-paren :left-paren)))
("\\)" (return (values :right-paren :right-paren)))
("~" (return (values :concat :concat))) ;; D like concat...
;; ("&" (return (values :and :and)))
;; ("|" (return (values :or :or)))
("%" (return (values :mod :mod)))
(">>" (return (values :rshift :rshift)))
("<<" (return (values :lshift :lshift)))
("\\+" (return (values :add :add)))
("\\*" (return (values :mul :mul))))
(defun hexpitch-lex-line (string)
"REPL helper to test lexer"
(loop :with lexer := (hexpitch-lexer string)
:for tok := (funcall lexer)
:while tok
:collect tok))
;; 82 * 5 + f34234234 * 3 + 2
;; https://en.cppreference.com/w/c/language/operator_precedence
(yacc:define-parser hexpitch-parser
(:start-symbol expression)
(:terminals (:add :mul :hex :dec :rshift :lshift :concat
:mod :left-paren :right-paren :minus))
(:precedence ((:left :mul) (:left :mod)
(:left :add) (:left :minus)
(:left :rshift) (:left :lshift)
(:left :concat)))
(expression
(expression :add expression (lambda (x _ z) (declare (ignore _)) `(add ,x ,z)))
(expression :minus expression (lambda (x _ z) (declare (ignore _)) `(minus ,x ,z)))
(expression :mul expression (lambda (x _ z) (declare (ignore _)) `(numcl:* ,x ,z)))
(expression :mod expression (lambda (x _ z) (declare (ignore _)) `(numcl:mod ,x ,z)))
(expression :rshift expression (lambda (x _ z) (declare (ignore _)) `(roll ,x (- ,z))))
(expression :lshift expression (lambda (x _ z) (declare (ignore _)) `(roll ,x ,z)))
(expression :concat expression (lambda (x _ z) (declare (ignore _)) `(concatenate 'vector ,x ,z)))
term)
(parenthosis (:left-paren expression :right-paren
(lambda (x y z) (declare (ignore x z)) y)))
(term :dec
:hex
parenthosis))
;;--------------------------------------------------
;; Grammar usage
(defun hexpitch (s)
(let* ((to-eval (yacc:parse-with-lexer (hexpitch-lexer s) hexpitch-parser))
(earray (eval to-eval)))
(values (make-cycle (coerce earray 'list))
earray
to-eval)))
;; FIXME: when the same pattern is used it returns the same cycle...u can add a space in the end to workarount it
(defun hexpitchc (s)
(declare (type string s))
(or (gethash s *hexpitch-cache*)
(setf (gethash s *hexpitch-cache*) (hexpitch s))))
;; FIXME: they get generated at different time (unaligned)...u can clrhash it
(defmacro hexplay (beat &body body)
`(when (not (zerop (next (hexpitchc ,beat))))
,@body))
| 6,741 | Common Lisp | .lisp | 160 | 35.66875 | 113 | 0.551304 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 25a594b07fc1e79d8b8c96de22987bc914ec7fecb998dc22a30851d5db912203 | 9,039 | [
-1
] |
9,040 | cm.lisp | azimut_shiny/lib/cm.lisp | (in-package :shiny)
;;--------------------------------------------------
;; CM helpers
;;--------------------------------------------------
;;
;; Reference:
;; https://ccrma.stanford.edu/courses/220b-winter-2006/cm/doc/dict/patterns-topic.html
;;
;; TODO:
;; (make-markov)
;; (make-thunk)
;; (make-rewrite)
;; (make-transposer)
;; (make-chord)
;; (make-join)
;; (make-copier)
(defun make-cycle (elements &optional (for-elements 1 for-elements-p))
"loops over elements in a continuous cycle"
(when elements ;; do not make a cycle of ONLY nil (?
(if for-elements-p
(cm:new cm:cycle :of elements :for for-elements)
(cm:new cm:cycle :of elements))))
(defun make-coin ()
"returns a cycle that iterates between NIL and T"
(make-cycle '(NIL T)))
(defun make-heap (elements &optional (for-elements 1 for-elements-p))
(if for-elements-p
(cm:new cm:heap :of elements :for for-elements)
(cm:new cm:heap :of elements)))
(defun make-line (elements)
"loops over elements in a continuous cycle"
(cm:new cm:line :of elements))
(defun make-rotation (elements &optional (rotations '(0 1 1)) (for-elements 1 for-elements-p))
"A constantly rotating pattern.
> (next (make-rotation '(1 2 3 4)) 30)
(1 2 3 4 2 3 4 1 3 4 1 2 4 1 2 3 1 2 3 4 2 3 4 1 3 4 1 2 4 1)"
(declare (type list rotations))
(if for-elements-p
(cm:new cm:rotation :of elements
:rotations rotations
:for for-elements)
(cm:new cm:rotation :of elements
:rotations rotations)))
(defun make-accumulation (elements &optional (for-elements 1 for-elements-p))
"For each item, generates all items up to and including the current item.
The process starts over when all the items have been accumulated.
> (cm:next (cm:new cm:accumulation :of '(1 2 3 4)) 10)
(1 1 2 1 2 3 1 2 3 4)"
(if for-elements-p
(cm:new cm:accumulation :of elements :for for-elements)
(cm:new cm:accumulation :of elements)))
(defun make-weighting (elements &optional (for-elements 1 for-elements-p))
;; try to add :weight keyword if only provided 2 elements
;; we push since order doesn't really matter...
(let ((sane-elements '()))
(loop
:for e :in elements :do
(cond ((and (listp e) (length= 3 e))
(push e sane-elements))
((not (listp e))
(push e sane-elements))
((and (listp e) (length= 2 e))
(push (list (first-elt e) :weight (last-elt e))
sane-elements))))
(if for-elements-p
(cm:new cm:weighting :of sane-elements :for for-elements)
(cm:new cm:weighting :of sane-elements))))
;; FIXME!!
(defun make-stutter (elements &optional (for 1))
(cm:new cm:cycle
:of elements
:for (cm:new cm:cycle :of for)))
(defun make-palindrome (elements)
"generates elements forwards and backwards"
(cm:new cm:palindrome :of elements :elide t))
(defun make-range (from to &optional (by 1))
"iterates numbers in a range"
(cm:new cm:range :from from :to to :by by))
;; took from jazz.cm
(defun rancyc (data prob)
(list (make-cycle data) :weight prob))
(defun markov-find-shortest (markov)
(declare (markov markov))
(let ((long-cycle (next markov 30)))
(loop
:for cycle :in long-cycle
:with queue
:while (not (position cycle queue))
:finally (return queue)
:do (push cycle queue))))
(defun make-graph (elements &optional (for 1 for-p))
"The Graph pattern. A graph is a network of nodes, each node contains
a 'value' (the item to return from the pattern), a 'link' to the
node that should come next , and an identifier (a unique name for
the node in the graph). Both the value and the link can be
subpatterns . node identifiers default to increasing numbers from 1.
Example:
> (make-graph '((A 2) (B 3) (C 1))))"
(let ((pat (loop
:for id :from 1
:for (elt to-id) :in elements
:collect (list elt :id id :to to-id))))
(if for-p
(cm:new cm:graph :of pat :for for)
(cm:new cm:graph :of pat))))
;;------------------------------------------------------------
;; TODO: sub-cycles, like (make-var '(4 2) '(1 2 (2 (3 4))))
;; Version that takes 2 lists
(defun make-var (elements &optional (for NIL for-p))
"Returns a LIST of cycles and/or symbols.
FOR NIL is usefult to play plain lists of cycles
FOR =1 is useful for
FOR >1 is useful to stutter ELEMENTS."
(declare (type list elements))
(if for-p
(loop
:for element :in elements
:for f :in (repeat (length elements)
(ensure-list for))
:collect
(if (and (= f 1) (or (null element) (not (listp element))))
element
(cm:new cm:cycle :of element :for f)))
(loop
:for element :in elements
:collect
(if (or (null element) (not (listp element)))
element
(cm:new cm:cycle :of element)))))
(defun make-war (elements &optional (for NIL for-p))
(declare (type list elements))
(if for-p
(loop
:for element :in elements
:for f :in (repeat (length elements)
(ensure-list for))
:collect
(if (and (= f 1) (or (null element) (not (listp element))))
element
(cm:new cm:weighting :of element :for f)))
(loop
:for element :in elements
:collect
(if (or (null element) (not (listp element)))
element
(cm:new cm:weighting :of element)))))
(defun make-har (elements &optional (for NIL for-p))
(declare (type list elements))
(if for-p
(loop
:for element :in elements
:for f :in (repeat (length elements)
(ensure-list for))
:collect
(if (and (= f 1) (or (null element) (not (listp element))))
element
(cm:new cm:heap :of element :for f)))
(loop
:for element :in elements
:collect
(if (or (null element) (not (listp element)))
element
(cm:new cm:heap :of element)))))
;; Version that takes 1+N arguments
(defgeneric make-cycles (for &rest rest)
(:documentation "returns a list of cycles or symbols using FOR as the :for param
tries to avoid creating cycles when FOR=1
kind of useful to mimic stutter OR creating alternating patterns
a'la () in FoxDot")
(:method ((for fixnum) &rest rest)
(if (= 1 for)
(mapcar (lambda (x) (if (listp x)
(cm:new cm:cycle :of x :for for)
x))
rest)
(mapcar (lambda (x) (cm:new cm:cycle :of (ensure-list x) :for for))
rest)))
(:method ((for list) &rest rest)
(loop
:for f :in for
:for r :in rest :collect
(if (= 1 f)
r
(cm:new cm:cycle
:of (ensure-list r)
:for f)))))
;;--------------------------------------------------
;; From SC
(defun make-shuf (elements &optional (for NIL for-p))
"kind of Pshuf, shuffle the list in random order, and use
the same random order FOR times"
(if for-p
(cm:new cm:copier
:of (cm:new cm:heap :of elements)
:for for)
(cm:new cm:copier
:of (cm:new cm:heap :of elements))))
;;--------------------------------------------------
;; From nudruz/rhythm.lisp
(defun upbeatcyc (minups maxups mindown maxdown)
"UPBEATCYC -- returns upbeat cycle
between 'minups' and 'maxups' upbeats of 1
between 'mindown' and 'maxdown' length of downbeat
> (next (upbeatcyc 2 5 10 20) 20)"
(cm:new cm:weighting
:of `((1 :min ,minups :max ,maxups)
(,(pval (between mindown maxdown)) :max 1))))
(defun cyc-rhythms (mlens subdivs)
"CYC-RHYTHMS -- combines measures and subdivisions cyclically
> (cyc-rhythms '(2 3 1.5) '(1 2))
(2.0 1.5 1.5 1.5 1.0 1.0 3.0 0.75 0.75)"
(let* ((subdivcyc (new cycle of subdivs))
(mlencyc (new cycle of mlens)))
(loop :until (and (eop? subdivcyc)
(eop? mlencyc))
:for this-subdiv = (next subdivcyc)
:for this-mlen = (next mlencyc)
:append (loop :repeat this-subdiv
:collect (float (/ this-mlen this-subdiv))))))
(defun combine-atks (rhythms atklist)
"COMBINE-ATKS -- 'fuses' attacks within a rhythm
'combiner' = number of attacks to combine (cycle)
> (combine-atks '(1 2) '(1 1 3))
(1 2 4 2 1 5)"
(let ((rcyc (cm:new cm:cycle :of rhythms))
(atkcyc (cm:new cm:cycle :of atklist)))
(loop :until (and (eop? rcyc)
(eop? atkcyc))
:collect (apply #'+ (next rcyc (next atkcyc))))))
| 8,784 | Common Lisp | .lisp | 229 | 31.49345 | 94 | 0.584174 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | e6c8bebb4ead70372d4128110e131fe7bb954f24e2359f57909a05ef261ec5c6 | 9,040 | [
-1
] |
9,041 | espeak-ng.lisp | azimut_shiny/lib/espeak-ng.lisp | (in-package #:espeak-ng)
(defvar *espeak-buffers* (make-hash-table :test #'equal))
(defun chunk-to-buffer (pointer length)
"Returns a new buffer filled with the content on pointer
with size LENGTH"
(declare (type cffi:foreign-pointer pointer)
(type fixnum length))
(let ((buf (incudine:make-buffer length :sample-rate 22050)))
(incudine.external:foreign-copy-samples
(incudine:buffer-data buf)
pointer
length)
buf))
(defun get-syl (syl-counter syls-length)
"Helper that returns the syllabic state for ecantorix,
based on the sentence length on SYLS-LENGTH and the
current SYL-COUNTER."
(declare (type fixnum syl-counter syls-length))
(cond ((= syls-length 1) 0)
((and (= syls-length 2) (= syl-counter 0)) 1)
((and (= syls-length 2) (= syl-counter 1)) 3)
((and (> syls-length 2) (= syl-counter 0)) 1)
((and (> syls-length 2)
(< syl-counter (1- syls-length))) 2)
(t 3)))
(defun espeak-phonemes (text)
"Returns a list with the phonemes of the given TEXT.
Should be run inside a initialized espeak
state block."
(declare (type string text))
(cffi:with-foreign-string (s text)
(cffi:with-foreign-object (p :pointer)
(setf (cffi:mem-aref p :pointer) s)
(let* ((phonemes (espeak_texttophonemes
p
ESPEAKCHARS_AUTO
0))
(phonemes-list phonemes))
phonemes-list))))
;; libespeak-ng PATCHES:
;; - Samples are doubles instead of singles
;; - Synthezise accepts phonemes
;; - Init and Term
;; (defun sinsytest (speech &optional (language "es") (speed 960))
;; "Returns a new buffer with the SPEECH rendered into it."
;; (declare (type string language))
;; (with-espeak (:AUDIO_OUTPUT_SYNCHRONOUS 0 (cffi:null-pointer) 0)
;; (with-sinsy
;; (espeak_setsynthcallback (cffi:callback ctest))
;; (cffi:with-foreign-object (l :int)
;; (espeak_setvoicebyname language)
;; (dolist (sentence (cl-ppcre:split :whitespace-char-class speech))
;; (sinsy_ng_addrest (round (* .1 speed)))
;; (let* ((syls (if (> (length sentence) 3)
;; (espeak-phonemes sentence)
;; (list sentence)))
;; (syls-length (length syls))
;; (syl-counter 0)
;; (syl-type 0)
;; (breath 0))
;; (dolist (syl syls)
;; (incf breath (length syls))
;; (setf syl-type (get-syl syl-counter syls-length))
;; (format t "~%~a~C~a~C~a"
;; syl-type #\tab
;; sentence #\tab
;; syl)
;; (sinsy_ng_addnote
;; (round
;; (* speed (cm:interp (length syl)
;; 0f0 .15 3 1f0)))
;; (if (> (length sentence) 3)
;; (format NIL "[[~a]]" syl)
;; syl)
;; (cm:pickl (shiny::ov-scale :C3 :minor))
;; NIL NIL 1 syl-type (if (> breath 8)
;; (progn (setf breath 0) T)
;; NIL))
;; (incf syl-counter))))
;; (chunk-to-buffer (sinsy_ng_getaudiodata l)
;; (cffi:mem-ref l :int))))))
(defun mixed-parser (s &optional (split-by ",|'|[ ]"))
"takes a string separated by spaces and further down by hyphens
to denote syllabic separation"
(loop :for word :in (cl-ppcre:split :whitespace-char-class s)
:append (cond ((position #\- word :test #'equal) ;; Split by dashes?
(cl-ppcre:split "-" word))
;; Is supposed to be parsed TO phonemes
((string= "<" (subseq word 0 1))
(let* ((word (cl-ppcre:regex-replace-all "<|>" word ""))
(split-char (subseq word 0 1))
(split-p (not (cl-ppcre:scan "[a-zA-Z]" split-char))))
(when split-p
(setf split-by split-char)
(setf word (subseq word 1)))
(text-to-phonemes word "en" T split-by)))
(t (list word)))))
(defvar *tmp* nil)
(defun sinsytest (phonemes notes durations breaths &optional stypes (language "en") (speed 960))
"Returns a new buffer with the SPEECH rendered into it."
(declare (type string language))
(when *tmp* (incudine:free *tmp*))
(with-espeak (:AUDIO_OUTPUT_SYNCHRONOUS 0 (cffi:null-pointer) 0)
(with-sinsy ()
(espeak_setsynthcallback (cffi:callback ctest))
(cffi:with-foreign-object (l :int)
(espeak_setvoicebyname language)
(let* ((syls phonemes)
(csyls (shiny::make-cycle syls))
(syls-length (if (string= "[" (subseq (first syls) 0 1))
(length syls)
1))
(cdurations (shiny::make-cycle durations))
(cnotes (shiny::make-cycle notes))
(cbreaths (shiny::make-cycle breaths))
(cstypes (if stypes (shiny::make-cycle stypes)))
(syl-counter 0)
(syl-type 0))
(sinsy_ng_addrest (round (* .1 speed)))
(mapcar (lambda (syl)
(if stypes
(cm:next cstypes)
(setf syl-type (get-syl syl-counter syls-length)))
(format t "~%~a~C~a"
syl-type #\tab
syl)
(sinsy_ng_addnote (round (* speed (cm:next cdurations)))
syl
(cm:next cnotes)
NIL
NIL
0
syl-type
(cm:next cbreaths))
(incf syl-counter))
syls))
(sinsy_ng_addrest (round (* .1 speed)))
(setf *tmp*
(chunk-to-buffer (sinsy_ng_getaudiodata l)
(cffi:mem-ref l :int)))))))
;; (defun sim (phonemes notes durations breaths &optional stypes (language "en") (speed 960))
;; "Returns a new buffer with the SPEECH rendered into it."
;; (declare (type string language))
;; (when (gethash phonemes shiny::*buffers*)
;; (incudine:free (gethash phonemes shiny::*buffers*)))
;; (with-espeak (:AUDIO_OUTPUT_SYNCHRONOUS 0 (cffi:null-pointer) 0)
;; (with-sinsy ()
;; (espeak_setsynthcallback (cffi:callback ctest))
;; (cffi:with-foreign-object (l :int)
;; (espeak_setvoicebyname language)
;; (sinsy_ng_addnote (round (* speed durations))
;; phonemes
;; notes
;; NIL
;; NIL
;; 0
;; 0
;; breaths)
;; (setf (gethash phonemes shiny::*buffers*)
;; (chunk-to-buffer (sinsy_ng_getaudiodata l)
;; (cffi:mem-ref l :int)))))))
(defun sim (phonemes note duration breath &optional (language "en")
(speed 960))
"Returns a new buffer with the SPEECH rendered into it, buffer is saved
on *BUFFERS* with PHONEMES for key"
(declare (type string phonemes language))
(when (gethash phonemes shiny::*buffers*)
(incudine:free (gethash phonemes shiny::*buffers*)))
(with-espeak (:AUDIO_OUTPUT_SYNCHRONOUS 0 (cffi:null-pointer) 0)
(with-sinsy ()
(espeak_setsynthcallback (cffi:callback ctest))
(cffi:with-foreign-object (l :int)
(espeak_setvoicebyname language)
(sinsy_ng_addnote (round (* speed duration))
phonemes
note
T
T
1
1
breath)
(setf (gethash phonemes shiny::*buffers*)
(chunk-to-buffer (sinsy_ng_getaudiodata l)
(cffi:mem-ref l :int)))))))
(defun sims (phrase notes durations breaths &optional (language "en"))
"Creates separate buffers for each list element on PHRASE."
(declare (type list phrase))
(let ((cnotes (shiny::make-cycle (alexandria:ensure-list notes)))
(cdurations (shiny::make-cycle (alexandria:ensure-list durations)))
(cbreaths (shiny::make-cycle (alexandria:ensure-list breaths))))
(mapcar
(lambda (p)
(sim p (cm:next cnotes) (cm:next cdurations) (cm:next cbreaths) language))
phrase)))
(defun sim1 (word phonemes note duration breath &optional (language "en")
(syl-type 0)
accent
stacatto
(slur-type 0)
(speed 960))
"WORD is the index on buffers
PHONEMES chunks to render, might include a space"
(declare (type string word language)
(type list phonemes))
(when (gethash word shiny::*buffers*)
(incudine:free (gethash phonemes shiny::*buffers*)))
(with-espeak (:AUDIO_OUTPUT_SYNCHRONOUS 0 (cffi:null-pointer) 0)
(with-sinsy ()
(espeak_setsynthcallback (cffi:callback ctest))
(cffi:with-foreign-object (l :int)
(espeak_setvoicebyname language)
(let ((cduration (shiny::make-cycle (alexandria:ensure-list duration)))
(cnotes (shiny::make-cycle (alexandria:ensure-list note)))
(cbreath (shiny::make-cycle (alexandria:ensure-list breath)))
(csyl-type (shiny::make-cycle (alexandria:ensure-list syl-type)))
(caccent (shiny::make-cycle (alexandria:ensure-list accent)))
(cstacatto (shiny::make-cycle (alexandria:ensure-list stacatto)))
(cslur-type (shiny::make-cycle (alexandria:ensure-list slur-type))))
(mapcar
(lambda (phoneme)
(if (string= " " phoneme)
(sinsy_ng_addrest (round (* speed .1)))
(sinsy_ng_addnote (round (* speed (cm:next cduration)))
phoneme
(cm:next cnotes)
(cm:next caccent)
(cm:next cstacatto)
(cm:next cslur-type)
(cm:next csyl-type)
(cm:next cbreath))))
phonemes))
(setf (gethash word shiny::*buffers*)
(chunk-to-buffer (sinsy_ng_getaudiodata l)
(cffi:mem-ref l :int)))))))
| 11,094 | Common Lisp | .lisp | 234 | 35.901709 | 96 | 0.502997 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 3e9a6bce5eedf109dbb70123953a2f96a6a21ab79da219ce012ebd27068dc542 | 9,041 | [
-1
] |
9,042 | midifile.lisp | azimut_shiny/lib/midifile.lisp | (in-package :shiny)
;; TODO: go-track loop end check for outer range.
;; function that returns pairs (50 .5) per measure
;;
;; NOTE
;; ----
;; In order to use the (group-measures-pair) function you need to know
;; the midi song bar length. Ex: 4/4 or 6/8. Then provide the
;; MEASURE-LENGTH, here is measure so .25 is 1 black note. a
;; MEASURE-LENGTH of 2 is then a 4/4 due (= 2 (* .25 4))
;;
;; General Midi Info
;; -----------------
;; Midi Tracks:
;; (Sometimes)One per line you see on a sheet.
;; Starting from 0, from the top OR bottom line.
;;
;; Midi Events:
;; List of midi events in hexadecimal
;; http://www.onicos.com/staff/iz/formats/midi-event.html
;;
;; 144 - 0x90 - Chan 1 Note on
;; 176 - 0xB0 - Chan 1 Control mode change
;; 192 - 0xC0 - Chan 1 Program change
;; 255 - 0xFF - Sys real time sys reset
;;
;; Midi Notes:
;; There are no explicit silence/rests on the midifile format
;;
;; Example
;; -------
;; (defparameter *notes* nil)
;; (setf *notes* (subseq (get-measures-pair *mf* 10 2 1) 6))
;; (let ((measures (make-heap *notes*)))
;; (defun f (time)
;; (let* ((measure (next measures))
;; (notes (first measure))
;; (durations (second measure)))
;; (play-midi-arp time notes 50 durations 0 (d2o durations)))
;; (aat (+ time #[2 b]) #'f it)))
(defvar *qnotes* (make-hash-table))
(defun go-track (to-track mf)
"Skip ahead TO-TRACK"
(declare (unsigned-byte to-track) (midifile:input-stream mf))
(let* ((number-of-tracks (1- (midifile:number-of-tracks mf)))
(current-track (midifile:current-track mf))
(to-track (max (min to-track number-of-tracks) 0)))
(loop :repeat (- to-track current-track)
:do (midifile:next-track mf))))
(defun get-notes (filename &optional (track-number 0))
"Just return the midi notes, useful with bars without chords.
> (get-notes *mf*)
(60 64 69 34 59 30 49 59 29)"
(declare (string filename))
(midifile:with-open-midifile (mf filename)
(go-track track-number mf)
(loop
:for ev = (midifile:read-event mf)
:while ev
:when (and (= ev 144)
(= track-number (midifile:current-track mf))
(plusp (midifile:message-data2 mf)))
:collect (midifile:message-data1 mf))))
(defun push-midi-note
(note time-seconds velocity &optional start-time coerce)
"helper for (get-notes-duration)"
(when coerce
(setf time-seconds (coerce time-seconds 'single-float)))
(let ((current (gethash note *qnotes*)))
;; NOTE: some midi files have two hits without release between them,
;; avoiding those for now
(if current
(when (zerop velocity)
;; Remove cache for note
(setf (gethash note *qnotes*) NIL)
(let ((result (list note (- time-seconds (cadr current)))))
(when start-time
(alexandria:appendf result (list (cadr current))))
result))
(when (plusp velocity)
(setf (gethash note *qnotes*)
(list note time-seconds))
NIL))))
(defun get-notes-durations
(filename &optional (track-number 0) start-time (coerce t))
"get notes and duration as pairs, useful for bars with only one note
> (get-notes-duration *mf*)
((50 .2) (60 .2) (90 1.3))"
(declare (string filename))
(clrhash *qnotes*)
(midifile:with-open-midifile (mf filename)
(go-track track-number mf)
(remove-if
#'null
(loop
:for ev = (midifile:read-event mf)
:while ev
:with previous-time = 0f0
:when (and (= ev 144)
(= track-number (midifile:current-track mf)))
:collect
(let ((seconds (midifile:event-seconds mf)))
(when (not (= previous-time seconds))
(setf previous-time seconds))
(push-midi-note (midifile:message-data1 mf)
seconds
(midifile:message-data2 mf)
start-time
coerce))))))
(defun get-notes-durations-chords
(filename &optional (track-number 0) start-time (coerce t))
"sorts and groups get-notes-duration to get the notes on chords"
(declare (string filename))
(remove-if
#'null
(loop
:for (note duration time)
:in (sort (get-notes-durations filename track-number T coerce)
#'< :key #'caddr)
:with queue
:with last-time
:collect
(cond ((not queue)
(prog1 NIL
(setf last-time time)
(setf queue (list note duration))))
((and queue (= last-time time))
(prog1 NIL
(let ((notes (append (ensure-list (car queue))
(list note)))
(durations (append (ensure-list (cadr queue))
(list duration))))
(setf queue (list notes durations)))))
((and queue (not (= last-time time)))
(let ((result queue))
(when start-time
(alexandria:appendf result (list last-time)))
(setf last-time time)
(setf queue `(,note ,duration))
result))))))
(defun get-notes-chords (filename &optional (track-number 0))
"get notes grouped by time they were triggered
> (get-notes-list *mf*)
((60 62 65) (60 62 69) (79)"
(declare (string filename))
(midifile:with-open-midifile (mf filename)
(go-track track-number mf)
(remove-if
#'null
(loop
:for ev = (midifile:read-event mf)
:while ev
:with queue = '()
:when (and (= 144 ev)
(= track-number (midifile:current-track mf))
(> (midifile:message-data2 mf) 0))
:collect
(let* ((time (midifile:event-seconds mf))
(now (list (midifile:message-data1 mf)
time)))
(cond ((not queue)
(push now queue) NIL)
((and queue (= time (cadar queue)))
(push now queue) NIL)
;; Time to return the queue
((and queue (not (= time (cadar queue))))
(prog1 (mapcar #'car queue)
(setf queue NIL)
(push now queue)))))))))
(defun get-notes-durations-chords-silences
(filename &optional (track-number 0) start-time (coerce t))
"Returns pais of notes/durations on the current TRACK-NUMBER.
Including any silence period. As a pair with 0 as the midi-note
and the duration of the silence.
> (get-notes-durations-chords-silences *mf*)
((40 0.49895832) (42 0.49895835) (43 0.49895835) (47 0.49895835)
(45 0.49895835) (43 0.49895835) (38 0.99895835) (40 0.4989581))"
(declare (string filename))
(loop
:for (notes durations time)
:in (get-notes-durations-chords filename track-number T coerce)
:with next-time
:appending
(let ((current
(if start-time
(list notes durations time)
(list notes durations))))
(cond
;; First run
((not next-time)
(setf next-time
(+ time (extremum (ensure-list durations) #'>)))
(list current))
;; Silence in between notes
((and next-time
(< next-time time)
;; NOTE: Hacks! basically we skip silences too small product
;; of the flaky math
(> (- time next-time) .02))
(let* ((zero-duration (- time next-time))
(zero-start (- time zero-duration)))
(setf next-time
(+ time (extremum (ensure-list durations) #'>)))
(if start-time
(list (list 0 zero-duration zero-start) current)
(list (list 0 zero-duration) current))))
;; No silence in between (?
(t
(setf next-time
(+ time (extremum (ensure-list durations) #'>)))
(list current))))))
;;--------------------------------------------------
(defun group-by-measure (mf &optional (measure-length 2) (track-number 0))
"returns 2 values as lists. First list of values are the notes per measure.
Second list of values is for the durations.
> (group-by-measure *mf* 2 1)
((40 42 43 47) (45 43) (40 42))
((0.49895832 0.49895835 0.49895835 0.49895835)
((0.9989586 0.9989586) (0.9989586 0.9989586)))"
(loop
:for (notes durations)
:in (get-notes-durations-chords-silences mf track-number)
:with acc-notes
:with acc-durations
:with ret-notes
:with ret-durations
:summing (if (listp durations)
(first durations)
durations) :into total-duration
:do
(cond ((> total-duration measure-length)
(setf total-duration (if (listp durations)
(first durations)
durations))
;;
(push (reverse acc-notes) ret-notes)
(push (reverse acc-durations) ret-durations)
(setf acc-notes NIL)
(setf acc-durations NIL)
;;
(push notes acc-notes)
(push durations acc-durations))
(t
(push notes acc-notes)
(push durations acc-durations)))
:finally (return (values (reverse ret-notes)
(reverse ret-durations)))))
(defun get-measures-pair
(mf &optional (n-measures 4) (measure-length 2) (track-number 0))
"Returns a list of pairs of notes and durations of the midi file MF
and TRACK-NUMBER. Up to N-MEASURES measure by MEASURE-LENGTH.
Re-arrange output of group-by-measure to make it easier to
shuffle measures around.
> (get-measures-pair *mf* 2 2 1)
(((40 42 43 47) (0.49895832 0.49895835 0.49895835 0.49895835))
((45 43 38) (0.49895835 0.49895835 0.99895835)))"
(multiple-value-bind (notes durations)
(group-by-measure mf measure-length track-number)
(loop
:for measure-notes :in notes
:for measure-durations :in durations
:repeat n-measures
:collect (list measure-notes
measure-durations))))
| 10,440 | Common Lisp | .lisp | 264 | 30.359848 | 77 | 0.563502 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | a1fb4529f8ca73f1deb271c97f88c1c644c814d9a3e8423641e537e17f638b5a | 9,042 | [
-1
] |
9,043 | nudruz.lisp | azimut_shiny/lib/nudruz.lisp | (in-package :shiny)
;;
;; Nudruz
;;
;; Code copied from https://github.com/gogins/gogins.github.io/tree/master/nudruz
;; EXPWARP -- 'warps' pits by expt factor
;; (above optional bass-note, or lowest note in chd)
;; ME: added (round) to return value
(defun expwarp (pits factor &optional (bassnote nil))
(let* ((orig-hz (remove-duplicates (cm:hertz pits)))
(bn (if bassnote bassnote (apply #'min orig-hz)))
(hzdiffs (mapcar (lambda (x) (- x bn)) orig-hz)))
(loop for n to (- (length orig-hz) 1) collect
(round (cm:keynum
(+ bn (* (nth n hzdiffs) factor))
:hz 't)))))
;;--------------------------------------------------
;; Helpers
;;--------------------------------------------------
;;INTV -- interval between two notes (simple difference)
;; can be positive or negative
;; (intv 11 17) = 6
(defun intv (x y)
(- y x))
;; MELINT -- list of melodic intervals within a list
;; "thanks Kenny Tilton!"
;; enhanced Feb. 2006 to also measure non-adjacent skips
;; example: (melint '(8 5 10 2)) = (-3 5 -8)
(defun melint (list &optional (skip 1))
(mapcar #'intv list (nthcdr skip list)))
;; DIRECTIONS -- returns 1/-1 indices for melodic up/down
;(directions '(2 3 9 6 1 3)) = (1 1 -1 -1 1)
(defun directions (melody)
(let ((mymelint (melint melody)))
(loop for x in mymelint collect
(if (eq x (abs x)) 1 -1))))
;; LISTSUB -- replaces 'olds' with 'news' in 'inlist'
(defun listsub (news olds inlist)
(sublis (pairlis olds news) inlist))
(defun random-codeword (codelen)
(shuffle (cons 1 (loop repeat (- codelen 1) collect (pick 1 0)))))
;; NO-NILS -- removes all instances of 'nil from a list
;; fixed 'reverse' bug April 2006
(defun no-nils (a-list)
(reverse
(set-difference a-list '(nil))))
;; STEP-INCREM -- single move between lists
;; utility for 'fromto-stepper'
(defun step-increm (slist elist)
(let* ((listdiffs (map 'list #'- elist slist))
(onlydiffidx (no-nils (loop for n to (- (length listdiffs) 1) collect
(if (not (eql 0 (nth n listdiffs))) n))))
(stepidx (pickl onlydiffidx)))
(loop for n to (- (length slist) 1) collect
(if (eql n stepidx) (+ (nth n slist) (/ (nth n listdiffs)
(abs (nth n listdiffs))))
(nth n slist)))))
; FROMTO-STEPPER -- more refined 'fromto'
; avoids retracing steps from 'slist' to 'elist'
; [randomly selected set of steps]
; (fromto-stepper '(0 9) '(5 6))
; = ((0 9) (1 9) (2 9) (3 9) (4 9) (4 8) (5 8) (5 7) (5 6))
(defun fromto-stepper (slist elist)
(let* ((listdiffs (map 'list #'- elist slist))
(absdiffs (loop for x in listdiffs collect (abs x)))
(totdiff (apply #'+ absdiffs)))
(cons slist
(when (plusp totdiff)
(fromto-stepper (step-increm slist elist) elist)))))
;; MELINT->LINE -- builds a line from starting pitch & melint
;; --> adds intervals from the previous pitch
;; (melint->line 50 '(1 2 4)) = (50 51 53 57)
(defun melint->line (startnum int-vector)
(cons startnum
(when int-vector
(melint->line (+ (first int-vector) startnum)
(cdr int-vector)))))
;; TRANSP -- applying 'op' of 'level' to number or list
;; level may be a rest [July 2008]
(defun transp (input level &optional (op #'+))
(if (eql level 'r) 'r
(cond
((eql input 'r) 'r)
((numberp input) (funcall op input level))
(t (mapcar (lambda (x) (transp x level op)) input)))))
;; SEQ-EQL: whether two lists are identical
;; (seq-eql '(1 2 3) '(1 3 2)) = nil
;; (seq-eql '(1 2) '(1 2)) = T
(defun seq-eql (list1 list2)
(not (mismatch list1 list2)))
;; FLATTEN -- removes all nesting in list
;; "thank you Paul Graham!"
(defun flatten (x)
(labels ((rec (x acc)
(cond ((null x) acc)
((atom x) (cons x acc))
(t (rec (car x) (rec (cdr x) acc))))))
(rec x nil)))
;; DIVVY-UP -- simple utility used in 'ferney'
(defun divvy-up (mlen subdiv &optional (numtype 'float))
(loop repeat subdiv collect
(if (eql numtype 'float)
(float (/ mlen subdiv))
(/ mlen subdiv))))
;; FERNEY -- build list from mlens, subdivs, durs
;; now using modified 'ferneyrat' [Jan. 2006]
;; may specify rats or floats
;; cycling through everything
;; omitting durations will yield 'basic' mlens/subdivs list
;; Jan 2011: added 'treeflag'
;; (ferney '(2 3) '(1 2 4) '(2 4) 'float) =
;; (3.5 3.0 3.5 3.5 1.5 5.5 1.0 5.5 1.5 5.0 2.0 4.5 2.0 3.0)
(defun ferney (mlens subdivs &optional (durs '(1)) (treeflag nil) (numtype 'rat))
(let* ((mlens-cyc (new cycle of mlens))
(subdivs-cyc (new cycle of subdivs))
(durs-cyc (new cycle of durs))
(ferntree
(loop until (and (cm:eop? mlens-cyc)
(cm:eop? subdivs-cyc))
collect (divvy-up (next mlens-cyc)
(next subdivs-cyc)
numtype)))
(flatcyc
(new cycle of
(flatten ferntree))))
(if treeflag ferntree
(loop until (and (cm:eop? flatcyc) (cm:eop? durs-cyc))
collect (apply #'+ (next flatcyc (next durs-cyc)))))))
;; RANDVEC -- list of random mod-x integers (could include repeats)
;; as (random len &optional (modlen 12))
;; (randvec 5 3) = (2 1 2 0 0)
;; added Nov. 2005
(defun randvec (len &optional (modlen 12) (transplevel 0))
(let ((randpitrand (new weighting :of
(loop for x from 0 to (- modlen 1) collect x))))
(transp (loop repeat len collect (next randpitrand)) transplevel)))
;; FLATTER -- removes one level of tree (preserves sublists)
(defun flatter (alist)
(loop for a in alist append a))
;; EQL-SUMMER -- all ways to sum componentnums to targetnum
;; if fails, returns targetnum
(defun eql-summer (targetnum componentnums)
(let ((es (eqlsum targetnum componentnums)))
(if es es (list targetnum))))
;; ONES&TWOS -- all seqs of 1&2 summing to a number
(defun ones&twos (anum)
(remove-duplicates
(alexandria:map-permutations
#'flatter
(eql-summer anum '(1 2)))
:test #'seq-eql))
;; PERMUTATIONS -- returns all permutations of a list
;; (defun permutations (a-list)
;; (loop for x in
;; (cllib:permutations-list (make-array (length a-list)
;; :initial-contents a-list))
;; collect (coerce x 'list)))
(defun permutations (list)
(if list
(mapcan #'(lambda (x)
(mapcar #'(lambda (y) (cons x y))
(permutations (remove x list))))
list)
'(()))) ; else
;; N-OF-LIST -- utility for wiggle-to2
(defun n-of-list (n l)
(if (= n 0) '()
(cons (screamer:a-member-of l) (n-of-list (- n 1) l))))
;;; LIST-EQL: whether two lists have equal contents, irrespective of order
;; (list-eql '(1 2 3) '(1 3 2)) = T
(defun list-eql (list1 list2)
(and (subsetp list1 list2)
(subsetp list2 list1)
(= (length list1) (length list2))))
;; EQLSUM -- finds all combos of 'componentnums' that sum to 'targetnum'
(defun eqlsum (targetnum componentnums)
(remove-duplicates
(screamer:all-values
(let* ((maxlen (ceiling (/ targetnum (reduce #'min componentnums))))
(multvars (n-of-list (screamer:an-integer-between 0 maxlen) componentnums)))
(unless (= (reduce #'+ multvars) targetnum) (screamer:fail))
multvars))
:test #'list-eql))
;; COPYLIST -- make copies of list
; (copylist '(3 4 5) 3) = (3 4 5 3 4 5 3 4 5)
;; outputs list or tree [July 2008]
;; takes atom as input [May 2009]
(defun copylist (input mult &optional (notflat nil))
(let* ((a-list (if (listp input) input (list input)))
(rawlist
(loop repeat mult collect a-list)))
(if notflat rawlist (flatten rawlist))))
;; ALLROTS -- returns list of all rotations of list
;; (allrots '(58 60 54)) = ((58 60 54) (60 54 58) (54 58 60))
;; fixed May 2009
(defun allrots (alist)
(mapcar
(lambda (x) (rotate-list alist x))
(indices (length alist))))
;; MAKE-POLY -- distributes line according to texture vector
;; (make-poly '(1 2 3 4 5 6) '(1 0 2)) = ((1) (R) (2 3) (4) (R) (5 6))
;; changed June 2005
;; Nov. 2005: added 0->R functionality
;; Aug. 2006: using 'likeflat' for better output
;; May 2009: 'fitflag'=t ends with complete texture, ie no partial textures
(defun make-poly (mel texture &optional (fitflag nil))
(like-flat
(if fitflag
(let* ((mel-len (length mel))
(txtlist
(copylist texture
(floor (/ mel-len
(apply #'+
(flatten (not-flat texture))))))))
(loop for txt in txtlist
collect (no-nils
(if (eql txt 0) (list 'r)
(loop repeat txt collect (pop mel))))))
(let ((txtcyc (new cycle of texture)))
(loop while mel
collect (no-nils
(let ((nxt-txt (next txtcyc)))
(if (eql nxt-txt 0) (list 'r)
(loop repeat nxt-txt collect (pop mel))))))))))
;; ALLSWAPS -- all pairwise 'place swaps' (permutations) in a list
(defun allswaps (alist)
(let ((polys (cons 2
(copylist (list 1) (- (length alist) 2)))))
(loop for p in (allrots polys) collect
(flatten
(mapcar
(lambda (x) (if (numberp x) x (reverse x)))
(make-poly alist p))))))
;; INDICES -- get a quick list of integers
;; (indices 4) = (0 1 2 3)
;; enhanced June 2005
(defun indices (len &optional (base 0))
(transp (loop for n to (- len 1) collect n) base))
;; LIKE-FLAT -- converts all 1-lists to atoms; leaves the rest alone
;; August 2006
(defun like-flat (alist)
(mapcar (lambda (x) (if (and (listp x) (eql 1 (length x)))
(car x)
x))
alist))
;; NORESTS -- removes rests
(defun norests (alist)
(no-nils (loop for x in alist collect
(if (not (eql x 'r)) x))))
;; NOT-FLAT -- makes everything into a list; leaves lists alone
;; (not-flat '(2 4 (3 4) 2 (2 1 4))) = ((2) (4) (3 4) (2) (2 1 4))
;; removing rests in chords (May 2007)
;; makes atoms into lists (May 2009)
(defun not-flat (alist)
(if (listp alist)
(mapcar (lambda (x) (if (listp x) (norests x) (list x)))
alist)
(list alist)))
;; SAFESORT -- non-destructive sort
(defun safesort (a-list)
(let ((templist (loop for a in a-list collect a)))
(sort templist #'<)))
;; RECURZ -- generalized recursion; returns chain
;; 'input' always a list
(defun recurz (func input len)
(cond ((eql len 1) input)
((eql len 2) (list input (funcall func input)))
(t
(let ((prev (recurz func input (- len 1))))
(append prev (list (funcall func (car (last prev)))))))))
;;--------------------------------------------------
;; END Helpers
;;--------------------------------------------------
;;--------------------------------------------------
;; rhythms.lisp
;;--------------------------------------------------
;; CYC-RHYTHMS -- combines measures and subdivisions cyclically
(defun cyc-rhythms (mlens subdivs)
(let* ((subdivcyc (new cycle of subdivs))
(mlencyc (new cycle of mlens)))
(loop until (and (eop? subdivcyc)
(eop? mlencyc))
for this-subdiv = (next subdivcyc)
for this-mlen = (next mlencyc)
append (loop repeat this-subdiv
collect (float (/ this-mlen this-subdiv))))))
;; UPBEATCYC -- returns upbeat cycle
;; between 'minups' and 'maxups' upbeats of 1
;; between 'mindown' and 'maxdown' length of downbeat
;;(next (upbeatcyc 2 5 10 20) 20)
(defun upbeatcyc (minups maxups mindown maxdown)
(new weighting :of `((1 :min ,minups :max ,maxups)
(,(pval (between mindown maxdown)) :max 1))))
;; COMBINE-ATKS -- 'fuses' attacks within a rhythm
;; 'combiner' = number of attacks to combine (cycle)
(defun combine-atks (rhythms atklist)
(let ((rcyc (new cycle of rhythms))
(atkcyc (new cycle of atklist)))
(loop until (and (eop? rcyc) (eop? atkcyc))
collect (apply #'+ (next rcyc (next atkcyc))))))
;; (combine-atks '(1 2) '(1 1 3))
;; = (1 2 4 2 1 5)
;;--------------------------------------------------
;; EOF rhythms
;;--------------------------------------------------
;; UDWN -- note-to-note utility for 'make-updown'
(defun udwn (startpit endpit udval &optional (modlen 12))
(let* ((m-startpit (mod startpit modlen))
(m-endpit (mod endpit modlen))
(modfloor (floor (/ startpit modlen)))
(grtrflag (> m-startpit m-endpit)))
(case udval
(1 (+ m-endpit
(* modlen
(+ (if grtrflag 1 0) modfloor))))
(-1 (+ m-endpit
(* modlen
(+ (if grtrflag 0 -1) modfloor))))
(t startpit))))
;; MAKE-UPDOWN -- applying +1/-1 contour to 'alist' from first pit
(defun make-updown (alist udvals &optional (modlen 12))
(if (eql 2 (length alist))
(list (car alist) (udwn (car alist) (cadr alist) (car udvals) modlen))
(cons (car alist)
(make-updown
(cons (udwn (car alist) (cadr alist) (car udvals) modlen)
(cddr alist))
(cdr udvals)
modlen))))
;; TAKE-UPDOWN - same as 'directions'
(defun take-updown (melody)
(directions melody))
;; UPDOWN-OPPOSITE -- opposite signs
(defun updown-opposite (udvec)
(mapcar (lambda (x) (* -1 x)) udvec))
;; UPDOWN-RANDOM -- random contour
(defun updown-random (len)
(listsub '(-1 1) '(0 1)
(random-codeword len)))
;; UPDOWN-CONVERSIONS -- list of updown p,i,r,ri
(defun updown-conversions (udvec)
(list udvec
(updown-opposite udvec)
(reverse udvec)
(reverse (updown-opposite udvec))))
;; MAKE-UPDOWN-RANDOM -- apply random updown
(defun make-updown-random (alist &optional (modlen 12))
(make-updown alist
(updown-random (- (length alist) 1))
modlen))
;; FLIP-CONTOUR -- change up/down directions
(defun flip-contour (melody)
(make-updown melody
(updown-opposite (take-updown melody))))
;;; CHOOSER -- returns members of 'alist' from list of indices 'idxs'
;; now treats rests -- Jan. 2008
;; now treats sublists -- July 2008
;; azimut: like my nths...
(defun chooser (idxs alist)
(loop for n in idxs collect
(if (listp n) (chooser n alist)
(if (eql n 'r) 'r
(nth n alist)))))
; UPDOWN-FROMTO -- stepwise up/down contour change (incl first & last)
(defun updown-fromto (ud-start ud-end)
(let* ((start01
(listsub '(0 1) '(-1 1) ud-start))
(end01
(listsub '(0 1) '(-1 1) ud-end)))
(mapcar
(lambda (x) (chooser x '(-1 1)))
(fromto-stepper start01 end01))))
;; (all-updowns len) ?
;; neumes = three or four pitches
;; "neumatic transformations" (p. 34)
;; CRAW-INTS
;; each interval is replaced by its complement or compound
(defun craw-ints (neume &optional (modlen 12))
(let* ((neumelint (melint neume))
(neumintlen (length neumelint)))
(mapcar (lambda (x) (melint->line (car neume) x))
(loop for victim to (- neumintlen 1) append
(loop for trindx in '(1 -1) collect
(loop for n to (- neumintlen 1) collect
(if (eql n victim)
(+ (nth n neumelint)
(* trindx modlen))
(nth n neumelint))))))))
;; CRAW-MELCONVERSIONS
(defun craw-melconversions (mymel)
(let* ((mymint (melint mymel))
(mymintit (transp mymint -1 #'*)))
(mapcar
(lambda (x)
(melint->line (car mymel) x))
(list mymint
mymintit
(reverse mymint)
(reverse mymintit)))))
;; CRAW-CONV -- random melconversion
(defun craw-conv (amel)
(pickl (craw-melconversions amel)))
;; CRAW-MULT -- all intervals multiplied by a constant
(defun craw-mult (amel mfactor)
(let* ((amint (melint amel)))
(melint->line (car amel) (transp amint mfactor #'*))))
;; CRAW-ADD -- all intervals expanded/contracted by a constant
(defun craw-add (amel mfactor)
(let* ((amint (melint amel)))
(melint->line (car amel)
(map 'list #'*
(take-updown amel)
(transp (mapcar #'abs amint) mfactor)))))
;; CRAW-PE -- 'partial expansion' (all collected)
;; one interval expands by a semitone
(defun craw-pe (amel)
(let* ((mint (melint amel))
(pevec
(mapcar (lambda (x)
(cond ((plusp x) (+ x 1))
((minusp x) (- x 1))
(t x)))
mint))
(mlen (- (length mint) 1)))
(mapcar
(lambda (x) (melint->line (car amel) x))
(reverse
(set-difference
(loop for m to mlen collect
(loop for n to mlen collect
(if (= m n) (nth n pevec) (nth n mint))))
(list mint)
:test #'seq-eql)))))
;; CRAW-PC -- 'partial expansion' (all collected)
;; one interval contracts by a semitone
(defun craw-pc (amel)
(let* ((mint (melint amel))
(pevec
(mapcar (lambda (x)
(cond ((plusp x) (- x 1))
((minusp x) (+ x 1))
(t x)))
mint))
(mlen (- (length mint) 1)))
(mapcar
(lambda (x) (melint->line (car amel) x))
(reverse
(set-difference
(loop for m to mlen collect
(loop for n to mlen collect
(if (= m n) (nth n pevec) (nth n mint))))
(list mint)
:test #'seq-eql)))))
;; ALL-CRAW -- all transformations
;; useful for 'generic-path' & 'generic-branch'
(defun all-craw (amel &optional (modlen 12))
(remove-duplicates
(append (craw-ints amel)
(craw-melconversions amel)
(loop for n from 1 to 7 collect
(craw-mult amel n))
(loop for n from -11 to 11 collect
(craw-add amel n))
(craw-pe amel))
:test #'seq-eql))
;; ALL-CRAW-PE-PC -- all contractions + expansions
(defun all-craw-pe-pc (amel)
(remove-duplicates
(append (craw-pe amel) (craw-pc amel))
:test #'seq-eql))
;;
;; verse rhythms -- inspired by Crawford
(defun make-verse (len)
(mapcar
(lambda (x) (ferney '(1) x (pickl (cons x (ones&twos x)))))
(randvec len 3 3)))
; verse variations
;; VERSE-SWAPS -- adjacent bars swapped (all possible)
;;> (verse-swaps '(60 62 64 67))
;; ((62 60 64 67) (60 64 62 67) (60 62 67 64))
(defun verse-swaps (averse)
(chooser
(allswaps (indices (length averse)))
averse))
;; VERSE-DROPS -- single verse dropped (all possible)
;; > (verse-drops '(60 62 64 67))
;; ((62 64 67) (60 64 67) (60 62 67) (60 62 64))
(defun verse-drops (averse)
(let ((verseidx (indices (length averse))))
(mapcar
(lambda (x) (chooser x averse))
(mapcar
(lambda (x)
(safesort
(set-difference verseidx (list x))))
verseidx))))
; SWAPDROP-CHAIN -- recursive random swaps & drops
(defun swapdrop-chain (a-verse len)
(no-nils
(recurz
(lambda (x)
(pickl (append (verse-swaps x)
(verse-drops x))))
a-verse
len)))
| 18,336 | Common Lisp | .lisp | 505 | 31.978218 | 87 | 0.609517 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 28557ea2047d3f7d681c656da895f7130399d2d6eabb712b3d5ed7d16a6b7a1c | 9,043 | [
-1
] |
9,044 | inscore.lisp | azimut_shiny/lib/inscore.lisp | (in-package :shiny)
;; NOTE: all this is kind of flaky. As it works mostly with one voice
;; per score. And that won't change until all notes go to a common place
;; where they then can be converted into chords (events from different
;; sources happening at the same time).
;; And might be not even that will help for livecoding. As there is no time
;; index or anything being send on a stream so, everything happens serially
;; a voice at the time, without a possible whole note followed by a quarted
;; before the whole finish...
;; TODO:
;; - use more (par)
;; Reference:
;; http://www.grame.fr/ressources/publications/inscore-tenor-2016.pdf
(defvar *oscout* nil)
(defvar *window-name* "scene")
(defvar *layer-name* "l")
(defvar *bar-counter* (make-hash-table :test #'equal))
(defvar *meter* "4/4")
(defvar *clef* "f")
(defun inscore-reset
(&optional (window-name *window-name*) delete)
"delete elements under /ITL/WINDOW-NAME/*, or the whole window
thing if DELETE is set T"
(declare (string window-name) (boolean delete))
(let* ((root (concatenate 'string "/ITL/" window-name))
(childs (concatenate 'string root "/*")))
(setf (gethash window-name *bar-counter*) 30)
(osc:message *oscout* childs "s" "del")
(clrhash *bar-counter*)
(when delete
(osc:message *oscout* root "s" "del"))))
(defun inscore-init
(&optional (window-name *window-name*) (layer-name *layer-name*))
"create WINDOW-NAME if not exists and a layer LAYER-NAME under it
with a black background"
(declare (string window-name layer-name))
(let* ((root (concatenate 'string "/ITL/" window-name))
(layer (concatenate 'string root "/" layer-name))
(background (concatenate 'string layer "/background")))
(osc:message *oscout* root "s" "new")
(osc:message *oscout* layer "ss" "set" "layer")
(osc:message *oscout* background "ssff" "set" "rect" 10f0 10f0)
(osc:message *oscout* background "siii" "color" 0 0 0)))
(defun make-inscore ()
"initialize *oscout* global variable and initialize window"
(setf *oscout*
(osc:open :host "127.0.0.1"
:port 7000
:direction :output))
(inscore-reset)
(inscore-init))
(defun inscore-score-debug
(score &key (window-name *window-name*) (layer-name *layer-name*))
"write a whole static score into WINDOW-NAME under LAYER-NAME"
(declare (string score window-name layer-name))
(let ((score-path
(concatenate 'string "/ITL/" window-name "/" layer-name "/score")))
(osc:message
*oscout* score-path "sss" "set" "gmn"
score)
;;COLOR WHITE
(osc:message *oscout* score-path "siii" "color" 240 240 240)))
(defun inscore-score
(score &key
(meter *meter*) (clef *clef*) (key 0)
(window-name *window-name*) (layer-name *layer-name*))
"static score"
(let ((score-path
(concatenate 'string "/ITL/" window-name "/" layer-name "/score")))
(osc:message
*oscout* score-path "sss" "set" "gmn"
(format nil "[ \\meter<\"~a\"> \\clef<\"~a\"> \\key<~a> ~a ]"
meter clef key score))
;;COLOR WHITE
(osc:message *oscout* score-path "siii" "color" 240 240 240)))
(defun inscore-stream
(&key
(meter *meter* meter-p) (clef *clef* clef-p) (key 0 key-p)
(window-name *window-name*) (layer-name *layer-name*))
"stream score"
(let ((final-score "[ ")
(score-path
(concatenate 'string "/ITL/" window-name "/" layer-name "/score")))
(inscore-init window-name layer-name)
(when clef-p
(setf final-score (format nil "~a\\clef<\"~a\"> " final-score clef)))
(when meter-p
(setf final-score (format nil "~a\\meter<\"~a\"> " final-score meter)))
(when key-p
(setf final-score (format nil "~a\\key<~d> " final-score key)))
(osc:message
*oscout* score-path "sss" "set" "gmnstream"
final-score)
;; (osc:message *oscout* score-path "si" "tempo" 60)
;; (osc:message *oscout* score-path "si" "date" 60)
;;COLOR WHITE
(osc:message *oscout* score-path "siii" "color" 240 240 240)))
(defun inscore-write
(score &optional (window-name *window-name*) (layer-name *layer-name*))
"add the gmn code to the current gmn stream"
(declare (string score window-name layer-name))
(let ((score-path
(concatenate 'string "/ITL/" window-name "/" layer-name "/score")))
(osc:message
*oscout* score-path "ss" "write"
(format nil " ~a " score))))
;;--------------------------------------------------
;; Music Notation Helpers
(defvar *inscore-reverse-notes*
(alexandria:alist-hash-table
'((0 . "c") (1 . "c#")
(2 . "d") (3 . "e&")
(4 . "e") (5 . "f")
(6 . "f#") (7 . "f#")
(8 . "a&") (9 . "a")
(10 . "b&") (11 . "b"))))
(defun inscore-reverse-notes (n)
(declare (unsigned-byte n))
(format nil "~a~d"
(gethash (mod n 12) *inscore-reverse-notes*)
(+ -3 (cm:octave-number n))))
;; a*1/4
;; Denominators: 1*1.5 1 2 4 8 16 32 64
;; Seconds: 6 4 2 1 .5 .25
;; 2^: 0 1 2 3 4 5 6
;; HACKS!!... I need some math here instead...oh well
(defun inscore-rhythm (n)
(cond ((>= n 8) (format nil "*~d/1" (round (/ n 4))))
((<= 4 n 8) "/1")
((<= 2 n 4) "/2")
((<= 1 n 2) "/4")
((<= .5 n 1) "/8")
((<= .25 n .4) "/16")
((<= .125 n) "/32")
((<= .0625 n) "/64")
(t "/1")))
| 5,466 | Common Lisp | .lisp | 136 | 35.264706 | 77 | 0.601054 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | f8534eaae437b7e9292931d7180877e09e6367586fbc14c877509205f0732667 | 9,044 | [
-1
] |
9,045 | fluidsynth.lisp | azimut_shiny/lib/fluidsynth.lisp | (in-package #:shiny)
(defvar *settings* (fluidsynth:new-settings
`(("synth.polyphony" 128)
("synth.midi-channels" 32)
("synth.sample-rate" ,*sample-rate*)
("audio.sample-format" "float"))))
(defvar *synth* (fluidsynth:new *settings*))
(dsp! fluid-test ((synth fluidsynth:synth))
(with ((len (block-size))
(left (make-f32-array len))
(right (make-f32-array len)))
(fluidsynth:write-float synth len left 0 1 right 0 1)
(foreach-frame
(out (f32-ref left current-frame)
(f32-ref right current-frame)))))
;; Adding filters to output from fluidsynth.
;;----------------------------------------
;; Due the output is single-float I cannot apply a filter directly
;; So i dump the channels to buses. Then use a second dsp to filter.
;; Trying to implement:
;; https://sourceforge.net/p/incudine/mailman/message/36266377/
;; I use this when rt-block-size != 1, otherwise just use (bus) directly
(define-vug input-bus ((channel fixnum))
(bus
(the fixnum
(+ (the fixnum (* current-frame 2))
channel
2))))
(dsp! fluid-in-down ((synth fluidsynth:synth))
(with ((len (block-size))
(left (make-f32-array len))
(right (make-f32-array len)))
(fluidsynth:write-float synth len left 0 1 right 0 1)
(foreach-frame
(setf (input-bus 0) (f32-ref left current-frame)
(input-bus 1) (f32-ref right current-frame)))))
;; (fluid-in-down *synth*)
;; (fluid-out-down)
;; (free (node 0))
;; (lvc-mono )
;; (p (now) 60 60 1 0)
;; (incudine.vug:lv2->vug "http://invadarecords.com/plugins/lv2/compressor/mono"
;; lvc-mono)
;; (incudine.vug:lv2->vug "http://invadarecords.com/plugins/lv2/compressor/stereo"
;; lvc-stereo)
;; (dsp! fluid-out-down ()
;; (foreach-frame
;; (foreach-channel
;; (with-samples ((c (input-bus current-channel)))
;; (cout c)))))
;;--------------------------------------------------
(defgeneric p (time pitch velocity duration channel &key pan))
;; Stop reusing p here. WHY?
(defmethod p ((time double-float) (pitch list) (velocity fixnum) (duration number) (channel fixnum) &key pan)
"Play chord of notes"
(mapc (lambda (p)
(declare (fixnum p))
(when (and (> p 0) (> duration 0) (> velocity 0))
(when pan (fpan channel pan))
(at time #'fluidsynth:noteon *synth* channel p velocity)
(at (+ time (calc-beats duration)) #'fluidsynth:noteoff *synth* channel p)))
pitch))
(defmethod p ((time double-float) (pitch list) (velocity fixnum) (duration list) (channel fixnum) &key pan)
"Play chord of notes, with provided durations"
(mapc (lambda (p d)
(declare (fixnum p))
(when (and (> p 0) (> d 0) (> velocity))
(when pan (fpan channel pan))
(at time #'fluidsynth:noteon *synth* channel p velocity)
(at (+ time (calc-beats d)) #'fluidsynth:noteoff *synth* channel p)))
pitch
duration))
(defmethod p ((time double-float) (pitch list) (velocity fixnum) (duration number) (channel list) &key pan)
"Play chord of notes, on provided channels"
(mapc (lambda (p c)
(declare (fixnum p c))
(p time p velocity duration c))
pitch
channel))
(defmethod p ((time double-float) (pitch fixnum) (velocity fixnum) (duration number) (channel fixnum) &key pan)
"Play given pitch"
(when (and (< 0 pitch 127)
(> duration 0)
(> velocity 0))
(when pan
(fluidsynth:cc *synth* channel 10 (alexandria:clamp pan 0 127)))
(at time #'fluidsynth:noteon *synth* channel pitch velocity)
(at (+ time (calc-beats duration)) #'fluidsynth:noteoff *synth* channel pitch))
pitch)
(defmethod p ((time double-float) (pitch fixnum) (velocity fixnum) (duration symbol) (channel fixnum) &key pan)
"Play given pitch, at CM duration/rythm"
(let ((d (cm:rhythm duration)))
(when (and (> d 0) (> velocity 0))
(at time #'fluidsynth:noteon *synth* channel pitch velocity)
(at (+ time (calc-beats d)) #'fluidsynth:noteoff *synth* channel pitch)))
pitch)
(defmethod p ((time double-float) (pitch symbol) (velocity fixnum) (duration symbol) (channel fixnum) &key pan)
"Play given note on american notation, at CM duration/rhythm"
(unless (and (eql :_ pitch) (eql 'cm::r pitch) (eql NIL pitch))
(let ((n (if (keywordp pitch) (note pitch) (cm:keynum pitch)))
(d (cm:rhythm duration)))
(declare (fixnum n))
(when (and (> d 0) (> velocity 0))
(at time #'fluidsynth:noteon *synth* channel n velocity)
(at (+ time (calc-beats d)) #'fluidsynth:noteoff *synth* channel n))))
pitch)
(defmethod p ((time double-float) (pitch symbol) (velocity fixnum) (duration number) (channel fixnum) &key pan)
"Play given note on american notation"
(when (and (> duration 0)
(not (eql NIL pitch))
(not (eql :_ pitch))
(not (eql 'cm::r pitch))
(> velocity 0))
(let ((n (if (keywordp pitch) (note pitch) (cm:keynum pitch))))
(declare (fixnum n))
(at time #'fluidsynth:noteon *synth* channel n velocity)
(at (+ time (calc-beats duration)) #'fluidsynth:noteoff *synth* channel n)))
pitch)
;;--------------------------------------------------
;; TODO:
;; - add one that takes a single note and multiple velocities,
;; useful for cycles that last whole bars.
;; - use a more generic macro so i can use the same pattern for midi/jack
(defgeneric pa (time notes velocity duration channel offset)
(:documentation "Play the given notes as an arpeggio"))
;; Single note, single all
(defmethod pa ((time double-float) (notes number) (velocity fixnum) (duration number) (channel fixnum) (offset number))
(when (>= offset 0)
(p (+ time (calc-beats offset)) notes velocity duration channel))
notes)
;; Single note, multiple other things
(defmethod pa ((time double-float) (notes number) (velocity list) (duration number) (channel fixnum) (offset number))
(let* ((lnotes (length velocity))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(map nil (lambda (v o)
(declare (fixnum v))
(p (+ time (calc-beats o)) notes v duration channel))
velocity
offsets)
notes))
(defmethod pa ((time double-float) (notes number) (velocity fixnum) (duration list) (channel fixnum) (offset number))
(let* ((lnotes (length duration))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(map nil (lambda (d o)
(p (+ time (calc-beats o)) notes velocity d channel))
duration
offsets)
notes))
(defmethod pa ((time double-float) (notes number) (velocity fixnum) (duration number) (channel fixnum) (offset list))
(map nil (lambda (o)
(when (>= o 0)
(p (+ time (calc-beats o)) notes velocity duration channel)))
offset)
notes)
(defmethod pa ((time double-float) (notes number) (velocity list) (duration number) (channel fixnum) (offset list))
(map nil (lambda (v o)
(declare (fixnum v))
(when (>= o 0)
(p (+ time (calc-beats o)) notes v duration channel)))
velocity
offset)
notes)
(defmethod pa ((time double-float) (notes number) (velocity fixnum) (duration list) (channel fixnum) (offset list))
(map nil (lambda (d o)
(when (>= o 0)
(p (+ time (calc-beats o)) notes velocity d channel)))
duration
offset)
notes)
;; Multiple notes
(defmethod pa ((time double-float) (notes list) (velocity fixnum) (duration number) (channel fixnum) (offset number))
(let* ((lnotes (length notes))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(mapc (lambda (n o)
;; (declare (fixnum n) (number o))
(p (+ time (calc-beats o)) n velocity duration channel))
notes
offsets)))
(defmethod pa ((time double-float) (notes list) (velocity fixnum) (duration number) (channel list) (offset number))
(let* ((lnotes (length notes))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(mapc (lambda (n o c)
(declare (fixnum c))
(p (+ time (calc-beats o)) n velocity duration c))
notes
offsets
channel)))
(defmethod pa ((time double-float) (notes list) (velocity list) (duration number) (channel fixnum) (offset number))
(let* ((lnotes (length notes))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(mapc (lambda (n o v)
(declare (fixnum v))
(p (+ time (calc-beats o)) n v duration channel))
notes
offsets
velocity)))
(defmethod pa ((time double-float) (notes list) (velocity list) (duration number) (channel list) (offset number))
(let* ((lnotes (length notes))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(mapc (lambda (n o v c)
(declare (fixnum v c))
(p (+ time (calc-beats o)) n v duration c))
notes
offsets
velocity
channel)))
(defmethod pa ((time double-float) (notes list) (velocity fixnum) (duration list) (channel fixnum) (offset number))
(let* ((lnotes (length notes))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(mapc (lambda (n o d)
;;(declare (fixnum n))
(p (+ time (calc-beats o)) n velocity d channel))
notes
offsets
duration)))
(defmethod pa ((time double-float) (notes list) (velocity fixnum) (duration list) (channel list) (offset number))
(let* ((lnotes (length notes))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(mapc (lambda (n o c d)
(declare (fixnum c))
(p (+ time (calc-beats o)) n velocity d c))
notes
offsets
channel
duration)))
(defmethod pa ((time double-float) (notes list) (velocity list) (duration list) (channel fixnum) (offset number))
(let* ((lnotes (length notes))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(mapc (lambda (n o v d)
(declare (fixnum v))
(p (+ time (calc-beats o)) n v d channel))
notes
offsets
velocity
duration)))
(defmethod pa ((time double-float) (notes list) (velocity list) (duration list) (channel list) (offset number))
(let* ((lnotes (length notes))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(mapc (lambda (n o v c d)
(declare (fixnum v c))
(p (+ time (calc-beats o)) n v d c))
notes
offsets
velocity
channel
duration)))
(defmethod pa ((time double-float) (notes list) (velocity fixnum) (duration number) (channel fixnum) (offset list))
(mapc (lambda (n o)
;;(declare (fixnum n))
(p (+ time (calc-beats o)) n velocity duration channel))
notes
offset))
(defmethod pa ((time double-float) (notes list) (velocity fixnum) (duration number) (channel list) (offset list))
(mapc (lambda (n o c)
(declare (fixnum c))
(p (+ time (calc-beats o)) n velocity duration c))
notes
offset
channel))
(defmethod pa ((time double-float) (notes list) (velocity list) (duration number) (channel fixnum) (offset list))
(mapc (lambda (n o v)
(declare (fixnum v))
(p (+ time (calc-beats o)) n v duration channel))
notes
offset
velocity))
(defmethod pa ((time double-float) (notes list) (velocity list) (duration number) (channel list) (offset list))
(mapc (lambda (n o v c)
(declare (fixnum v c))
(p (+ time (calc-beats o)) n v duration c))
notes
offset
velocity
channel))
(defmethod pa ((time double-float) (notes list) (velocity fixnum) (duration list) (channel fixnum) (offset list))
(mapc (lambda (n o d)
;;(declare (fixnum n))
(p (+ time (calc-beats o)) n velocity d channel))
notes
offset
duration))
(defmethod pa ((time double-float) (notes list) (velocity fixnum) (duration list) (channel list) (offset list))
(mapc (lambda (n o c d)
(declare (fixnum c))
(p (+ time (calc-beats o)) n velocity d c))
notes
offset
channel
duration))
(defmethod pa ((time double-float) (notes list) (velocity list) (duration list) (channel fixnum) (offset list))
(mapc (lambda (n o v d)
(declare (fixnum v))
(p (+ time (calc-beats o)) n v d channel))
notes
offset
velocity
duration))
(defmethod pa ((time double-float) (notes list) (velocity list) (duration list) (channel list) (offset list))
(mapc (lambda (n o v c d)
(declare (fixnum v c))
(p (+ time (calc-beats o)) n v d c))
notes
offset
velocity
channel
duration))
;;--------------------------------------------------
(defun freset ()
"reset all the things! (programs and synths)"
(fluidsynth:system-reset *synth*))
(defun off-with-the-notes (&optional (max-channels 32))
"turn off all the notes"
(dotimes (chan max-channels)
(fluidsynth:all-notes-off *synth* chan)))
;; ---------------------------------------------------
;; http://midi.teragonaudio.com/tech/midispec/pressure.htm
(defun fpress (channel pressure)
"Set the MIDI channel pressure controllre value.
a.k.a wibbly-woobly
0>=pressure>=127"
(declare (type (integer 0 127) pressure))
(fluidsynth:channel-pressure *synth* channel pressure))
;; http://midi.teragonaudio.com/tech/midispec.htm
(defun fsens (channel sens)
"Set MIDI pitch wheel (aka sensitivity) on a MIDI channel.
0>=sens>=72"
(declare (type (integer 0 72) sens))
(fluidsynth:pitch-wheel-sens *synth* channel sens))
;; NOTE: I think the default is correct...sounds like it
;; http://www.moforte.com/geoShredAssets2.0/help/pitchBendRange.html
;; "If 8192 equals 12 semitones, then one semitone is pitchbend value 8192 / 12 = 682.66667."
(defun fpitch (channel &optional (bend 8192))
"Set the MIDI pitch bend controller value on a MIDI channel.
0>=bend>=16383"
(declare (type (integer 0 16383) bend))
(fluidsynth:pitch-bend *synth* channel bend))
;; From FoxDot
(defun fspread (channel left-p &optional (semitones .125))
(declare (type boolean left-p))
(if left-p (fpan channel 0) (fpan channel 127))
(fpitch channel (+ 8192 (round (* semitones (/ 8192 12))))))
;; ---------------------------------------------------
(let ((enabled 0))
(defun fchorus-toggle ()
(setf enabled (mod (1+ enabled) 2))
(fluidsynth:set-chorus-on *synth* enabled)
(if (zerop enabled) :DISABLED :ENABLED)))
(defun fchorus (&key (nr 3 nr-set)
(level 2.0d0 level-set)
(speed 0.3d0 speed-set)
(depth 8.0d0 depth-set)
(mode 0 mode-set))
(assert (and (<= 0 nr 99)
(<= 0d0 level 10d0)
(<= 0.29d0 speed 5.0d0)
(<= 0.0d0 depth 21.0d0)
(or (= mode 0) (= mode 1))))
(when (or nr-set level-set speed-set
depth-set mode-set)
(fluidsynth:set-chorus *synth*
nr level speed
depth mode)))
;;--------------------------------------------------
(let ((enabled 0))
(defun freverb-toggle ()
(setf enabled (mod (1+ enabled) 2))
(fluidsynth:set-reverb-on *synth* enabled)
(if (zerop enabled) :DISABLED :ENABLED)))
(defun freverb (&key (roomsize 0.2d0 roomsize-p)
(damp 0.0d0 damp-p)
(width 0.5d0 width-p)
(level 0.9d0 level-p))
(when (or roomsize-p damp-p width-p level-p)
(fluidsynth:set-reverb *synth* roomsize damp width level)))
;; fluid_synth.c
(defun freverb-preset (preset)
(case preset
(1 (freverb :roomsize 0.2d0 :damp 0.0d0 :width 0.5d0 :level 0.9d0))
(2 (freverb :roomsize 0.4d0 :damp 0.2d0 :width 0.5d0 :level 0.8d0))
(3 (freverb :roomsize 0.6d0 :damp 0.4d0 :width 0.5d0 :level 0.7d0))
(4 (freverb :roomsize 0.8d0 :damp 0.7d0 :width 0.5d0 :level 0.6d0))
(5 (freverb :roomsize 0.8d0 :damp 1.0d0 :width 0.5d0 :level 0.5d0))
(6 (freverb :roomsize 0.6d0 :damp 0.1d0 :width 0.9d0 :level 1d0))
(t (format nil "choose a value between 1-6 dummy"))))
;;--------------------------------------------------
(defun fp (channel program &optional (bank 0 bank-set))
"short-hand to set the fluidsynth channel to program"
(declare (type integer channel program bank))
(when bank-set
(fluidsynth:bank-select *synth* channel bank))
(fluidsynth:program-change *synth* channel program))
(defun all-piano (&optional (program 0) (max-channels 32))
"set all the midi channels to PROGRAM"
(dotimes (chan max-channels)
(fluidsynth:program-change *synth* chan program)))
(defun try-sounds (time chan sf &optional (beats 8) (bank 0 bank-set))
"helper to iterate over programs on a soundfont to test sounds"
(print sf)
(when bank-set
(fluidsynth:bank-select *synth* chan bank))
(fluidsynth:program-change *synth* chan (mod sf 100))
(aat (+ time beats) #'try-sounds it chan (1+ sf) beats))
;;--------------------------------------------------
(defun fg (gain)
"short-hand to set the gain on fluidsynth"
(declare (type float gain))
(setf (fluidsynth:setting *settings* "synth.gain")
gain))
;;--------------------------------------------------
(defun fpan (channel pan)
(declare (type (integer 0 127) pan))
(fluidsynth:cc *synth* channel 10 pan))
(defun fvol (channel vol)
(declare (type (integer 0 127) vol))
(fluidsynth:cc *synth* channel 7 vol))
(defun all-pan (&optional (pan 64) (max-channels 32))
"Set PAN on all channels"
(declare (type (integer 0 127) pan))
(dotimes (channel max-channels)
(fluidsynth:cc *synth* channel 10 pan)))
(defun fstart (&optional (id 777))
"starts fluidsynth dsp! on given ID"
(fluid-test *synth* :id id))
;;--------------------------------------------------
(defun fload (path)
"Load given .sf2 soundfont"
(declare (type string path))
(assert (probe-file path))
(assert (string= "sf2" (last-elt (cl-ppcre:split #\. path))))
(fluidsynth:sfload *synth* path 1)
(fstart))
;;--------------------------------------------------
| 18,746 | Common Lisp | .lisp | 432 | 36.886574 | 119 | 0.600405 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 9a037f54d5a83d9a5f86a1b8888e1846b318027e0184506a90143899b220e0c8 | 9,045 | [
-1
] |
9,046 | leipzig.lisp | azimut_shiny/lib/leipzig.lisp | (in-package :shiny)
(defn phrase
"Translates a sequence of durations and pitches into a melody.
- nil pitches signify rests,
- vectors represent clusters
- and maps represent chords.
Vector durations represent repeated notes.
e.g. (phrase [1/2 1/2 3/2 3/2] [0 1 nil 4])
(phrase [1 1 2] [4 3 [0 2]])
(phrase [1 [1 2]] [4 3])
(phrase (repeat 4) (map #(-> triad (root %))) [0 3 4 3])"
([durations pitches velocities]
(let [wrap (fn [x] (if (sequential? x) x [x]))
counts (map (comp count wrap) durations)
normalised-pitches (mapcat repeat counts pitches)
normalised-durations (mapcat wrap durations)
times (reductions + 0 normalised-durations)]
(mapcat utter normalised-pitches times normalised-durations velocities)))
([durations pitches]
(->> (phrase durations pitches (repeat nil))
(map #(dissoc % :velocity)))))
(defn utter [object time duration velocity]
(cond
(number? object) [{:pitch object :time time :duration duration :velocity velocity}]
(sequential? object) (mapcat #(utter % time duration velocity) object)
(map? object) (utter (-> object vals sort) time duration velocity)
(nil? object) [{:time time :duration duration}]))
(def voiceX
(->>
(phrase (cycle [3 1/2 1/2]) [[0 4] 5 7 [0 4] 5 7 9 8 7 7 nil nil])
(then (phrase (cycle [3 1/2 1/2]) [[0 4] 5 7 [0 4] 5 4 [0 2] 1 0 0 nil nil]))
(where :pitch scale/raise)
(all :part :voice)))
(defun if-applicable (applies-p f)
(lambda (x) (if (funcall applies-p x) (funcall f x) x)))
(defun wherever (applies-p k f notes)
"Applies f to the k key of each note wherever condition? returns true.
e.g. (->> notes (wherever (comp not :part), :part (is :piano))"
(mapcar (if-applicable applies-p (lambda (x) (update-in x (list k) f)))
notes))
(defun where (k f notes)
(wherever))
(defun after (wait notes)
(where ))
(defun then (later earlier)
(->> later
(a)))
(defstruct play-event
pitch
time
duration
velocity)
(defun utter (&optional (object nil object-p) time duration velocity)
(cond
((numberp object)
(list (make-play-event :pitch object :time time :duration duration :velocity velocity)))
((listp object) (mapcar (lambda (x) (utter x time duration velocity)) object))
;; (map?)
(object-p
(list (make-play-event :time time :duration duration)))))
(defun phrase (durations pitches velocities)
(labels ((wrap (x)
(if (listp x) x (list x))))
(let* ((counts (mapcar (lambda (x) (length (wrap x))) durations))
(normalised-pitches (mapcat #'repeat counts pitches))
(normalised-durations (mapcat #'wrap durations))
(times (reductions #'+ normalised-durations)))
(mapcat #'utter normalised-pitches times normalised-durations velocities))))
| 2,846 | Common Lisp | .lisp | 68 | 37.279412 | 93 | 0.653054 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 16069d7c210d644195a7b68c80cb5d25dfd8115926b7417a9a5859b8ac1feb07 | 9,046 | [
-1
] |
9,047 | morse.lisp | azimut_shiny/lib/morse.lisp | (in-package #:shiny)
(defun morse-to-times (morse-string)
"(let ((pat (make-cycle
(morse-to-times (cl-morse:string->morse \"race\")))))
(defun f (time)
(destructuring-bind (p r) (next pat)
(when p (p time 60 40 (* .2 p) 5))
(aat (+ time #[(* .2 r) b]) #'f it))))"
(declare (type string morse-string))
(loop :for char :across morse-string :collect
(eswitch (char :test #'char=)
(#\. '(1 2))
(#\- '(3 6))
(#\ '(NIL 6)))))
| 496 | Common Lisp | .lisp | 14 | 29.357143 | 65 | 0.513514 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | be48ed28c9043e8d856d3f7bcce60a3acbd713f2dbb3518d9241f626b19ddacd | 9,047 | [
-1
] |
9,048 | aubio.lisp | azimut_shiny/lib/aubio.lisp | (in-package :shiny)
;; ## Using with incudine
;; Most straightforward usage I can think of is having aubio read an incudine buffer. Just have aubio and incudine use the same type for samples. And do something like:
;; ```
;; (defun test-onset (source-buffer)
;; "returns a list of the seconds where a set is found"
;; (declare (incudine:buffer source-buffer))
;; (let* ((buffer-frames (buffer-frames source-buffer))
;; (sample-rate (round (buffer-sample-rate source-buffer)))
;; (slices (loop :for slice :from 0 :by 512 :to buffer-frames
;; :collect slice))
;; (sets '())
;; (frames '())
;; (total-seconds (coerce (/ buffer-frames sample-rate) 'double-float)))
;; (assert (= 44100 sample-rate))
;; (aubio:with-onset (onset :sample-rate sample-rate)
;; (aubio:with-fvec (out-fvec 1)
;; (cffi:with-foreign-object (fvec '(:pointer (:struct fvec_t)))
;; (cffi:with-foreign-slots ((data length) fvec (:struct fvec_t))
;; (setf length 512)
;; (loop
;; :for slice :in slices :do
;; (setf data (cffi:inc-pointer (buffer-data source-buffer)
;; (* 8 2 slice)))
;; ;; Perform onset calculation
;; (sb-int:with-float-traps-masked (:divide-by-zero)
;; (aubio:aubio_onset_do onset fvec out-fvec))
;; ;; Retrieve result
;; (let ((onset-new-peak (aubio:fvec_get_sample out-fvec 0)))
;; (when (> onset-new-peak 0)
;; (let ((set (aubio:aubio_onset_get_last_s onset)))
;; (push set sets)
;; (push (round (* set sample-rate)) frames)))))
;; (push total-seconds sets)
;; (push buffer-frames frames)
;; (values (reverse sets) (reverse frames))))))))
;; ```
;; Only works when aubio is compiled to use double for samples
;;(ql:quickload :aubio/double)
;; Define aubio fvec_t struct to hack a new one using Incudine's buffers
(cffi:defcstruct fvec_t
(length :unsigned-int)
(data :pointer))
(defun test-onset (source-buffer)
"returns a 2 VALUES lists of the seconds where a set is found and
the buffer frame where it happened"
(declare (incudine:buffer source-buffer))
(let* ((buffer-frames (buffer-frames source-buffer))
(sample-rate (round (buffer-sample-rate source-buffer)))
(slices (loop :for slice :from 0 :by 512 :to buffer-frames
:collect slice))
(sets '())
(frames '())
(total-seconds (coerce (/ buffer-frames sample-rate) 'double-float)))
(assert (= 44100 sample-rate))
(aubio:with-onset (onset :sample-rate sample-rate)
(aubio:with-fvec (out-fvec 1)
(cffi:with-foreign-object
(fvec '(:pointer (:struct fvec_t)))
(cffi:with-foreign-slots
((data length) fvec (:struct fvec_t))
(setf length 512)
(loop
:for slice :in slices :do
(setf data (cffi:inc-pointer (buffer-data source-buffer)
(* 8 2 slice)))
;; Perform onset calculation
(sb-int:with-float-traps-masked (:divide-by-zero)
(aubio:aubio_onset_do onset fvec out-fvec))
;; Retrieve result
(let ((onset-new-peak (aubio:fvec_get_sample out-fvec 0)))
(when (> onset-new-peak 0)
(let ((set (aubio:aubio_onset_get_last_s onset)))
(push set sets)
(push (round (* set sample-rate)) frames)))))
(push total-seconds sets)
(push buffer-frames frames)
(values (reverse sets) (reverse frames))))))))
(defun test-beats (source-buffer)
"returns a list of the seconds where a set is found"
(declare (incudine:buffer source-buffer))
(let* ((buffer-frames (buffer-frames source-buffer))
(n-channels (buffer-channels source-buffer))
(sample-rate (buffer-sample-rate source-buffer))
(slices (loop :for slice :from 0 :by 512 :to buffer-frames
:collect slice))
(total-seconds (/ buffer-frames sample-rate))
(sets '())
(frames '()))
(aubio::with-tempo (tempo :sample-rate sample-rate)
(aubio:with-fvec (out-fvec 1)
(cffi:with-foreign-object (fvec '(:pointer (:struct fvec_t)))
(cffi:with-foreign-slots ((data length) fvec (:struct fvec_t))
(setf length 512)
(loop
:for slice :in slices :do
(setf data (cffi:inc-pointer (buffer-data source-buffer)
(* 8 n-channels slice)))
;; Perform onset calculation
(sb-int:with-float-traps-masked (:divide-by-zero)
(aubio:aubio_tempo_do tempo fvec out-fvec))
;; Retrieve result
(let ((in-beat (aubio:fvec_get_sample out-fvec 0)))
(when (> in-beat 0)
(push (aubio:aubio_tempo_get_last_s tempo) sets)
(push (aubio:aubio_tempo_get_last tempo) frames))))
(push total-seconds sets)
(push (round (* sample-rate total-seconds)) frames)
(values (reverse sets) (reverse frames))))))))
(defun test-pitches (source-buffer)
"returns a list of the seconds where a set is found"
(declare (incudine:buffer source-buffer))
(let* ((buffer-frames (buffer-frames source-buffer))
(n-channels (buffer-channels source-buffer))
(sample-rate (buffer-sample-rate source-buffer))
(slices (loop :for slice :from 0 :by 512 :to buffer-frames
:collect slice))
(total-seconds (/ buffer-frames sample-rate))
(pitches '())
(confidences '()))
(aubio::with-pitch (pitch :sample-rate sample-rate :confidence .8)
(aubio:with-fvec (out-fvec 1)
(cffi:with-foreign-object (fvec '(:pointer (:struct fvec_t)))
(cffi:with-foreign-slots ((data length) fvec (:struct fvec_t))
(setf length 512)
(loop
:for slice :in slices
:with last-pitch = (sample 0)
:do
(setf data (cffi:inc-pointer (buffer-data source-buffer)
(* 8 n-channels slice)))
;; Perform pitch calculation
(sb-int:with-float-traps-masked (:divide-by-zero)
(aubio:aubio_pitch_do pitch fvec out-fvec))
;; Retrieve result
(let ((p (round (aubio:fvec_get_sample out-fvec 0)))
(confidence (aubio:aubio_pitch_get_confidence pitch)))
(when (and (not (= last-pitch p))
;;(> confidence .9)
)
(push confidence confidences)
(push p pitches))
(setf last-pitch p)))
(values (reverse pitches) (reverse confidences))))))))
;;--------------------------------------------------
(defun remove-sides (l &optional (n 1))
(declare (list l) (alexandria:non-negative-integer n))
(let ((len (length l)))
(subseq l (+ 0 n) (- len n))))
(defun get-sets (l &optional (slicer #'cddr))
"Takes list L of frames and groups them in pairs.
Examples:
(get-sets (nth-value 1 (test-onset ...)))
(get-sets (nth-value 1 (test-onset ...)) #'cdr)"
(declare (type list l) (type function slicer))
(assert (>= (length l) 4))
(let* ((sets (remove-sides l)) ;; remove non-real sets
(set-pairs
(loop :for (x y) :on sets :by slicer :collect
(list x y))))
;; Remove sets with NIL
(remove-if (lambda (x) (member NIL x)) set-pairs)))
(defun save-sets (buf &optional (slicer #'cddr))
"saves provided buffer OR buffer-name sets into *BUFFER-SETS*
as an array"
(declare (function slicer))
(when (or (symbolp buf) (stringp buf))
(let ((b (gethash buf *buffers*)))
(when b
(setf buf b))))
(when-let* ((buffer-p (buffer-p buf))
(buffer-name (file-namestring (buffer-file buf)))
(sets (get-sets
(remove-sides
(nth-value 1 (test-onset buf)))
slicer))
(lsets (length sets))
(sets-array (make-array (list lsets 2) :initial-contents sets)))
(setf (gethash buffer-name *buffer-sets*) sets-array)))
(defun save-beats (buf &optional (slicer #'cddr))
"saves provided buffer OR buffer-name sets into *BUFFER-SETS*
as an array"
(declare (function slicer))
(when (or (symbolp buf) (stringp buf))
(let ((b (gethash buf *buffers*)))
(when b
(setf buf b))))
(when-let* ((buffer-p (buffer-p buf))
(buffer-name (file-namestring (buffer-file buf)))
(sets (get-sets
(remove-sides
(nth-value 1 (test-beats buf)))
slicer))
(lsets (length sets))
(sets-array (make-array (list lsets 2) :initial-contents sets)))
(setf (gethash buffer-name *buffer-sets*) sets-array)))
(defun get-longest-set (l)
(let* ((sets (remove-sides l))
(sec1 (first-elt sets))
(sec2 (last-elt sets)))
(mapcar (lambda (x) (round (* x 44100)))
(list sec1 sec2))))
;;--------------------------------------------------
(defun play-n-set (buffer sets n)
(declare (incudine:buffer buffer)
(list sets)
(integer n))
(assert (< n (length sets)))
(let* ((set (nth n sets))
(frame-start (first set))
(frame-end (lastcar set)))
(play-lsample-f
buffer
:id 100
:dur (/ (- frame-end frame-start) 44100)
:amp .01
:start-pos frame-start
:loopstart frame-start
:loopend frame-end)))
(defun play-set (buffer frame-start frame-end)
(declare (incudine:buffer buffer))
(play-lsample
buffer
:id 100
:amp .01
:start-pos frame-start
:loopend frame-end))
(defun slice-buffer (source-buffer start-frame end-frame)
"creates a new buffer, with frames from SOURCE-BUFFER,
between START-FRAME and END-FRAME, destroys SOURCE-BUFFER"
(declare (incudine:buffer source-buffer)
(alexandria:non-negative-integer start-frame end-frame))
(assert (> end-frame start-frame))
(let* ((sample-rate (buffer-sample-rate source-buffer))
(channels (buffer-channels source-buffer))
(frames (- end-frame start-frame))
(dest-buffer (make-buffer frames
:channels channels
:sample-rate sample-rate)))
(incudine.external:foreign-copy
(buffer-data dest-buffer)
(cffi:inc-pointer (buffer-data source-buffer) (* start-frame 8 channels))
(* channels 8 frames))
(incudine:free source-buffer)
dest-buffer))
(defun in-times (l f)
(declare (function f) (list l))
(mapcar (lambda (x) (at (+ (now) #[x b])
f))
l))
| 11,180 | Common Lisp | .lisp | 250 | 35.816 | 168 | 0.560169 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 4d1001899a46a07876f829a394a7338288ab0db929fa764778ce880624d5739d | 9,048 | [
-1
] |
9,049 | lv2.lisp | azimut_shiny/lib/lv2.lisp | (in-package #:shiny)
(dsp! swipe-dsp-up ((plugin (or null vug-foreign:plugin-instance))
(port-index fixnum)
dur
(max single-float)
(min single-float))
(:defaults NIL 45 1 1 0)
(with-samples ((e (envelope
(make-envelope `(,max ,min ,max) '(.5 .5))
1 dur #'stop)))
(foreach-frame
(setf (f32-ref (vug-foreign:plugin-port-pointer plugin port-index))
(coerce e 'single-float)))))
(dsp! swipe-dsp-down ((plugin (or null vug-foreign:plugin-instance))
(port-index fixnum)
dur
(max single-float)
(min single-float))
(:defaults NIL 45 1 1 0)
(with-samples ((e (envelope
(make-envelope `(,max ,min ,max) '(.5 .5))
1 dur #'stop)))
(foreach-frame
(setf (f32-ref (vug-foreign:plugin-port-pointer plugin port-index))
(coerce e 'single-float)))))
;;--------------------------------------------------
(dsp! swipe-dsp-sin ((plugin (or null vug-foreign:plugin-instance))
(port-index fixnum)
dur)
(:defaults NIL 45 1)
(with-samples ((e (envelope
(make-envelope '(0 1 0) '(.4 .6))
1 dur #'stop)))
(foreach-frame
(setf (f32-ref (vug-foreign:plugin-port-pointer plugin port-index))
(coerce (+ .5 (* .5 (sine 440 e))) 'single-float)))))
;;--------------------------------------------------
(defun lv2-note (time plugin keynum velocity duration)
(declare (type vug-foreign:plugin-instance plugin)
(type double-float time)
(type fixnum keynum velocity))
(rt-eval ()
(at time #'lv2:write-event plugin (lv2:midi-message #x90 keynum velocity))
(at (+ time (calc-beats duration))
(lambda (k) (lv2:write-event plugin (lv2:midi-message #x80 k 0)))
keynum))
keynum)
(defun lv2-arp (time plugin keynum velocity duration)
(declare (type vug-foreign:plugin-instance plugin)
(type double-float time)
(type fixnum velocity)
(type list keynum))
(let* ((lnotes (length keynum))
(offsets (loop :for i :from 0 :by duration :collect i :repeat lnotes)))
(mapcar (lambda (n o) (note-test (+ time (calc-beats o)) plugin n velocity duration))
keynum
offsets)))
(defun lv2-control (plugin port-index value)
(declare (type vug-foreign:plugin-instance plugin)
(type fixnum port-index))
;; Change the port value in rt-thread.
(rt-eval ()
(setf (f32-ref (vug-foreign:plugin-port-pointer plugin port-index))
(coerce value 'single-float)))
value)
| 2,771 | Common Lisp | .lisp | 65 | 32.753846 | 89 | 0.547002 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 2b19396239a6cba4360c4f1e46b5fed853fb3268028bcb5258657a49c7903cd7 | 9,049 | [
-1
] |
9,050 | extempore.lisp | azimut_shiny/lib/extempore.lisp | (in-package :shiny)
;;;
;; Helpers
;;;
(defvar TWOPI 6.283185)
(defun filter (fn 1st)
(let ((ace nil))
(dolist (x 1st)
(let ((val (funcall fn x)))
(if val (push val ace))))
(nreverse ace)))
(defun myrange (max &key (min 0) (step 1))
(loop for n from min below max by step
collect n))
(defun remove-first (obj lst)
(if (member obj lst)
(labels ((f (new lstb)
(if (equal (car lstb) obj)
(append new (cdr lstb))
(f (append new (list (car lstb))) (cdr lstb)))))
(f '() lst))
lst))
(defvar *phrygian* '(0 1 3 5 7 8 10))
; Define basic diatonic major
(defvar *diatonic-major*
'((i . (0 . ^))
(i6 . (0 . ^6))
(i64 . (0 . ^64))
(i7 . (0 . ^7))
(i- . (0 . -))
(i-7 . (0 . -7))
(n . (1 . ^)) ; neopolitan
(n6 . (1 . ^6)) ; neopolitan
(ii . (2 . -))
(ii6 . (2 . -6))
(ii7 . (2 . -7))
(ii9 . (2 . -9))
(ii^ . (2 . ^))
(ii^7 . (2 . ^7))
(iii . (4 . -))
(iii6 . (4 . -6))
(iii7 . (4 . -7))
(iii^ . (4 . ^))
(iii^7 . (4 . ^7))
(iv . (5 . ^))
(iv6 . (5 . ^6))
(iv7 . (5 . ^7))
(iv- . (5 . -))
(iv-7 . (5 . -7))
(v . (7 . ^))
(v6 . (7 . ^6))
(v7 . (7 . 7))
(v- . (7 . -))
(v-7 . (7 . -7))
(b6 . (8 . ^))
(vi . (9 . -))
(vi6 . (9 . -6))
(vi7 . (9 . -7))
(vi^ . (9 . ^))
(vi^7 . (9 . ^7))
(b7 . (10 . ^))
(viio . (11 . o))
(viio7 . (11 . o7))
(vii . (11 . o))
(vii7 . (11 . -7b5))
))
;; Define basic diatonic minor
(defvar *diatonic-minor*
'((i . (0 . -))
(i6 . (0 . -6))
(i64 . (0 . -64))
(i7 . (0 . -7))
(i^ . (0 . ^))
(i^6 . (0 . ^6))
(i^64 . (0 . ^64))
(i^7 . (0 . ^7))
(n . (1 . ^)) ; neopolitan
(n6 . (1 . ^6)) ; neopolitan
(ii . (2 . o))
(ii6 . (2 . o6))
(ii7 . (2 . o7))
(ii- . (2 . -))
(ii-6 . (2 . -6))
(ii-7 . (2 . -7))
(ii^ . (2 . ^))
(ii^7 . (2 . ^7))
(iii . (3 . ^))
(iii6 . (3 . ^6))
(iii7 . (3 . ^7))
(iii- . (3 . -))
(iii-6 . (3 . -6))
(iii-7 . (3 . -7))
(iv . (5 . -))
(iv6 . (5 . -6))
(iv7 . (5 . -7))
(iv^ . (5 . ^))
(iv^6 . (5 . ^6))
(iv^7 . (5 . ^7))
(v . (7 . ^))
(v^ . (7 . ^))
(v6 . (7 . ^6))
(v7 . (7 . 7))
(v- . (7 . -))
(v-6 . (7 . -6))
(v-6 . (7 . -6))
(v-7 . (7 . -))
(vi . (8 . ^))
(vi6 . (8 . ^6))
(vi7 . (8 . ^7))
(vi- . (8 . -))
(vi-6 . (8 . -6))
(vi-7 . (8 . -7))
(vii . (10 . ^))
(vii6 . (10 . ^6))
(vii7 . (10 . ^7))
(viio . (11 . o)) ;raised 7 (dim)
(viio6 . (11 . o6)) ;raised 7 (dim)
(viio7 . (11 . o7)) ; raised 7 (dim)
))
; Define basic chord symbols
(defvar *chord-syms*
'((^ . (0 4 7))
(^sus . (0 5 7))
(^6 . (4 7 0))
(^64 . (7 0 4))
(^7 . (0 4 7 11))
(^65 . (4 7 11 0))
(^43 . (7 11 0 4))
(^42 . (11 0 4 7))
(^2 . (11 0 4 7))
(^7#4 . (0 4 7 11 6))
(^9 . (0 4 7 11 2))
(7 . (0 4 7 10))
(9 . (0 4 7 10 2))
(65 . (4 7 10 0))
(43 . (7 10 0 4))
(2 . (10 0 4 7))
(42 . (10 0 4 7))
(- . (0 3 7))
(-sus . (0 5 7))
(-6 . (3 7 0))
(-64 . (7 0 3))
(-7 . (0 3 7 10))
(-65 . (3 7 10 0))
(-43 . (7 10 0 3))
(-42 . (10 0 3 7))
(-2 . (10 0 3 7))
(-9 . (0 3 7 10 2))
(o . (0 3 6))
(o6 . (3 6 0))
(o64 . (6 0 3))
(o7 . (0 3 6 8))
(o65 . (3 6 8 0))
(o43 . (6 8 0 3))
(o42 . (8 0 3 6))
(o2 . (8 0 3 6))
(-7b5 . (0 3 6 9))))
;; various scales defined as pc sets
(defvar *scales*
'((pentatonic . (2 2 3 2))
(ryukyu . (4 1 2 4))
(wholetone . (2 2 2 2 2))
(chromatic . (1 1 1 1 1 1 1 1 1 1 1))
(octatonic . (2 1 2 1 2 1 2))
(messiaen1 . (2 2 2 2 2))
(messiaen2 . (2 1 2 1 2 1 2))
(messiaen3 . (2 1 1 2 1 1 2 1))
(messiaen4 . (1 1 3 1 1 1 3))
(messiaen5 . (1 4 1 1 4))
(messiaen6 . (2 2 1 1 2 2 1))
(messiaen7 . (1 1 1 2 1 1 1 1 2))
(harmonic . (2 1 2 2 1 3))
(ionian . (2 2 1 2 2 2))
(major . (2 2 1 2 2 2))
(dorian . (2 1 2 2 2 1))
(phrygian . (1 2 2 2 1 2))
(lydian . (2 2 2 1 2 2))
(lydian-dominant . (2 2 2 1 2 1))
(lydian-mixolydian . (2 1 2 1 2 1 2))
(mixolydian . (2 2 1 2 2 1))
(aeolian . (2 1 2 2 1 2))
(minor . (2 1 2 2 1 2))
(locrian . (1 2 2 1 2 2))
(bartok . (2 2 1 2 1 2))))
;; returns a scale based on a chord (standard jazz translations)
(defvar *pc-chord->scale*
'((i . (0 . ionian))
(i7 . (0 . ionian))
(ii . (2 . dorian))
(ii7 . (2 . dorian))
(ii9 . (2 . dorian))
(iii . (4 . phrygian))
(iii7 . (4 . phrygian))
(iv . (5 . lydian))
(iv7 . (5 . lydian))
(v . (7 . mixolydian))
(v7 . (7 . mixolydian))
(vi . (9 . aeolian))
(vi7 . (9 . aeolian))
(vii . (11 . locrian))
(vii7 . (11 . locrian))))
;; General MIDI drum note numbers
(defvar *gm-kick* 35)
(defvar *gm-kick-2* 36)
(defvar *gm-side-stick* 37)
(defvar *gm-snare* 38)
(defvar *gm-hand-clap* 39)
(defvar *gm-snare-2* 40)
(defvar *gm-low-floor-tom* 41)
(defvar *gm-closed-hi-hat* 42)
(defvar *gm-hi-floor-tom* 43)
(defvar *gm-pedal-hi-hat* 44)
(defvar *gm-low-tom* 45)
(defvar *gm-open-hi-hat* 46)
(defvar *gm-low-mid-tom* 47)
(defvar *gm-hi-mid-tom* 48)
(defvar *gm-crash* 49)
(defvar *gm-hi-tom* 50)
(defvar *gm-ride* 51)
(defvar *gm-chinese* 52)
(defvar *gm-ride-bell* 53)
(defvar *gm-tambourine* 54)
(defvar *gm-splash* 55)
(defvar *gm-cowbell* 56)
(defvar *gm-crash-2* 57)
(defvar *gm-vibraslap* 58)
(defvar *gm-ride-2* 59)
(defvar *gm-hi-bongo* 60)
(defvar *gm-low-bongo* 61)
(defvar *gm-mute-hi-conga* 62)
(defvar *gm-hi-conga* 63)
(defvar *gm-low-conga* 64)
(defvar *gm-hi-timbale* 65)
(defvar *gm-low-timbale* 66)
(defvar *gm-hi-agogo* 67)
(defvar *gm-low-agogo* 68)
(defvar *gm-cabasa* 69)
(defvar *gm-maracas* 70)
(defvar *gm-short-whistle* 71)
(defvar *gm-long-whistle* 72)
(defvar *gm-short-guiro* 73)
(defvar *gm-long-guiro* 74)
(defvar *gm-claves* 75)
(defvar *gm-hi-wood-block* 76)
(defvar *gm-low-wood-block* 77)
(defvar *gm-mute-cuica* 78)
(defvar *gm-open-cuica* 79)
(defvar *gm-mute-triangle* 80)
(defvar *gm-open-triangle* 81)
(defvar *gm-mute-surdo* 86)
(defvar *gm-open-surdo* 87)
(defun pc-random (lower upper pc)
"select random pitch from pitch class
bounded by lower and upper (inclusive lower exclusive upper)
arg 1: lower bound (inclusive)
arg 2: upper bound (exclusive)
arg 3: pitch class
returns -1 if no valid pitch is possible"
(if (not pc)
-1
(let ((choices (filter (lambda (x) (if (ispitch x pc) x))
(myrange upper :min lower))))
(if (not choices)
-1
(random-list choices)))))
(defun pc-chord (root type)
"returns a chord given a root and type
see *pc:chord-syms* for currently available types
e.g. (pc:chord 0 '^7) => '(0 4 7 11)"
(let ((chord (assoc type *chord-syms*)))
(if chord
(labels ((f (l newlst)
(if (not l)
(reverse newlst)
(f (cdr l)
(cons (mod (+ (car l) root) 12)
newlst)))))
(f (cdr chord) '() )))))
(defun pc-chord-options (root maj-min pc)
"returns chord options for root in maj-min key of pc
e.g. (pc:chord-options 0 '^ (pc:scale 0 'ionian))
=> ((0 4 7) (0 4 7 11) (0 5 7) (0 4 7 11 2) (0 4 7 11 6))"
(let ((major7 '(^ ^7 ^sus ^9 ^7#4))
(dom7 '(^ 7 ^sus 9))
(minor7 '(- -7 -sus -9))
(dim7 '(o -7b5 o7))
(degree (pc-degree root pc)))
(mapcar (lambda (sym) (pc-chord root sym))
(if (equal maj-min '^)
(case degree
((-1) '())
((1 4) major7)
((5) dom7)
((2 3 6) minor7)
((7) dim7))
(case degree
((-1) '())
((1 4 6) minor7)
((3) major7)
((5) (append minor7 dom7))
((2) dim7)
((7) (append dom7 dim7)))))))
(defun make-chord-fixed (fix-point number pc &rest args)
"make a chord that is fixed at either the 'top or the 'bottom
where fixed is as close as the chord allows to fix-point
defaults to bottom
(pc:make-chord-fixed 60 3 '(0 3 7)) => (60 63 67)
(pc:make-chord-fixed 60 3 '(0 3 7) 'top) => (51 55 60)"
(if (< number 1)
'()
(let* ((fixd (mod fix-point 12))
(place (if (null args) 'bottom (car args)))
(bass (- fix-point fixd))
(chord (if (eql place 'bottom) pc (reverse pc)))
(v (mapcar (lambda (pc) (abs (- fixd pc))) chord))
(minim (apply #'min v))
(start (- (length v) (length (member minim v)))))
(labels ((ff (i new-lst bb lst)
(if (< i number)
(ff (+ i 1)
(cons (+ bb (car lst)) new-lst)
(if (null (cdr lst))
(funcall (if (null args) '+ '-)
bb
12)
bb)
(if (null (cdr lst))
chord
(cdr lst)))
(if (eql place 'bottom)
(sort (reverse new-lst) #'<)
(sort new-lst #'<)))))
(ff 0 '() bass (nthcdr start chord))))))
(defun pc-relative (pitch i pc)
"select pitch from pitch class relative to a given pitch
1st: bass pitch
2nd: pc relationship to bass pitch (max is abs 7)
3rd: pitch class
example:
(pc:relative 64 -2 '(0 2 4 5 7 9 11)) => 60
(pc:relative 69 3 '(0 2 4 5 7 9 11)) => 74"
(when (and (numberp pitch) (numberp i))
(setf i (round i))
(if (= i 0)
pitch
(let* ((inc (if (< i 0) '- '+)))
(labels ((f (p cnt)
(progn (if (ispitch p pc)
(setf cnt (funcall inc cnt 1)))
(if (= cnt i)
p
(f (funcall inc p 1) cnt)))))
(f (funcall inc pitch 1) 0))))))
(defun pc-degree (value pc)
"Returns a scale degree of a given value (pitch) based on a pc"
(labels ((f (i lst)
(if (null lst)
-1
(if (= (car lst) (mod value 12))
i
(f (1+ i) (cdr lst))))))
(f 1 pc)))
(defun pc-diatonic (root maj-min degree)
"returns a chord following basic diatonic harmony rules
based on root (0 for C etc.) maj/min ('- or '^) and degree (i-vii)
ex: (pc:diatonic 0 '- 'i) => (0 3 7)"
(if (typep degree 'integer)
(setf degree (cdr (assoc degree '((0 . i) (1 . ii) (2 . ii)
(3 . iii) (4 . iii) (5 . iv)
(6 . iv) (7 . v) (8 . vi)
(9 . vi) (10 . vii) (11 . vii))))))
(let ((val (assoc degree (if (eq '^ maj-min)
*diatonic-major*
*diatonic-minor*))))
(pc-chord (mod (+ root (cadr val)) 12)
(cddr val))))
(defun cosr (centre amplitude period)
"- the first argument is the \"centre\" to oscillate around
- the second argument is the \"amplitude\" of the oscillation
- the third argument is the \"period\" of the oscillation.
Ex: (cosr 5 3 1/2)"
(declare (number centre amplitude period))
(let ((beat (float (/ (get-internal-real-time) 36000) 1f0)))
(+ centre
(* amplitude
(cos (* TWOPI
beat
period))))))
;;(cos (* TWOPI (now) period)))))
(defmacro rcosr (centre amplitude period)
`(round (cosr ,centre ,amplitude ,period)))
(defmacro qcosr (pc center amplitude period)
`(pc-quantize (cosr ,center ,amplitude ,period) ,pc))
(defun sinr (centre amplitude period)
(let ((beat (float (/ (get-internal-real-time) 36000) 1f0)))
(+ centre
(* amplitude
(sin (* TWOPI
beat
period))))))
(defmacro rsinr (centre amplitude period)
`(round (sinr ,centre ,amplitude ,period)))
(defmacro qsinr (pc centre amplitude period)
`(pc-quantize (sinr ,centre ,amplitude ,period) ,pc))
(defun tanr (centre period amplitude)
(let ((beat (float (/ (get-internal-real-time) 36000) 1f0)))
(+ centre
(* amplitude
(tan (* TWOPI
beat
period))))))
(defmacro rtanr (centre period amplitude)
`(round (tanr ,centre ,period ,amplitude)))
(defmacro qtanr (pc centre period amplitude)
`(pc-quantize (tanr ,centre ,period ,amplitude) ,pc))
(defun ispitch (pitch pc)
"A predicate for calculating if pitch is in pc
arg 1: pitch to check against pc
arg 2: pc to check pitch against
retuns true or false"
(if (member (mod pitch 12) pc) t))
(defun pc-quantize (pitch-in pc)
"Always selects a higher value before a lower value where distance is equal.
arg 1: pitch to quantize to pc
arg 2: pc to quantize pitch against
returns quantized pitch or #f if non available"
(labels ((f (inc pitch)
(cond ((ispitch (+ pitch inc) pc) (+ pitch inc))
((ispitch (- pitch inc) pc) (- pitch inc))
((< inc 7) (f (+ inc 1) pitch))
(t (print "Derp!") nil))))
(f 0 (round pitch-in))))
(defun pc-quantize-low (pitch-in pc)
"Always slelects a lower value before a higher value where distance is equal.
arg 1: pitch to quantize to pc
arg 2: pc to quantize pitch against
returns quntized pitch or #f if non available"
(labels ((f (inc pitch)
(cond ((ispitch (- pitch inc) pc) (- pitch inc))
((ispitch (+ pitch inc) pc) (+ pitch inc))
((< inc 7) (f (+ inc 1) pitch))
(t (print "Derp!") nil))))
(f 0 (round pitch-in))))
(defun pc-quantize-list (lst pc)
(mapcar (lambda (_) (pc-quantize _ pc))
lst))
(defun ivl-retrograde (args) (reverse args))
(defun ivl-invert (lst &rest args)
"invert list paying no attention to key"
(let ((pivot (if (null args)
(car lst)
(car args))))
(cons (car lst) (mapcar (lambda (_) (- pivot (- _ pivot)))
(cdr lst)))))
(defun ivl-transpose (val lst)
"transpose list paying no attention to key"
(mapcar (lambda (_) (+ _ val))
lst))
;; TODO ivl:expand/contract
(defun pc-invert (lst pc &rest args)
"invert the values of lst quantizing to pc"
(if (null args)
(pc-quantize-list (ivl-invert lst) pc)
(pc-quantize-list (ivl-invert lst (car args)) pc)))
(defun pc-transpose (val lst pc)
"transpose the values of lst quantizing to pc"
(pc-quantize-list (ivl-transpose val lst) pc))
;; TODO ivl:expand/contract
(defun pc-chord->scale (root type)
(scale (mod (+ (cadr (assoc type *pc-chord->scale*)) root) 12)
(cddr (assoc type *pc-chord->scale*))))
(defun scale (root type)
"scheme<7099> (pc:scale 0 'aeolian)
=> (0 2 3 5 7 8 10)
returns a scale type based on a given root"
(if (assoc type *scales*)
(labels ((f (l current newlst)
(if (not l)
(reverse (cons current newlst))
(f (cdr l)
(mod (+ current (car l)) 12)
(cons current newlst))
)))
(f (cdr (assoc type *scales*))
(mod root 12)
'()))
nil))
;;;
;; pc:make-chord
;;;
(defun make-chord (lower upper number pc)
"creates a list of "number" pitches between "lower" and "upper"
bounds from the given "pc". a division of the bounds
by the number of elements requested breaks down the selection into
equal ranges from which each pitch is selected.
make-chord attempts to select pitches of all degrees of the pc.
it is possible for elements of the returned chord to be -1 if no
possible pc is available for the given range.
non-deterministic (i.e. result can vary each time)
arg1: lower bound (inclusive)
arg2: upper bound (exclusive)
arg3: number of pitches in chord
arg4: pitch class
example: c7
(pc:make-chord 60 85 4 '(0 4 7 10)) => (60 70 76 79)"
(let ((chord '()))
(labels ((f (l u n p)
(if (< n 1)
(mapcar (lambda (x) (round x))
(sort (remove -1 chord) '<))
(let* ((range (- u l))
(gap (round (/ range n)))
(pitch (pc-random l (+ l gap) p)))
(if (< pitch 0)
(setf chord (cons (pc-random lower upper p)
chord))
(setf chord (cons pitch chord)))
(f (+ l gap)
u
(- n 1)
(if (> (length p) 1)
(remove (mod (car chord) 12) p)
pc))))))
(f (round lower) (round upper) number pc))))
;;;
;; From extempore - Scheme - instruments_ext-scm.xtm
;;;
;;
(defun note-name-to-midi-number (name)
"> (regex:matched \"F#1\" \"([abcdefgABCDEFG])([#b])?(-?[0-9])\") => (\"F#1\" \"F\" \"#\" \"1\")"
(let ((result (multiple-value-bind (a b) (cl-ppcre:scan-to-strings "([abcdefgABCDEFG])([#b])?(-?[0-9])" name)
(append (list a) (coerce b 'list)))))
(if (null result)
nil
(let ((offset (+ 12 (* (parse-integer (cadddr result)) 12)))
(pc (case (mod (- (mod (char-code (coerce (cadr result) 'character)) 16) 3) 7)
((0) 0) ((1) 2) ((2) 4) ((3) 5) ((4) 7) ((5) 9) ((6) 11) (otherwise 0))))
(+ offset pc
(cond ((string= (caddr result) "#") 1)
((string= (caddr result) "b") -1)
(t 0)))))))
(defun pc-from-steps (pitch steps pc)
"returns a pc-set based on:
- a list of steps
- a beginning pitch class
- and a pc-set"
(labels ((f (slst plst)
(if (null slst)
(reverse plst)
(f (cdr slst)
(cons (mod (pc-relative (car plst) (car slst) pc) 7)
plst)))))
(f steps (list pitch))))
(defun pc-distance (pitch pc)
"distance between pitch and pc"
(when (atom pc)
(setf pc (list pc)))
(let ((p (mod pitch 12)))
(car (sort (mapcar (lambda (class)
(let ((val (abs (- p class))))
(abs (if (< val (- 12 val)) val (- 12 val)))))
pc)
#'<))))
(defun pc-closest-pc (pitch pc)
"find the pc that is closest to given pitch
useful for finding next step for a pitch given a chord"
(cdar (sort (mapcar (lambda (class) (cons (pc-distance pitch class) class))
pc)
(lambda (a b) (< (car a) (car b))))))
(defun pc-closest-pitch (pc pitches)
(cdar (sort (mapcar (lambda (p) (cons (pc-distance p pc) p))
pitches)
(lambda (a b) (< (car a) (car b))))))
(defun pc-find-closest (plst pc)
"returns the pitch in plst that is closest to the pc set
if multiple pitches in plst ar the closes return the first"
(cdar (sort (mapcar (lambda (p) (cons (pc-distance p pc) p))
plst)
(lambda (a b) (if (< (car a) (car b)) T nil)))))
(defun pc-move-chord (chord pc)
"find shortest part movement from a chord to pc"
(labels ((f (pci chda chdb)
(when (null pci) (setf pci pc))
(if (null chda)
(sort chdb #'<)
(let* ((match (pc-find-closest chda pci))
(new-pitch (if (> (random 1.0) .5)
(pc-quantize-low match pci)
(pc-quantize match pci))))
(f (remove-first (mod new-pitch 12) pci)
(remove-first match chda)
(cons new-pitch chdb))))))
(f pc chord '())))
;;; ----------------------------
;; Extempore - Rhythm functions
;; -----------------------------
(defun make-metro (start-tempo &rest args)
"(define *metro* (make-metro 120))
creates a metronome object
metro is basically a linear function that returns
a time in absolute samples when given a time in beats.
metro is instantiated with a starting tempo.
you can call the metro with the following symbols
'get-time ; which is also the default
'get-beat
'get-tempo
'set-tempo
'get-cycle
'set-cycle
'pos
'dur"
(let* ((offset (if (null args) (round (now)) (caar args))) ; args
(cycle 4)
(mark offset)
(loffset 0.0)
(total-beats (if (null args) 0 (cdar args))) ; args
(cycle-beats total-beats)
(g-tempo (/ 60 start-tempo))
(beat-pos (lambda (x1 y1 x2 y2)
(let* ((m (if (= 0 (- x2 x1)) 0 (/ (- y2 y1) (- x2 x1))))
(c (- y1 (* m x1))))
(lambda (time)
(+ (* time m) c)))))
(beat-env (funcall beat-pos mark total-beats
(+ mark (* g-tempo *sample-rate*))
(+ total-beats 1)))
(samp-env (funcall beat-pos
total-beats
mark
(+ total-beats 1)
(+ mark (* g-tempo *sample-rate*)))))
(lambda (sym &rest args)
(cond ((numberp sym)
(+ (funcall samp-env sym) loffset))
((eq sym 'get-mark)
(cons mark total-beats))
((eq sym 'get-time)
(+ (funcall samp-env (car args)) loffset))
((eq sym 'get-cycle) cycle)
((eq sym 'get-cycle-mark) cycle-beats)
((eq sym 'set-cycle)
(setf cycle-beats (cadr args))
(setf cycle (car args)))
((eq sym 'pos)
(mod (- (car args) cycle-beats) cycle))
((eq sym 'beat-at-time)
(funcall beat-env (car args))) ;; FIXME
;; ((eq sym 'set-tempo)
;; (let ((time (if (null (cdr args)) (now) (cadr args))))
;; (if (or (null (cdr args))
;; (null (cddr args)))
;; (setf total-beats
;; (+ total-beats (/ (- time mark)
;; (* *sample-rate* g-tempo))))
;; (setf total-beats (caddr args)))
;; (setf g-tempo (/ 60 (car args)))
;; (setf mark time)
;; (setf samp-env (funcall beat-pos total-beats
;; mark
;; (+ total-beats 1)
;; (+ mark (* g-tempo *sample-rate*))))
;; (setf beat-env (funcall beat-pos mark
;; total-beats
;; (+ mark (* g-tempo *sample-rate*))
;; (+ total-beats 1)))
;; (car args)))
((eq sym 'get-tempo) (* (/ 1 g-tempo) 60))
((eq sym 'dur) (* *sample-rate* g-tempo (car args)))
((eq sym 'push) (setf loffset (+ loffset 256)))
((eq sym 'pull) (setf loffset (- loffset 256)))
((eq sym 'get-beat)
(let ((val (+ total-beats
(/ (- (round (now)) mark)
(* *sample-rate* g-tempo))))
(quantize (if (null args) 1.0 (car args))))
(+ val (- quantize (mod val quantize)))))
(t 'bad-method-name)))))
(defun make-metre (metre base)
"creates a meter where metre is a list of numerators
and base is a shared denominator (relative to impromptu beats. i.e. 1 = crotchet, 0.5 = eighth etc.)
e.g.
(define *metre* (make-metre '(2 3 2) 0.5)) = 2/8 3/8 2/8 rotating cycle.
then call meter with time and beat if beat matches time then #t else #f
e.g. give the above define
(*metre* 2.5 1.0) => #t because 0.0 = 1, 0.5 = 2, 1.0 = 1, 1.5 = 2, 2.0 = 3, 2.5 = 1, 3.0 = 2 and repeat."
(let ((metre-length (apply '+ metre)))
(lambda (time &rest beat)
(let ((b (print (do ((qtime (mod (/ time base) metre-length))
(lst metre (cdr lst))
(valuea (car metre) (+ valuea (cadr lst)))
(valueb 0 (+ valueb (car lst))))
((< qtime valuea)
(+ 1.0 (- qtime valueb)))))))
(if (null beat)
b
(if (= (car beat) b) t nil))))))
(defun make-metre (metre base)
(let ((metre-length (apply #'+ metre)))
(lambda (time &rest beat)
(let ((b (labels ((f (qtime lst valuea valueb)
(if (< qtime valuea)
(+ 1d0 (- qtime valueb))
(f qtime
(rest lst)
(+ valuea (second lst))
(+ valueb (first lst))))))
(f (mod (/ time base) metre-length)
metre
(first metre)
0))))
(if (null beat)
b
(if (= (first beat) b) ;; BEAT match!
t
nil))))))
(defun pc-melody-by-step (starting-pitch steps pc &rest args)
"generate a melody from a list of steps in a (pc) pitch class
(pc-melody-by-step 60 '(2 4 6) *phrygian*) => (60 63 70 80)"
(if (null steps)
(reverse (car args))
(if (null args)
(pc-melody-by-step starting-pitch steps pc (cons starting-pitch args))
(pc-melody-by-step (pc-relative starting-pitch (car steps) pc)
(cdr steps)
pc
(cons (pc-relative starting-pitch (car steps) pc)
(car args))))))
(defun ivl-melody-by-ivl (starting-pitch ivls &rest args)
"generate a melody from a list of intervals
(ivl-melody-by-ivl 60 '(2 4 6)) => (60 62 66 72)"
(if (null ivls)
(reverse (car args))
(if (null args)
(ivl-melody-by-ivl starting-pitch ivls (cons starting-pitch args))
(ivl-melody-by-ivl (+ starting-pitch (car ivls))
(cdr ivls)
(cons (+ starting-pitch (car ivls))
(car args))))))
;; extra - not on extempore
(defun make-chord-alberti (lower upper pc)
"creates 4 notes, from a 3 note chord sorted a'la alberti"
(let ((mychord (make-chord lower upper 3 pc))
(indexes '(0 2 1 2)))
(loop :for x :in indexes
:collect (nth x mychord))))
;; TODO: pc-relative
(defun make-chord-company (lower upper pc &optional (offset 0))
"creates 2 groups of notes, from a 4 notes chord
> (make-chord-company 60 80 '(0 1 3 5 7 8 10)) => ((61 67 72) 75)"
(let ((mychord (make-chord lower upper 4 pc)))
(list (subseq mychord 0 3)
(+ (nth 3 mychord) offset))))
;; https://github.com/DavidM1088/Composer
(defun make-chord-alternate (lower upper pc)
"write a sequence of bass note, chord, bass note, chord
> (make-chord-alternate 60 80 '(0 1 3 5 7 8 10)) =>
(53 (65 68 75) 60 (65 68 75))"
(let* ((mychord (make-chord lower upper 3 pc))
(bass-note (first mychord)))
(list (- bass-note 12) mychord
(+ 7 (- bass-note 12)) mychord)))
(defun make-chord-alternate1 (lower upper pc &optional (bass 12) (nr 3))
"write a sequence of bass note, chord, bass note, chord
> (make-chord-alternate1 60 80 '(0 1 3 5 7 8 10))
(51 (63 72 79) 51 (63 72 79))"
(let* ((mychord (make-chord lower upper nr pc))
(bass-note (- (first mychord) bass)))
(list bass-note mychord
bass-note mychord)))
(defun make-chord-daydreaming (lower upper pc)
"Daydreaming from radiohead type of chord
> (make-chord-daydreaming 60 70 (scale 0 'minor))
(67 60 65)"
(let ((c (make-chord lower upper 3 pc)))
(list (caddr c) (first c) (second c))))
;; --------------------------------------------------
(defun make-chord-waltz (lower upper pc &optional (bass 12))
"> (make-chord-waltz 60 80 '(0 1 3 5 7 8 10))
(48 (60 68 73) (60 68 73))"
(let* ((mychord (make-chord lower upper 3 pc))
(bass-note (first mychord)))
(list (- bass-note bass) mychord mychord)))
(defun make-chord-waltz1 (lower upper pc &optional (bass 12) (nr 3))
"> (make-chord-waltz1 60 80 '(0 1 3 5 7 8 10))
(48 (60 68 73))"
(let* ((mychord (make-chord lower upper nr pc))
(bass-note (first mychord)))
(list (- bass-note bass) mychord)))
(defun make-chord-5 (lower upper pc)
(let ((mychord (make-chord lower upper 5 pc)))
(list (first mychord) (subseq mychord 1 5))))
;; --------------------------------------------------
(defun make-chord-fade (lower upper pc
&optional (nr-notes 3) (direction 'u))
"> (make-chord-fade 60 80 '(0 1 3 5 7 8 10))
((60 70 75) (60 70) (75))"
(let ((mychord (make-chord lower upper nr-notes pc)))
(case direction
(u (loop :for c :from nr-notes :downto 1
:collect (subseq mychord 0 c)))
(d (loop :for c :from 0 :to (1- nr-notes)
:collect (subseq mychord c nr-notes))))))
(defun make-chord-appear (lower upper pc
&optional (nr-notes 3) (direction 'u))
(let ((mychord (make-chord lower upper nr-notes pc)))
(loop :for c :from 1 :upto nr-notes
:collect (subseq mychord 0 c))))
;; --------------------------------------------------
;; igorii/GeneticSonata
;; --------------------------------------------------
(defvar scale-triads
'((-13 . d) (-12 . ^) (-10 . m) (-8 . m) (-7 . ^) (-5 . ^) (-3 . m) (-1 . d)
(0 . ^) (2 . m) (4 . m) (5 . ^) (7 . ^) (9 . m) (11 . d) (12 . ^) (14 . m)))
(defun make-major-chord (root)
(list root (+ root 4) (+ root 7)))
(defun make-minor-chord (root)
(list root (+ root 3) (+ root 7)))
(defun make-augmented-chord (root)
(list root (+ root 4) (+ root 8)))
(defun make-diminished-chord (root)
(list root (+ root 3) (+ root 6)))
;; ??
(defun make-chord-sym (root)
(let ((r (cdr (assoc (- (+ root 12) 60) scale-triads))))
(case r
(^ (make-major-chord root))
(m (make-minor-chord root))
(a (make-augmented-chord root))
(d (make-diminished-chord root))
(t (format nil "wrong!")))))
| 31,527 | Common Lisp | .lisp | 830 | 29.404819 | 111 | 0.476254 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 85cd62d4c71eeda08826bec487118994d6689c3b1fee81920a156c54fca27f4a | 9,050 | [
-1
] |
9,051 | overtone.lisp | azimut_shiny/lib/overtone.lisp | (in-package #:shiny)
;; ----------- Overtone / Clojure
;; http://www.appservgrid.com/hyper/hyp/lisp#take
;; SOMECEPL> (take 2 '(0 1 2 3 4 5))
;; (0 1)
;; (defun take (n l)
;; (cond ((< n 0) (error "index negative"))
;; ((= n 0) ())
;; ((null l) (error "index too large"))
;; (t (cons (car l) (take (- n 1) (cdr l))))))
;; https://github.com/tororo060608/danmachi/blob/master/src/util.lisp
(defun take-nth (n seq)
(do ((i 0 (+ i n))
(res nil (cons (elt seq i) res))
(len (length seq)))
((<= len i) (nreverse res))))
;; http://www.appservgrid.com/hyper/hyp/lisp#take
;; SOMECEPL> (take 2 '(0 1 2 3 4 5))
;; (0 1)
(defun take (n l)
(cond ((< n 0) (error "index negative"))
((= n 0) ())
((null l) (error "index too large"))
(t (cons (car l) (take (- n 1) (cdr l))))))
;; Taking a similar function to cycle
;; NOTE: use make-list
(defun repeat (n l &optional (nl '()))
(when (not (listp l))
(setf l (list l)))
(if (zerop n)
nl
(repeat (- n 1)
(rotate l 1)
(if (not nl)
(list (first l))
(append nl (list (first l)))))))
(defun comp (a b)
(lambda (&rest args)
(funcall a (apply b args))))
(defun mapcat (function &rest lists)
(apply #'concatenate 'list (apply #'mapcar function lists)))
(defun reductions (function sequence &rest args
&key key from-end (start 0) end initial-value)
(declare (ignore key from-end start end initial-value))
"Return a list of intermediate values from reducing SEQUENCE with FUNCTION."
(let* ((reductions (list))
(result (apply #'reduce
(lambda (&rest arguments)
(let ((result (apply function arguments)))
(push result reductions)
result))
sequence
args)))
(values (or (nreverse reductions)
(list result))
result)))
;;;
;; pitch.clj
;;;
(defun to-keyword (s)
(cond ((stringp s) (intern (string-upcase s) "KEYWORD"))
((keywordp s) s)))
(defun name (n)
(cond ((keywordp n) (symbol-name n))
((stringp n) n)))
(defun octave-note (octave interval)
"Convert an octave and interval to a midi note."
(+ (* octave 12) interval 12))
(defvar +notes+ (alexandria:alist-hash-table
'((:C . 0) (:B# . 0)
(:C# . 1) (:DB . 1)
(:D . 2)
(:D# . 3) (:EB . 3)
(:E . 4)
(:E# . 5) (:F . 5)
(:F# . 6) (:GB . 6)
(:G . 7)
(:G# . 8) (:AB . 8)
(:A . 9)
(:A# . 10) (:BB . 10)
(:B . 11) (:CB . 11))))
(defun notes (n)
(if (keywordp n)
(gethash n +notes+)
(error "not a keyword")))
(defvar *reverse-notes*
(alexandria:alist-hash-table
'((0 . :C) (1 . :C#)
(2 . :D) (3 . :Eb)
(4 . :E) (5 . :F)
(6 . :F#) (7 . :F#)
(8 . :Ab) (9 . :A)
(10 . :Bb) (11 . :B))))
(defun reverse-notes (n)
(if (and (< n 12) (>= n 0))
(gethash n *reverse-notes*)
(error "out of range")))
(defvar *midi-note-re-str* "([a-gA-G][#bB]?)([-0-9]*)")
(defvar *only-midi-note-re-str*
(concatenate 'string "\\A" *midi-note-re-str* "\\Z"))
(defun midi-string-matcher (mk)
"Determines whether a midi keyword is valid or not. If valid,
returns a regexp match object
#(\"C\" \"4\")"
(multiple-value-bind (_ m) (cl-ppcre:scan-to-strings *only-midi-note-re-str*
(name mk))
(declare (ignore _))
m))
(defun validate-midi-string! (mk)
(let ((matches (midi-string-matcher mk)))
(unless matches
(error "invalid midi-string"))
(let ((octave (setf (aref matches 1)
(if (str:emptyp (aref matches 1))
"4"
(aref matches 1)))))
(when (< (parse-integer octave) -1)
(error "invalid midi-string too low")))
matches))
(defun canonical-pitch-class-name (pc)
"Returns the canonical version of the specified pitch class pc."
(reverse-notes (notes (to-keyword pc))))
(defun note-info (midi-string)
"Takes a string representing a midi note such as C4 and returns a map
of note info"
(let* ((matches (validate-midi-string! midi-string))
(pitch-class (aref matches 0))
(octave (aref matches 1))
(pitch-class (canonical-pitch-class-name pitch-class))
(octave (parse-integer octave))
(interval (notes (to-keyword pitch-class)))
(midi-note (octave-note octave interval)))
(alexandria:alist-hash-table `((:pitch-class . ,pitch-class)
(:octave . ,octave)
(:interval . ,interval)
(:midi-note . ,midi-note)))))
(defun note (n)
"Resolves note to MIDI number format. Resolves upper and lower-case
keywords and strings in MIDI note format. If given an integer or
nil, returns them unmodified. All other inputs will raise an
exception.
Usage examples:
(note \"C4\") ;=> 60
(note \"C#4\") ;=> 61
(note \"eb2\") ;=> 39
(note :F#7) ;=> 102
(note :db5) ;=> 73
(note 60) ;=> 60
(note nil) ;=> nil"
(cond ((null n) nil)
((integerp n) (if (>= n 0)
n
(error "Value out of range.")))
((keywordp n) (note (symbol-name n)))
((symbolp n) (note (symbol-name n)))
((stringp n) (gethash :midi-note (note-info n)))
(t (error "Bad argument."))))
;; NOTE: hack in
(defparameter +scale+
(flet ((rotate (scale-sequence offset)
(take (length scale-sequence)
(nthcdr offset (append scale-sequence scale-sequence)))))
(let* ((ionian-sequence '(2 2 1 2 2 2 1))
(hex-sequence '(2 2 1 2 2 3))
(pentatonic-sequence '(3 2 2 3 2))
(melodic-minor '(2 1 2 2 2 2 1)))
`((:diatonic . ,ionian-sequence)
(:ionian . ,(rotate ionian-sequence 0))
(:major . ,(rotate ionian-sequence 0))
(:dorian . ,(rotate ionian-sequence 1))
(:phrygian . ,(rotate ionian-sequence 2))
(:lydian . ,(rotate ionian-sequence 3))
(:mixolydian . ,(rotate ionian-sequence 4))
(:aeolian . ,(rotate ionian-sequence 5))
(:minor . ,(rotate ionian-sequence 5))
(:locrian . ,(rotate ionian-sequence 6))
(:hex-major6 . ,(rotate hex-sequence 0))
(:hex-dorian . ,(rotate hex-sequence 1))
(:hex-phrygian . ,(rotate hex-sequence 2))
(:hex-major7 . ,(rotate hex-sequence 3))
(:hex-sus . ,(rotate hex-sequence 4))
(:hex-aeolian . ,(rotate hex-sequence 5))
(:minor-pentatonic . ,(rotate pentatonic-sequence 0))
(:yu . ,(rotate pentatonic-sequence 0))
(:major-pentatonic . ,(rotate pentatonic-sequence 1))
(:gong . ,(rotate pentatonic-sequence 1))
(:egyptian . ,(rotate pentatonic-sequence 2))
(:shang . ,(rotate pentatonic-sequence 2))
(:jiao . ,(rotate pentatonic-sequence 3))
(:pentatonic . ,(rotate pentatonic-sequence 4))
(:zhi . ,(rotate pentatonic-sequence 4))
(:ritusen . ,(rotate pentatonic-sequence 4))
;; ?? - from rsg
(:dorian-2 . ,(rotate melodic-minor 1))
(:lydian-augmented . ,(rotate melodic-minor 2))
(:lydian-dominant . ,(rotate melodic-minor 3))
(:mixolydian-6 . ,(rotate melodic-minor 4)) ;; bartok,hindu,mm
(:half-diminished . ,(rotate melodic-minor 5))
(:altered-scale . ,(rotate melodic-minor 6)) ;; super-locrian
;; from nudruz
(:goodmode . (1 1 3 1 1 2 3))
(:stravmode . (2 1 2)) ;; "Shur"
(:hyperlydian . (2 2 2 1))
(:hyperphrygian . (1 2 2)) ;; "Segah"
(:shushtar . (1 2 1 3))
(:bayati . (2 2 1 2 1)) ;; "Bayati Shiraz"
(:humayun . (1 3 1 2 2))
;; end of ??
(:whole-tone . (2 2 2 2 2 2))
(:whole . (2 2 2 2 2 2))
(:chromatic . (1 1 1 1 1 1 1 1 1 1 1 1))
(:harmonic-minor . (2 1 2 2 1 3 1))
(:melodic-minor-asc . ,melodic-minor)
(:hungarian-minor . (2 1 3 1 1 3 1))
(:octatonic . (2 1 2 1 2 1 2 1))
(:messiaen1 . (2 2 2 2 2 2))
(:messiaen2 . (1 2 1 2 1 2 1 2))
(:messiaen3 . (2 1 1 2 1 1 2 1 1))
(:messiaen4 . (1 1 3 1 1 1 3 1))
(:messiaen5 . (1 4 1 1 4 1))
(:messiaen6 . (2 2 1 1 2 2 1 1))
(:messiaen7 . (1 1 1 2 1 1 1 1 2 1))
(:super-locrian . (1 2 1 2 2 2 2))
(:hirajoshi . (2 1 4 1 4))
(:kumoi . (2 1 4 2 3))
(:neapolitan-major . (1 2 2 2 2 2 1))
(:bartok . (2 2 1 2 1 2 2))
(:bhairav . (1 3 1 2 1 3 1))
(:locrian-major . (2 2 1 1 2 2 2))
(:ahirbhairav . (1 3 1 2 2 1 2))
(:enigmatic . (1 3 2 2 2 1 1))
(:neapolitan-minor . (1 2 2 2 1 3 1))
(:pelog . (1 2 4 1 4))
(:augmented2 . (1 3 1 3 1 3))
(:scriabin . (1 3 3 2 3))
(:harmonic-major . (2 2 1 2 1 3 1))
(:melodic-minor-desc . (2 1 2 2 1 2 2))
(:romanian-minor . (2 1 3 1 2 1 2))
(:hindu . (2 2 1 2 1 2 2))
(:iwato . (1 4 1 4 2))
(:melodic-minor . ,melodic-minor)
(:diminished2 . (2 1 2 1 2 1 2 1))
(:marva . (1 3 2 1 2 2 1))
(:melodic-major . (2 2 1 2 1 2 2))
(:indian . (4 1 2 3 2))
(:spanish . (1 3 1 2 1 2 2))
(:prometheus . (2 2 2 5 1))
(:diminished . (1 2 1 2 1 2 1 2))
(:todi . (1 2 3 1 1 3 1))
(:leading-whole . (2 2 2 2 2 1 1))
(:augmented . (3 1 3 1 3 1))
(:purvi . (1 3 2 1 1 3 1))
(:chinese . (4 2 1 4 1))
(:lydian-minor . (2 2 2 1 1 2 2))
(:ryukyu . (4 1 2 4 1))
(:blues-major . (2 1 1 3 2 3))
(:blues-minor . (3 2 1 1 3 2))))))
(defvar +degree+
(let ((degrees '((:i . 1) (:ii . 2) (:iii . 3)
(:iv . 4) (:v . 5) (:vi . 6)
(:vii . 7) (:_ . nil))))
(alexandria:alist-hash-table degrees)))
(defun degree (d)
(gethash d +degree+))
(defun degree->interval (degree scale)
"Converts the degree of a scale given as a roman numeral keyword and
converts it to the number of semitones from the tonic of
the specified scale.
(degree->interval :ii :major) ;=> 2
Trailing #, b, + - represent sharps, flats, octaves up and down
respectively. An arbitrary number may be added in any order."
(cond ((null degree) nil)
((eql :_ degree) nil)
((numberp degree) (nth-interval scale (1- degree)))
((keywordp degree) (let* ((degree (resolve-degree degree))
(interval (nth-interval scale (1- (gethash :degree degree))))
(oct-shift (* 12 (gethash :octave-shift degree)))
(semi-shift (gethash :semitone-shift degree)))
(+ interval oct-shift semi-shift)))))
(defun degrees->pitches (degrees scale root)
"Convert intervals to pitches in MIDI number format. Supports
nested collections."
(let ((root (note root)))
(unless root
(error "invalid root"))
(mapcar (lambda (degree) (cond ((listp degree)
(degrees->pitches degree scale root))
((null degree) nil)
(t (let ((interval (degree->interval degree scale)))
(when interval
(+ root interval))))))
degrees)))
(defun nth-interval (x &optional y)
"Return the count of semitones for the nth degree from the start of
the diatonic scale in the specific mode (or ionian/major by
default).
i.e. the ionian/major scale has an interval sequence of 2 2 1 2 2 2
1 therefore the 4th degree is (+ 2 2 1 2) semitones from the
start of the scale."
(let ((m (cdr (assoc x +scale+))))
(if y
(reduce #'+ (take y (append m m m)))
(nth-interval :diatonic x))))
(defun find-pitch-class-name (note)
"Given a midi number representing a note, returns the name of the note
independent of octave.
(find-pitch-class-name 62) ;=> :D
(find-pitch-class-name 74) ;=> :D
(find-pitch-class-name 75) ;=> :Eb"
(reverse-notes (mod note 12)))
(defun find-note-name (note)
"Given a midi number representing a note, returns a keyword
representing the note including octave number. Reverse of the fn note.
(find-note-name 45) ;=> A2
(find-note-name 57) ;=> A3
(find-note-name 58) ;=> Bb3"
(when note
(let ((octave (1- (floor (/ note 12)))))
(to-keyword (concatenate 'string
(name (find-pitch-class-name note))
(write-to-string octave))))))
(defun degree->int (degree)
(if (some (lambda (x) (degree x)) (alexandria:hash-table-keys +degree+))
(degree degree)
(error "wrong degree")))
(defun resolve-degree (degree &optional octave-shift semitone-shift)
"returns a map representing the degree, and the octave semitone
shift (i.e. sharp flat)"
(if (and octave-shift semitone-shift)
(let* ((oct (cl-user::string-to-octets (name degree)))
(len-oct (1- (length oct)))
(last-oct (aref oct len-oct)))
(cond ((= 45 last-oct) (resolve-degree (to-keyword (name degree))
(1- octave-shift)
semitone-shift))
((= 43 last-oct) (resolve-degree (to-keyword (name degree))
(1+ octave-shift)
semitone-shift))
((= 98 last-oct) (resolve-degree (to-keyword (name degree))
octave-shift
(1- semitone-shift)))
((= 35 last-oct) (resolve-degree (to-keyword (name degree))
octave-shift
(1+ semitone-shift)))
(t (let ((degree (degree->int degree)))
(alexandria:alist-hash-table `((:degree . ,degree)
(:octave-shift . ,octave-shift)
(:semitone-shift . ,semitone-shift)))))))
(resolve-degree degree 0 0)))
(defun resolve-degrees (degrees)
"Either maps the degrees to integers if they're keywords using the map DEGREE
or leaves them unmodified"
(mapcar (lambda (x) (if (keywordp x) (degree x) x))
degrees))
(defun ov-scale (root scale &optional l-degrees)
"Returns a list of notes for the specified scale. The root must be
in midi note format i.e. :C4 or :Bb4
(scale :c4 :major) ; c major -> (60 62 64 65 67 69 71 72)
(scale :Bb4 :minor) ; b flat minor -> (70 72 73 75 77 78 80 82)"
(if l-degrees
(let ((root (note root))
(degrees (resolve-degrees l-degrees)))
(cons root
(mapcar (lambda (x) (+ root (nth-interval scale x)))
degrees)))
(ov-scale root scale (myrange 8 :min 1))))
(defvar +chord+
(let ((major '(0 4 7))
(minor '(0 3 7))
(major7 '(0 4 7 11))
(dom7 '(0 4 7 10))
(minor7 '(0 3 7 10))
(aug '(0 4 8))
(dim '(0 3 6))
(dim7 '(0 3 6 9)))
(alexandria:alist-hash-table
`((:1 . (0))
(:5 . (0 7))
(:+5 . (0 4 8))
(:m+5 . (0 3 8))
(:sus2 . (0 2 7))
(:sus4 . (0 5 7))
(:6 . (0 4 7 9))
(:m6 . (0 3 7 9))
(:7sus2 . (0 2 7 10))
(:7sus4 . (0 5 7 10))
(:7-5 . (0 4 6 10))
(:m7-5 . (0 3 6 10))
(:7+5 . (0 4 8 10))
(:m7+5 . (0 3 8 10))
(:9 . (0 4 7 10 14))
(:m9 . (0 3 7 10 14))
(:m7+9 . (0 3 7 10 14))
(:maj9 . (0 4 7 11 14))
(:major9 . (0 4 7 11 14))
(:9sus4 . (0 5 7 10 14))
(:6*9 . (0 4 7 9 14))
(:m6*9 . (0 3 9 7 14))
(:7-9 . (0 4 7 10 13))
(:m7-9 . (0 3 7 10 13))
(:7-10 . (0 4 7 10 15))
(:9+5 . (0 10 13))
(:m9+5 . (0 10 14))
(:7+5-9 . (0 4 8 10 13))
(:m7+5-9 . (0 3 8 10 13))
(:11 . (0 4 7 10 14 17))
(:m11 . (0 3 7 10 14 17))
(:maj11 . (0 4 7 11 14 17))
(:major11 . (0 4 7 11 14 17))
(:11+ . (0 4 7 10 14 18))
(:m11+ . (0 3 7 10 14 18))
(:13 . (0 4 7 10 14 17 21))
(:m13 . (0 3 7 10 14 17 21))
(:major . ,major)
(:+ . ,major)
(:M . ,major)
(:minor . ,minor)
(:- . ,minor)
(:m . ,minor)
(:major7 . ,major7)
(:maj7 . ,major7)
(:M7 . ,major7)
(:dom7 . ,dom7)
(:7 . ,dom7)
(:minor7 . ,minor7)
(:m7 . ,minor7)
(:augmented . ,aug)
(:a . ,aug)
(:diminished . ,dim)
(:dim . ,dim)
(:i . ,dim)
(:diminished7 . ,dim7)
(:dim7 . ,dim7)
(:i7 . ,dim7)
;;------------------------------
(1 . (0))
(5 . (0 7))
(+5 . (0 4 8))
(m+5 . (0 3 8))
(sus2 . (0 2 7))
(sus4 . (0 5 7))
(6 . (0 4 7 9))
(m6 . (0 3 7 9))
(7sus2 . (0 2 7 10))
(7sus4 . (0 5 7 10))
(7-5 . (0 4 6 10))
(m7-5 . (0 3 6 10))
(7+5 . (0 4 8 10))
(m7+5 . (0 3 8 10))
(9 . (0 4 7 10 14))
(m9 . (0 3 7 10 14))
(m7+9 . (0 3 7 10 14))
(maj9 . (0 4 7 11 14))
(major9 . (0 4 7 11 14))
(9sus4 . (0 5 7 10 14))
(6*9 . (0 4 7 9 14))
(m6*9 . (0 3 9 7 14))
(7-9 . (0 4 7 10 13))
(m7-9 . (0 3 7 10 13))
(7-10 . (0 4 7 10 15))
(9+5 . (0 10 13))
(m9+5 . (0 10 14))
(7+5-9 . (0 4 8 10 13))
(m7+5-9 . (0 3 8 10 13))
(11 . (0 4 7 10 14 17))
(m11 . (0 3 7 10 14 17))
(maj11 . (0 4 7 11 14 17))
(major11 . (0 4 7 11 14 17))
(11+ . (0 4 7 10 14 18))
(m11+ . (0 3 7 10 14 18))
(13 . (0 4 7 10 14 17 21))
(m13 . (0 3 7 10 14 17 21))
(major . ,major)
(+ . ,major)
(M . ,major)
(minor . ,minor)
(- . ,minor)
(m . ,minor)
(major7 . ,major7)
(maj7 . ,major7)
(M7 . ,major7)
(dom7 . ,dom7)
(7 . ,dom7)
(minor7 . ,minor7)
(m7 . ,minor7)
(augmented . ,aug)
(a . ,aug)
(diminished . ,dim)
(dim . ,dim)
(i . ,dim)
(diminished7 . ,dim7)
(dim7 . ,dim7)
(i7 . ,dim7)))))
(defun inc-first (elems n)
"Remove the first element, increment it by n, and append to seq."
(append (rest elems)
(list (+ n (first elems)))))
(defun dec-last (elems n)
"Remove the last element, decrement it by n, and prepend to seq."
(append (list (- (last elems) n))
(butlast elems)))
(defun resolve-chord (chord)
"Either looks the chord up in the map of CHORDs if it's a keyword or
simply returns it unnmodified. Allows users to specify a chord
either with a set such as #{0 4 7} or by keyword such as :major
SHINY> (resolve-chord :m9)
(0 3 7 10 14)"
(if (symbolp chord)
(gethash chord +chord+)
chord))
(defun invert-chord (notes shift)
"Move a chord voicing up or down.
;first inversion
(invert-chord [60 64 67] 1) ;=> (64 67 72)
; second inversion
(invert-chord [60 64 67] 2) ;=> (67 72 76)
"
(cond ((> shift 0) (invert-chord (inc-first notes 12) (1- shift)))
((< shift 0) (invert-chord (dec-last notes 12) (1+ shift)))
((= shift 0) notes)))
;; NOTE: retuns might not be sorted accordingly (?
;; also second example is incorrect (!
(defun chord (root chord-name &optional inversion)
"Returns a set of notes for the specified chord. The root must be in
midi note format i.e. :C4.
(chord :c4 :major) ; c major -> #{60 64 67}
(chord :a4 :minor) ; a minor -> #{57 60 64}
(chord :Bb4 :dim) ; b flat diminished -> #{70 73 76}
"
(if inversion
(let* ((root (note root))
(chord (resolve-chord chord-name))
(notes (mapcar (lambda (x) (+ x root))
chord)))
(invert-chord notes inversion))
(chord root chord-name 0)))
(defun chord-degree (degree root mode &optional num-notes)
"Returns the notes constructed by picking thirds in a given scale
from in a given root. Useful if you want to try out playing standard
chord progressions. For example:
(chord-degree :i :c4 :ionian) ;=> (60 64 67 71)
(chord-degree :ii :c4 :melodic-minor-asc) ;=> (62 65 69 72)
"
(if num-notes
(let* ((d-int (degree->int degree))
(num-degrees (1- (+ d-int (* num-notes 2)))))
(take-nth 2 (nthcdr (degree->int degree)
(ov-scale root mode (myrange num-degrees)))))
(chord-degree degree root mode 4)))
(defun rand-chord (root chord-name
num-pitches pitch-range)
"Generates a random list of MIDI notes with cardinality num-pitches
bound within the range of the specified root and pitch-range and
only containing pitches within the specified chord-name. Similar to
Impromptu's pc:make-chord"
(let* ((chord (chord root chord-name))
(root (note root))
(max-pitch (+ pitch-range root))
(roots (myrange max-pitch :step 12))
(notes (flatten (mapcar (lambda (x) (mapcar (lambda (y) (+ x y)) chord))
roots)))
(notes (filter (lambda (x) (when (<= x max-pitch) x)) notes)))
(sort (pick-random-list notes num-pitches) #'<)))
#|
Scales can be quickly generated using the scale function, which takes a root note and the type of scale as arguments.
whelmed.play> (scale :C3 :major)
(48 50 52 53 55 57 59 60)
whelmed.play> (SCALE :purvi)
[1 3 2 1 1 3 1]
whelmed.play> (degrees->pitches [:i :ii :iii] :dorian :E3)
(52 54 55)
Scale degrees can be augmented by either + or - to denote the octave above or below the root of the scale, and can be sharped or flatted using # or b.
whelmed.play> (degrees->pitches [:i :ii :ii+ :ii#] :dorian :E3)
(52 54 66 55)
https://github.com/overtone/overtone/blob/36221f68733fc5921aeb60a2a8b10e99426f236d/src/overtone/music/pitch.clj
|#
;;--------------------------------------------------
;; From overtone, fn.clj
;; cycle-fn????
;; from overtone, lists.clj
;; rotate, like alexandria:rotate-elt
;; fill a.k.a. repeat
;; from overtone, chance.clj
;; might be called pickln
(defun choose-n (n l)
"Choose n random elements from l"
(take n (alexandria:shuffle l)))
;; weighted-coin is like (cm:odds)
;; ranged-rand is like (cm:between)
;; choose/chosen-from is like (cm:pickl) or (alexandria:random-elt)
;; weighted-choose is like (cm:new cm:weighted)
(defun sputter (list &optional (prob .25) (max 100) (result '()))
"Returns a list where some elements may have been repeated.
Repetition is based on probabilty (defaulting to 0.25), therefore,
for each element in the original list, there's a chance that it will
be repeated. (The repetitions themselves are also subject to further
repetiton). The size of the resulting list can be constrained to max
elements (defaulting to 100).
(sputter '(1 2 3 4)) ;=> (1 1 2 3 3 4)
(sputter '(1 2 3 4) 0.7 5) ;=> (1 1 1 2 3)
(sputter '(1 2 3 4) 0.8 10) ;=> (1 2 2 2 2 2 2 2 3 3)
(sputter '(1 2 3 4) 1 10) ;=> (1 1 1 1 1 1 1 1 1 1)
"
(let ((head (first list))
(tail (rest list)))
(if (and head (< (length result) max))
(if (< (random 1.0) prob)
(sputter (cons head tail)
prob max
(cons head result))
(sputter tail
prob max
(cons head result)))
(reverse result))))
;; sputter variation that always returns a list of the same length of the input
(defun stutter (list &optional (prob .25) (result '()))
(let ((head (first list))
(tail (rest list))
(max (length list)))
(if (and head (< (length result) max))
(if (< (random 1f0) prob)
(sputter (cons head tail)
prob max
(cons head result))
(sputter tail
prob max
(cons head result)))
(reverse result))))
;;--------------------------------------------------
;; CUSTOM
;;; Extra
(defun ov-pc-scale (scale-name-key)
"> (ov-pc-scale :todi)
(0 1 3 6 7 8 11)"
(declare (type keyword scale-name-key))
(butlast
(loop :for i :in (cons 0 (cdr (assoc scale-name-key +scale+)))
:with n = 0 :collect (incf n i))))
(defun list-scales ()
"returns a list with the keyword names of all overtone scales"
(mapcar #'car +scale+))
(defun list-in-list (small-list big-list)
"returns T or NIL if SMALL-LIST is into BIG-LIST"
(let ((len (length small-list)))
(length= len (intersection small-list big-list))))
(defun guess-scale (l)
"given a list L of midi notes returns a list of possible compatiple
pitch classes for the notes given"
(let* ((m12 (mod12 l))
(scales (list-scales))
(pc-scales (mapcar (lambda (x) (ov-pc-scale x)) scales)))
(remove NIL
(mapcar (lambda (s p)
(when (list-in-list m12 p)
s))
scales
pc-scales))))
| 27,384 | Common Lisp | .lisp | 657 | 32.964992 | 150 | 0.487956 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | b7579e2cbd739247cc192b9c0099ef99e47767e7cd6fac419ffbfb27096da360 | 9,051 | [
-1
] |
9,052 | drums.lisp | azimut_shiny/lib/drums.lisp | (in-package :shiny)
(defparameter *patterns* (make-hash-table))
;; Drum Patterns took from:
;; https://github.com/lvm/tidal-drum-patterns
;; http://hiphoptranscriptions.com/post/159995606528
;;
;; Info about pattern names:
;; https://en.wikipedia.org/wiki/Drum_tablature
;;
;; TODO:
;; - Some definition lost while translating them to t/nil
;; For example some are 0/2.
;;
;; - Others not done to being unable to understand the pattern format yet.
;; $ grep -l -e ']]' -e ']/' -e '\[\[' *.hs
;; Breaks.hs
;; Jungle.hs
;; https://stackoverflow.com/questions/5457346/lisp-function-to-concatenate-a-list-of-strings
(defun concat (&rest list)
"A non-recursive function that concatenates a list of strings."
(if (listp list)
(let ((result ""))
(dolist (item list)
(if (stringp item)
(setq result (concatenate 'string result item))))
result)))
(defclass drum-pattern ()
((name :initarg :name :reader pattern-name)
(bd :initarg :bd :reader bd)
(ch :initarg :ch :reader ch)
(oh :initarg :oh :reader oh)
(sn :initarg :sn :reader sn)))
(defmethod print-object ((obj drum-pattern) out)
(print-unreadable-object (obj out :type t)
(format out "~s" (pattern-name obj))))
(defgeneric parse-pattern (pattern &key true-char))
(defmethod parse-pattern ((pattern string) &key (true-char #\x))
(values
(loop
:for c
:across (string-downcase pattern)
:when (or (eq c #\x) (eq c #\1) (eq c #\0)
(eq c #\~) (eq c #\-))
:collect
(if (eq true-char c)
t
nil))
pattern))
;; FIXME: not consistent with string version
(defmethod parse-pattern ((pattern list) &key true-char)
(loop :for beat :in pattern :collect
(if (= 0 beat) nil t)))
(defun parse-patternc (s &key (true-char #\x))
(when-let ((p (parse-pattern s :true-char true-char)))
(make-cycle p)))
;; Shorthands
(defun parse1 (pattern)
(values
(loop
:for c
:across (string-downcase pattern)
:when (or (eq c #\x) (eq c #\1) (eq c #\0)
(eq c #\~) (eq c #\-))
:collect
(if (eq c #\1)
t
nil))
pattern))
(defun parsex (pattern)
(values
(loop
:for c
:across (string-downcase pattern)
:when (or (eq c #\x) (eq c #\1) (eq c #\0)
(eq c #\~) (eq c #\-))
:collect
(if (eq c #\x)
t
nil))
pattern))
(defun make-pattern (name short-name &key bd ch oh sn)
(declare (string name) (symbol short-name))
(setf (gethash short-name *patterns*)
(make-instance
'drum-pattern
:name name
:bd (parse-pattern bd :true-char #\0)
:ch (parse-pattern ch :true-char #\0)
:oh (parse-pattern oh :true-char #\0)
:sn (parse-pattern sn :true-char #\0))))
(defun list-patterns ()
(alexandria:hash-table-keys *patterns*))
(defun get-pattern (name)
(declare (symbol name))
"returns a list of the pattern"
(gethash name *patterns*))
(make-pattern
"Mother Popcorn"
'popcorn
:bd (concat "[0 ~ 0 ~][~ ~ ~ ~][~ ~ 0 ~][~ ~ ~ ~]"
"[~ ~ 0 ~][~ ~ 0 ~][~ ~ 0 ~][~ ~ 0 ~]")
:sn (concat "[~ ~ ~ ~][0 ~ ~ 0][~ 0 ~ ~][~ ~ 0 ~]"
"[~ 0 ~ 0][0 0 ~ 0][~ 0 ~ 0][0 0 ~ 0]")
:ch (concat "[0 ~ ~ ~]"))
(make-pattern
"Book Of Moses"
'moses
:bd "[0 ~ ~ ~][0 ~ ~ ~][0 ~ ~ 0][~ ~ ~ ~]"
:sn "[~ ~ ~ ~][0 ~ ~ ~][~ ~ ~ ~][0 ~ ~ ~]"
:ch "[0 ~ 0 ~]")
(make-pattern
"Synthetic Substitution"
'ssub
:bd "[0 ~ 0 ~][~ ~ ~ 0][~ 0 0 0][~ ~ ~ 0]"
:sn "[~ ~ ~ ~][~ 0 ~ ~][~ ~ ~ ~][~ 0 ~ ~]"
:ch (concat
"[0 ~ 0 ~][0 ~ 0 ~][0 ~ 0 ~][0 ~ 0 ~]"
"[0 ~ ~ ~][0 ~ 0 ~][0 ~ 0 ~][0 ~ 0 ~]")
:oh "[~ ~ 0 ~][~ ~ ~ ~][~ ~ ~ ~][~ ~ ~ ~]")
(make-pattern
"Get Up"
'getup
:bd "[0 ~ ~ ~][~ ~ ~ ~][~ ~ 0 ~][~ ~ 0 ~]"
:sn "[~ ~ ~ ~][0 ~ 0 0][~ 0 ~ ~][0 ~ ~ 0]"
:ch "[0 ~ ~ ~][0 ~ 0 0][0 ~ ~ ~][0 ~ 0 0]"
:oh "[~ ~ 0 ~][~ ~ ~ ~][~ ~ 0 ~][~ ~ ~ ~]")
(make-pattern
"Express Yourself"
'express
:bd (concat "[0 ~ ~ 0][0 ~ ~ 0][~ ~ 0 ~][0 ~ ~ 0]"
"[0 ~ ~ 0][~ ~ ~ ~][0 ~ ~ 0][~ ~ 0 ~]")
:sn (concat "[~ ~ ~ ~][0 ~ ~ 0][~ 0 ~ 0][~ 0 ~ 0]"
"[~ ~ ~ ~][0 ~ ~ 0][~ 0 ~ 0][0 ~ ~ ~]")
:ch (concat "[0 0 0 0][0 0 0 0][0 0 0 0][0 0 0 0]"
"[0 0 0 0][0 0 0 0][0 0 0 0][0 0 0 ~]"))
(make-pattern
"Superstition"
'superstition
:bd "[0 ~ ~ ~][0 ~ ~ ~][0 ~ ~ ~][0 ~ ~ ~]"
:sn "[~ ~ ~ ~][0 ~ ~ ~][~ ~ ~ ~][0 ~ ~ ~]"
:ch "[0 ~ 0 ~][0 ~ 0 0][0 0 0 ~][0 ~ 0 0]")
(make-pattern
"Respect Yourself"
'respect
:bd (concat "[0 ~ ~ ~][0 ~ ~ ~][0 ~ ~ ~][0 ~ ~ ~]")
:sn (concat "[~ ~ ~ ~][0 ~ ~ ~][~ ~ 0 ~][0 ~ ~ ~]"
"[~ ~ ~ ~][0 ~ ~ ~][0 ~ 0 ~][0 ~ ~ ~]")
:ch (concat "[0 ~ 0 ~]"))
(make-pattern
"Rock Steady"
'rsteady
:bd (concat "[~ ~ 0 ~][0 ~ ~ 0][~ ~ 0 ~][0 ~ ~ ~]")
:sn (concat "[~ 0 ~ ~][0 0 ~ 0][~ 0 ~ ~][0 0 ~ 0]")
:ch (concat "[~ 0 ~ ~][0 ~ 0 ~][0 ~ ~ ~][0 ~ 0 ~]"
"[0 ~ ~ ~][0 ~ 0 0][0 ~ ~ ~][0 ~ 0 0]")
:oh (concat "[~ ~ 0 ~][~ ~ ~ 0][~ ~ 0 ~][~ ~ ~ 0]"
"[~ 0 ~ ~][~ ~ ~ ~][~ ~ 0 ~][~ ~ ~ ~]"))
(make-pattern
"GrooveMe"
'grooveme
:bd "[0 ~ ~ 0][0 ~ ~ 0][0 0 ~ 0][~ 0 ~ 0]"
:sn "[~ ~ ~ ~][0 ~ ~ ~][~ ~ ~ ~][0 ~ ~ ~]"
:ch "[0 ~ 0 ~]")
(make-pattern
"The Thrill Is Gone"
'thrill
:bd (concat "[~ ~ ~ ~][~ ~ ~ 0][0 ~ 0 ~][~ ~ ~ ~]")
:sn (concat "[0 ~ ~ ~][0 ~ ~ ~][0 ~ ~ ~][0 ~ ~ ~]")
:ch (concat "[0 ~ 0 ~]"))
(make-pattern
"Haitian Divorce"
'haitian
:bd "[~ ~ 0 ~][0 ~ ~ ~][~ ~ 0 ~][0 ~ ~ ~]"
:sn "[~ 0 ~ ~][0 ~ 0 0][~ 0 ~ ~][0 ~ 0 0]"
:ch "[0 0 ~ ~][0 0 0 0][0 0 ~ ~][0 0 0 0]"
:oh "[~ ~ 0 ~][~ ~ ~ ~][~ ~ 0 ~][~ ~ ~ ~]")
(make-pattern
"The Fez"
'fez
:bd (concat "[0 ~ ~ ~][~ ~ ~ ~][0 ~ ~ ~][~ ~ ~ ~]"
"[0 ~ ~ ~][~ ~ ~ ~][0 ~ ~ 0][0 ~ ~ ~]")
:sn (concat "[~ 0 ~ 0][0 0 ~ 0][~ 0 ~ 0][0 0 ~ 0]")
:ch (concat "[~ ~ 0 ~][~ ~ 0 ~][~ ~ 0 ~][~ ~ 0 ~]"))
(make-pattern
"Pop tech 2010"
'pop
:bd (concat "[0 ~ ~ ~][~ ~ ~ ~][~ ~ ~ ~][~ ~ ~ ~]"
"[~ 0 ~ ~][~ ~ ~ ~][~ ~ ~ ~][~ 0 0 0]")
:sn (concat "[~ ~ ~ ~][0 ~ ~ ~][~ ~ ~ ~][0 ~ ~ ~]")
:ch (concat "[~ ~ ~ ~][~ ~ ~ ~][0 ~ ~ ~][~ ~ ~ ~]"
"[0 ~ ~ ~][~ ~ ~ ~][0 ~ ~ ~][~ ~ ~ ~]")
:oh (concat "[0 ~ ~ ~][~ ~ ~ ~][~ ~ ~ ~][~ ~ ~ ~]"
"[~ ~ ~ ~][~ ~ ~ ~][~ ~ ~ ~][~ ~ ~ ~]"))
(make-pattern
"Kissing My Love"
'kml
:bd (concat "[0 ~ ~ 0][~ ~ ~ ~][~ ~ ~ 0][~ ~ 0 ~]"
"[0 ~ ~ ~][~ ~ ~ ~][~ ~ ~ 0][~ 0 ~ ~]")
:sn (concat "[~ ~ ~ ~][0 ~ ~ ~][~ 0 ~ ~][0 ~ ~ ~]"
"[~ ~ ~ ~][0 ~ ~ 0][~ 0 ~ ~][0 ~ ~ ~]")
:ch (concat "[0 0 0 0][0 0 0 0][0 0 0 0][0 0 ~ ~]")
:oh (concat "[~ ~ ~ ~][~ ~ ~ ~][~ ~ ~ ~][~ ~ 0 ~]"))
(make-pattern
"Knocks Me Off My Feet"
'knocks
:bd "[0 ~ 0 ~][0 ~ ~ 0][0 ~ 0 ~][0 ~ ~ 0]"
:sn "[~ ~ ~ ~][0 ~ ~ ~][~ ~ ~ ~][0 ~ ~ ~]"
:ch "[0 ~ ~ ~][~ ~ 0 0][~ 0 ~ ~][~ ~ 0 ~]"
:oh "[~ ~ 0 ~][~ ~ ~ ~][~ ~ 0 ~][~ ~ ~ ~]")
(make-pattern
"Cissy Strut"
'cissy
:bd "[0 ~ ~ 0][~ 0 ~ ~][0 0 ~ 0][~ 0 ~ ~]"
:sn "[0 0 0 ~][0 ~ 0 0][~ 0 0 ~][0 ~ 0 ~]"
:ch "[0 0 0 ~][0 ~ 0 0][~ 0 0 ~][0 ~ 0 ~]")
(make-pattern
"Cissy Strut 2"
'cissy2
:bd (concat "[0 ~ ~ 0][~ 0 ~ ~][~ 0 ~ 0][0 ~ 0 ~]"
"[0 ~ ~ 0][~ ~ ~ 0][~ 0 ~ 0][0 ~ 0 ~]")
:sn (concat "[~ ~ ~ ~][0 ~ ~ 0][~ 0 0 ~][~ ~ ~ ~]"
"[~ ~ 0 ~][~ 0 0 ~][0 0 ~ ~][~ ~ ~ ~]")
:oh (concat "[~ ~ ~ ~][~ ~ ~ ~][~ ~ ~ ~][0 ~ 0 ~]"))
(make-pattern
"StrBtsDcGogo100"
'gogo
:bd "[0 ~ ~ 0][~ ~ 0 ~][~ ~ 0 ~][~ ~ ~ ~]"
:sn "[~ 0 ~ ~][0 ~ ~ 0][~ ~ ~ ~][0 ~ ~ ~]"
:ch "[~ 0 0 ~][0 0 ~ 0][~ ~ ~ ~][~ 0 0 ~]"
:oh "[~ ~ ~ ~][~ ~ ~ ~][0 ~ ~ ~][~ ~ ~ ~]")
(make-pattern
"Come Dancing"
'dancing
:bd (concat "[0 ~ ~ ~][~ ~ ~ 0][0 ~ ~ ~][~ ~ ~ 0]"
"[0 ~ 0 ~][~ 0 ~ 0][0 ~ ~ ~][~ ~ ~ 0]")
:sn (concat "[~ 0 0 ~][0 0 0 ~][~ 0 0 ~][0 0 0 ~]"
"[~ 0 ~ ~][0 0 ~ ~][~ 0 ~ ~][0 0 0 ~]")
:ch (concat "[0 ~ 0 ~]"))
(make-pattern
"Chug Chug Chug Chug A Lug"
'chug
:bd "[0 ~ ~ 0][~ 0 ~ 0][~ 0 ~ 0][~ ~ 0 ~]"
:sn "[~ 0 0 ~][0 ~ ~ 0][~ 0 0 ~][0 ~ ~ ~]"
:ch "[0 ~ 0 ~][0 0 0 ~][0 0 0 ~][0 ~ ~ ~]"
:oh "[~ ~ ~ ~][~ ~ ~ ~][~ ~ ~ ~][~ ~ 0 ~]")
(make-pattern
"Cold Sweat"
'cold
:bd (concat "[0 ~ ~ ~] [~ ~ ~ ~] [0 ~ 0 ~] [~ ~ ~ ~]")
:sn (concat "[~ ~ ~ ~] [0 ~ ~ 0] [~ ~ ~ ~] [~ ~ 0 ~]"
"[~ 0 ~ ~] [0 ~ ~ 0] [~ 0 ~ ~] [0 ~ ~ ~]")
:ch (concat "[0 ~ ~ ~] [0 ~ 0 ~] [0 ~ ~ ~] [0 ~ 0 ~]")
:oh (concat "[~ ~ 0 ~] [~ ~ ~ ~] [~ ~ 0 ~] [~ ~ ~ ~]"))
(make-pattern
"Amen"
'amen
:bd (concat "[0 ~ 0 ~] [~ ~ ~ ~] [~ ~ 0 0] [~ ~ ~ ~]"
"[0 ~ 0 ~] [~ ~ ~ ~] [~ ~ 0 0] [~ ~ ~ ~]"
"[0 ~ 0 ~] [~ ~ ~ ~] [~ ~ 0 ~] [~ ~ ~ ~]"
"[~ ~ 0 0] [~ ~ ~ ~] [~ ~ 0 ~] [~ ~ ~ ~]")
:sn (concat "[~ ~ ~ ~] [0 ~ ~ 0] [~ 0 ~ ~] [0 ~ ~ 0]"
"[~ ~ ~ ~] [0 ~ ~ 0] [~ 0 ~ ~] [0 ~ ~ 0]"
"[~ ~ ~ ~] [0 ~ ~ 0] [~ 0 ~ ~] [~ ~ 0 ~]"
"[~ 0 ~ ~] [0 ~ ~ 0] [~ 0 ~ ~] [~ ~ 0 ~]")
:ch (concat "[0 ~ 0 ~] [0 ~ 0 ~] [0 ~ 0 ~] [0 ~ 0 ~]")
:oh (concat "[~ ~ ~ ~] [~ ~ ~ ~] [~ ~ 0 ~] [~ ~ ~ ~]"))
(make-pattern
"Cowd Bell"
'cbell
:bd (concat "[0 ~ ~ 0][~ ~ 0 0][~ ~ 0 0][~ 0 ~ 0]"
"[0 ~ 0 0][~ ~ ~ 0][0 ~ 0 0][~ 0 ~ 0]")
:sn (concat "[0 ~ 0 0][~ ~ ~ 0][0 ~ 0 0][~ 0 ~ 0]")
:ch (concat "[0 ~ 0 0][0 ~ 0 0][0 ~ 0 0][0 ~ 0 0]"))
(make-pattern
"Expensive Shit"
'expensive
:bd (concat "[~ ~ ~ 0][~ ~ 0 ~][~ ~ ~ ~][~ ~ 0 ~]")
:sn (concat "[0 0 ~ 0][~ 0 ~ ~][0 0 ~ ~][0 0 ~ ~]")
:ch (concat "[0 ~ 0 0][0 ~ 0 0][0 ~ 0 ~][0 ~ 0 0]"
"[0 ~ 0 ~][0 ~ 0 0][0 ~ 0 0][0 ~ 0 0]")
:oh (concat "[~ ~ ~ ~][~ ~ ~ ~][~ ~ ~ 0][~ ~ ~ ~]"
"[~ ~ ~ 0][~ ~ ~ ~][~ ~ ~ ~][~ ~ ~ ~]"))
(make-pattern
"Hook And Sling"
'hook
:bd (concat "[0 ~ 0 ~][~ ~ ~ ~][~ 0 ~ ~][~ 0 0 ~]"
"[~ ~ ~ ~][~ ~ ~ ~][~ ~ ~ ~][~ 0 ~ ~]")
:sn (concat "[~ ~ ~ ~][0 ~ 0 0][~ ~ 0 ~][0 ~ ~ ~]"
"[0 ~ ~ ~][0 0 ~ 0][~ ~ 0 0][~ ~ 0 0]")
:ch (concat "[0 ~ 0 0][~ 0 ~ ~][0 0 ~ 0][~ ~ ~ ~]"
"[0 0 ~ 0][~ ~ 0 ~][0 0 ~ ~][0 ~ 0 ~]")
:oh (concat "[~ ~ ~ ~][~ ~ ~ ~][~ ~ ~ ~][~ ~ 0 ~]"))
(make-pattern
"OOH Child"
'oohchild
:bd (concat "[0 ~ 0 ~][~ ~ ~ ~][0 ~ 0 0][~ ~ ~ ~]"
"[0 ~ 0 0][~ ~ ~ ~][0 ~ 0 0][~ ~ ~ ~]")
:sn (concat "[~ 0 ~ 0][0 0 ~ 0][~ 0 ~ 0][0 0 ~ 0]"
"[~ 0 ~ 0][0 0 ~ 0][~ 0 ~ ~][0 ~ 0 ~]")
:ch (concat "[0 0 ~ ~][0 0 ~ ~][0 0 ~ ~][0 0 ~ ~]")
:oh (concat "[~ ~ 0 ~][~ ~ 0 ~][~ ~ 0 ~][~ ~ 0 ~]"))
(make-pattern
"Use Me"
'useme
:bd (concat "[0 ~ 0 ~][~ 0 ~ 0][0 ~ 0 0][~ 0 ~ 0]"
"[0 ~ 0 ~][~ 0 ~ ~][0 0 ~ 0][~ 0 ~ 0]")
:sn (concat "[~ ~ ~ ~][0 ~ ~ 0][~ 0 ~ ~][0 ~ ~ 0]"
"[~ ~ ~ ~][0 ~ ~ 0][~ ~ ~ ~][~ ~ ~ 0]")
:ch (concat "[0 0 0 0][0 0 0 0][0 0 0 0][0 0 0 0]"
"[0 0 0 0][0 0 0 0][0 ~ ~ ~][~ ~ ~ 0]")
:oh (concat "[~ ~ ~ ~][~ ~ ~ ~][~ 0 ~ 0][~ 0 ~ ~]"))
(make-pattern
"Use Me"
'useme2
:bd (concat "[0 ~ ~ ~][0 ~ ~ ~][~ ~ ~ ~][0 ~ ~ ~]"
"[~ ~ ~ ~][0 ~ ~ 0][~ ~ 0 ~][0 ~ ~ ~]")
:sn (concat "[~ ~ 0 ~][0 ~ 0 0][~ 0 0 ~][0 ~ 0 0]"
"[~ 0 0 ~][0 ~ 0 0][~ 0 0 ~][0 ~ 0 0]")
:ch (concat "[0 ~ ~ ~][0 0 0 0][0 0 ~ ~][0 0 0 0]"
"[0 0 ~ ~][0 0 0 0][0 0 ~ ~][0 0 0 0]")
:oh (concat "[~ ~ 0 ~][~ ~ ~ ~][~ ~ 0 ~][~ ~ ~ ~]"
"[~ ~ 0 ~][~ ~ ~ ~][~ ~ 0 ~][~ ~ ~ ~]"))
(make-pattern
"The Same Blood"
'blood
:bd "[0 0 ~ ~][~ ~ ~ ~][0 0 ~ ~][~ ~ ~ ~]"
:sn "[~ ~ ~ 0][~ 0 0 ~][~ ~ ~ ~][0 0 0 ~]"
:ch "[0 ~ 0 ~][0 ~ 0 0][0 ~ 0 0][0 ~ 0 0]")
(make-pattern
"Lady"
'lady
:bd (concat "[0 ~ ~ ~][~ ~ ~ ~][0 ~ ~ 0][~ ~ 0 ~]"
"[0 ~ ~ ~][~ ~ ~ ~][~ ~ ~ 0][~ ~ 0 ~]")
:sn (concat "[~ ~ ~ ~][0 0 ~ ~][~ ~ ~ ~][~ ~ ~ ~]"
"[~ ~ ~ ~][0 0 ~ ~][0 ~ ~ ~][~ ~ ~ ~]")
:ch (concat "[~ ~ 0 ~][~ ~ 0 ~][~ ~ ~ ~][~ ~ ~ ~]")
:oh (concat "[~ ~ 0 ~][~ ~ 0 ~][~ ~ ~ ~][~ ~ ~ ~]"))
(make-pattern
"Lady Marmalade"
'ladym
:bd (concat "[0 ~ ~ ~][~ ~ 0 ~][0 ~ ~ ~][~ ~ 0 ~]"
"[~ ~ ~ ~][~ ~ ~ ~][~ ~ ~ ~][0 ~ ~ ~]")
:sn (concat "[~ ~ ~ ~][0 ~ ~ ~][~ ~ ~ ~][0 ~ ~ ~]"
"[~ ~ ~ ~][0 ~ ~ ~][0 ~ ~ ~][~ ~ ~ ~]")
:ch (concat "[0 ~ 0 ~][0 ~ 0 ~][0 ~ 0 ~][0 ~ 0 ~]")
:oh (concat "[~ ~ ~ ~][~ ~ ~ ~][~ ~ 0 ~][~ ~ ~ ~]"))
(make-pattern
"Let A Woman Be A Woman Let A Man Be A Man"
'wm
:bd (concat "[~ ~ 0 ~][~ ~ ~ ~][0 ~ 0 0][~ 0 0 ~]"
"[~ ~ 0 ~][~ ~ ~ ~][~ ~ 0 ~][~ ~ 0 ~]")
:sn (concat "[~ ~ ~ ~][0 ~ ~ 0][~ 0 0 ~][0 0 ~ ~]"
"[~ ~ ~ ~][0 ~ ~ 0][~ 0 ~ 0][0 ~ ~ ~]")
:ch (concat "[0 ~ 0 ~][0 ~ 0 ~][0 ~ 0 ~][0 ~ ~ ~]")
:oh (concat "[~ ~ ~ ~][~ ~ ~ ~][~ ~ ~ ~][~ ~ 0 ~]"))
(make-pattern
"Look Ka Py Py"
'pypy
:bd (concat "[0 ~ ~ 0][~ 0 ~ ~][~ ~ 0 ~][~ 0 0 ~]"
"[0 ~ ~ 0][~ 0 ~ 0][0 ~ 0 ~][~ 0 0 ~]")
:sn (concat "[~ 0 ~ ~][0 ~ ~ 0][0 ~ 0 ~][~ ~ 0 ~]"
"[~ 0 ~ ~][0 0 ~ 0][0 ~ 0 ~][~ ~ 0 ~]")
:ch (concat "[0 ~ 0 ~][0 ~ 0 ~][0 ~ ~ ~][0 ~ 0 ~]")
:oh (concat "[~ ~ ~ ~][~ ~ ~ ~][~ ~ 0 ~][~ ~ ~ ~]"))
(make-pattern
"I Got You"
'igotyou
:bd (concat "[0 ~ ~ ~][~ ~ ~ ~][~ ~ 0 ~][~ ~ ~ ~]"
"[~ ~ 0 ~][~ ~ 0 ~][~ ~ 0 ~][~ ~ 0 ~]")
:sn "[~ ~ ~ ~][0 ~ ~ ~][~ ~ ~ ~][0 ~ ~ ~]"
:ch "[0 ~ ~ ~][0 ~ 0 ~][0 ~ ~ ~][0 ~ 0 ~]"
:oh "[~ ~ 0 ~][~ ~ ~ ~][~ ~ 0 ~][~ ~ ~ ~]")
(make-pattern
"I Got The Feelin"
'feelin
:bd (concat "[0 ~ 0 ~][~ ~ ~ ~][~ ~ 0 ~][~ ~ ~ ~]"
"[~ ~ 0 ~][~ ~ ~ ~][0 ~ ~ ~][0 ~ 0 ~]")
:sn (concat "[~ ~ ~ ~][~ ~ 0 ~][~ 0 ~ ~][~ ~ 0 ~]"
"[~ 0 ~ ~][0 0 ~ 0][~ 0 0 0][~ 0 0 0]")
:ch (concat "[0 ~ 0 ~]"))
(make-pattern
"Its A New Day"
'newday
:bd "[0 ~ 0 ~][~ ~ ~ ~][~ ~ 0 0][~ ~ ~ 0]"
:sn "[~ ~ ~ ~][0 ~ ~ ~][~ ~ ~ ~][0 ~ ~ ~]"
:ch "[0 ~ 0 ~]")
(make-pattern
"Palm Grease"
'palm
:bd (concat "[0 ~ ~ ~][~ ~ ~ ~][0 ~ ~ ~][~ ~ ~ 0]"
"[~ ~ 0 ~][~ ~ ~ ~][~ ~ ~ ~][~ ~ ~ ~]")
:sn (concat "[~ ~ ~ ~][0 ~ ~ 0][~ 0 ~ ~][0 ~ ~ 0]"
"[~ 0 ~ ~][~ ~ 0 ~][~ ~ ~ ~][~ ~ 0 ~]")
:ch (concat "[0 0 0 0][~ 0 0 ~][0 ~ 0 0][~ 0 0 ~]"
"[0 ~ 0 ~][~ ~ ~ ~][~ ~ ~ ~][~ ~ ~ ~]")
:oh (concat "[~ ~ ~ ~][~ ~ ~ ~][~ ~ 0 ~][~ ~ ~ ~]"))
(make-pattern
"Funky President"
'funkyp
:bd "[0 ~ ~ 0][~ ~ ~ 0][~ 0 0 ~][~ ~ ~ ~]"
:sn "[~ ~ ~ ~][0 ~ ~ ~][~ ~ ~ ~][0 ~ ~ ~]"
:ch "[0 ~ 0 ~][0 ~ 0 ~][0 ~ ~ ~][0 ~ 0 ~]"
:oh "[~ ~ ~ ~][0 ~ ~ ~][~ ~ 0 ~][~ ~ ~ ~]")
(make-pattern
"Funky Drummer"
'funkyd
:bd (concat "[0 ~ 0 ~][~ ~ ~ ~][~ ~ 0 ~][~ 0 ~ ~]"
"[0 ~ 0 ~][~ ~ ~ ~][~ ~ 0 ~][~ 0 ~ ~]")
:sn (concat "[~ ~ ~ ~][0 ~ ~ 0][~ 0 ~ 0][0 ~ ~ 0]"
"[~ ~ ~ ~][0 ~ ~ 0][~ 0 ~ 0][0 ~ ~ 0]")
:ch (concat "[0 0 0 0]"))
(make-pattern
"Galactic"
'galactic
:bd "xx-- x-x- xx-- -x--"
:sn "--x-"
:ch "xxxx")
;; --------------------------------------------------
;; TODO: track the beat progression to skip ahead on redefinition
;; add metro?
(defmacro defpattern (name (patterns dur) &body body)
"takes a list of patterns in the x-x-x- format OR as a list of NIL and T
and the same number of functions in BODY to play at beat x/T
(defpattern k ((\"x---\" \"xxxx\") .4)
(p time 60 60 1 0))
(defpattern k (((T NIL NIL NIL) (TTTT)) .4)
(p time 60 60 1 0))"
(let ((lets (loop :for pattern :in patterns :collect
`(,(gensym)
(if (cm:pattern? ,pattern)
,pattern
(make-cycle (if (stringp ,pattern)
(parse-pattern ,pattern)
,pattern)))))))
`(let (,@lets
(d ,dur))
(defun ,name (time)
,@(loop
:for l :in lets
:for b :in body
:collect
`(when (next ,(car l))
,b))
(aat (+ time (calc-beats ,dur))
#',name it)))))
(defmacro defbeat (name (pattern dur) &body body)
"Defines a function that can be used to play ONE pattern.
From list of NIL and T or a string like \"x--x\".
> (defbeat kick ((bd (get-pattern (pickl (list-patterns)))) .5)
(p time 60 60 .2 0))
> (kick (now))"
`(let ((d ,dur)
(ppattern
(cond
((stringp ,pattern) (parse-patternc ,pattern))
((listp ,pattern) (make-cycle ,pattern)))))
(defun ,name (time)
(when (next ppattern)
,@body)
(aat (+ time (calc-beats ,dur))
#',name it))))
| 16,236 | Common Lisp | .lisp | 461 | 30.201735 | 93 | 0.35083 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | e1e75c990450ce26e48032283fb1ff5366a6e32e7fe5403a298576cc15231d05 | 9,052 | [
-1
] |
9,053 | misc-gpu.lisp | azimut_shiny/lib/misc-gpu.lisp | (in-package :shiny)
(defvar *light-color* (v! 1 1 1))
(defvar *exposure* 1f0)
;; Range Constant Linear Quadratic
;; 3250, 1.0, 0.0014, 0.000007
;; 600, 1.0, 0.007, 0.0002
;; 325, 1.0, 0.014, 0.0007
;; 200, 1.0, 0.022, 0.0019
;; 160, 1.0, 0.027, 0.0028
;; 100, 1.0, 0.045, 0.0075
;; 65, 1.0, 0.07, 0.017
;; 50, 1.0, 0.09, 0.032
;; 32, 1.0, 0.14, 0.07
;; 20, 1.0, 0.22, 0.20
;; 13, 1.0, 0.35, 0.44
;; 7, 1.0, 0.7, 1.8
(defun-g point-light-apply ((color :vec3)
(light-color :vec3)
(light-pos :vec3)
(frag-pos :vec3)
(normal :vec3)
(constant :float)
(linear :float)
(quadratic :float))
(let* ((light-dir (normalize (- light-pos frag-pos)))
(diff (saturate (dot normal light-dir)))
(distance (length (- light-pos frag-pos)))
(attenuation (/ 1 (+ constant
(* linear distance)
(* quadratic distance distance))))
(ambient (* .1 color))
(diffuse (* diff color)))
(+ ambient diffuse)))
(defun-g dir-light-apply ((color :vec3)
(light-color :vec3)
(light-pos :vec3)
(frag-pos :vec3)
(normal :vec3))
(let* ((light-dir (normalize (- light-pos frag-pos)))
;; Diffuse shading
(diff (saturate (dot normal light-dir)))
;; combine
(ambient (* light-color .1 color))
(diffuse (* light-color diff color)))
(+ ambient diffuse)))
;;--------------------------------------------------
;; https://learnopengl.com/Advanced-Lighting/Normal-Mapping
;; "Pushing pixels" code
(defun-g norm-from-map ((normal-map :sampler-2d)
(uv :vec2))
(let* ((normal (s~ (texture normal-map uv) :xyz))
(normal (normalize (1- (* 2 normal)))))
(v! (x normal)
(y normal)
(z normal))))
;; Sometimes "y" component is wrong on the normal map.
(defun-g norm-from-map-flipped ((normal-map :sampler-2d)
(uv :vec2))
(let* ((normal (s~ (texture normal-map uv) :xyz))
(normal (normalize (1- (* 2 normal)))))
(v! (x normal)
(- (y normal))
(z normal))))
;; ?
;; From "pushing pixels" don't remember why it's needed
(defun-g treat-uvs ((uv :vec2))
(v! (x uv) (- 1.0 (y uv))))
;;--------------------------------------------------
;; https://learnopengl.com/Advanced-Lighting/Parallax-Mapping
;; vec3 viewDir = normalize(fs_in.TangentViewPos - fs_in.TangentFragPos);
(defun-g parallax-mapping ((uv :vec2)
(view-dir :vec3)
(depth-map :sampler-2d)
(height-scale :float))
(let* ((height (x (texture depth-map uv)))
(p (* (* height height-scale)
(/ (s~ view-dir :xy)
(z view-dir)))))
(- uv p)))
;; https://catlikecoding.com/unity/tutorials/rendering/part-20/
;; Limit lenght of 1
(defun-g parallax-mapping-offset ((uv :vec2)
(view-dir :vec3)
(depth-map :sampler-2d)
(height-scale :float))
(let* ((height (x (texture depth-map uv)))
(height (- height .5))
(p (* height height-scale)))
(+ uv (* (s~ view-dir :xy) p))))
(defun-g parallax-mapping-offset-flipped ((uv :vec2)
(view-dir :vec3)
(depth-map :sampler-2d)
(height-scale :float))
(let* ((height (- 1 (x (texture depth-map uv))))
(height (- height .5))
(p (* height height-scale)))
(+ uv (* (s~ view-dir :xy) p))))
;;--------------------------------------------------
;; https://catlikecoding.com/unity/tutorials/rendering/part-14/
;; (Euclidean) Distance (aka radial/range) based fog:
;; more realistic and expensive than using depth
;; TODO: add depth and defered fog versions
(defun-g fog-linear ((frag-pos :vec3)
(cam-pos :vec3)
(start :float)
(end :float))
(let* ((view-distance (length (- frag-pos cam-pos)))
(fog-factor
(+ (* view-distance (/ -1 (- end start)))
(/ end (- end start)))))
fog-factor))
(defun-g fog-exp ((frag-pos :vec3)
(cam-pos :vec3)
(density :float))
(let ((view-distance (length (- frag-pos cam-pos))))
(exp2 (- (* view-distance (/ density (log 2)))))))
(defun-g fog-exp2 ((frag-pos :vec3)
(cam-pos :vec3)
(density :float))
(let* ((view-distance (length (- frag-pos cam-pos)))
(fog-density
(* (/ density (sqrt (log 2))) view-distance))
(fog-factor
(exp2 (- (* fog-density fog-density)))))
fog-factor))
;;--------------------------------------------------
;; Versions that apply the fog and returns the final color
(defun-g fog-linear-apply ((color :vec3)
(fog-color :vec3)
(frag-pos :vec3)
(cam-pos :vec3)
(start :float)
(end :float))
(let ((fog-factor (fog-linear frag-pos cam-pos start end)))
(mix fog-color color (saturate fog-factor))))
(defun-g fog-exp-apply ((color :vec3)
(fog-color :vec3)
(frag-pos :vec3)
(cam-pos :vec3)
(density :float))
(let ((fog-factor (fog-exp frag-pos cam-pos density)))
(mix fog-color color (saturate fog-factor))))
(defun-g fog-exp2-apply ((color :vec3)
(fog-color :vec3)
(frag-pos :vec3)
(cam-pos :vec3)
(density :float))
(let ((fog-factor (fog-exp2 frag-pos cam-pos density)))
(mix fog-color color (saturate fog-factor))))
;;--------------------------------------------------
;; http://iquilezles.org/www/articles/fog/fog.htm
;; "For example, the color of the fog can tell us about the strengh of the
;; sun. Even more, if we make the color of the fog not constant but
;; orientation dependant we can introduce an extra level of realism to
;; the image. For example, we can change the typical bluish fog color to
;; something yellowish when the view vector aligns with the sun
;; direction. This gives a very natural light dispersion effect. One
;; would argue that sucha an effect shouldn't be called fog but
;; scattering, and I agree, but in the end of the day one simply has to
;; modify a bit the fog equation to get the effect done."
(defun-g apply-fog ((color :vec3)
(density :float)
(distance :float) ;; camera to point distance
(ray-dir :vec3) ;; camera to point vector
(sun-dir :vec3)) ;; sun light direction
(let* ((fog-amount (- 1 (exp (* (- distance) density))))
(sun-amount (max (dot ray-dir sun-dir) 0))
(fog-color (mix (v! .5 .6 .7) ;; blueish
(v! 1 .9 .7) ;; yellowish
(pow sun-amount 8))))
(mix color fog-color fog-amount)))
;; Modified version, with more generic args (works?)
(defun-g apply-fog ((color :vec3)
(density :float)
(frag-pos :vec3)
(cam-pos :vec3)
(sun-pos :vec3))
(let* ((distance (length (- cam-pos frag-pos)))
(ray-dir (normalize (- cam-pos frag-pos)))
(sun-dir (normalize (- sun-pos frag-pos)))
(fog-amount (- 1 (exp (* (- distance) density))))
(sun-amount (max (dot ray-dir sun-dir) 0))
(fog-color (mix (v! .5 .6 .7) ;; blueish
(v! 1 .9 .7) ;; yellowish
(pow sun-amount 8))))
(mix color fog-color fog-amount)))
;; Height fog - IQ
(defun-g apply-fog ((color :vec3)
(fog-color :vec3)
(distance :float)
(cam-pos :vec3)
(frag-pos :vec3))
(let* ((a .03) ;; .06 - .002
(b .3) ;; .3 - .02
(cam-dir (normalize (- frag-pos cam-pos)))
(fog-amount (/ (* (/ a b)
(exp (* (- (y cam-pos)) b))
(- 1 (exp (* (- distance)
(y cam-dir)
b))))
(y cam-dir))))
(mix color fog-color (saturate fog-amount))))
;;--------------------------------------------------
;; http://michael-david-palmer.com/fisa/UDK-2010-07/Engine/Shaders/HeightFogCommon.usf
;; https://docs.unrealengine.com/en-us/Engine/Actors/FogEffects/HeightFog
;; Calculates fogging from exponential height fog,
;; returns fog color in rgb, fog factor in a.
;; Fog Height Falloff: Height density factor, controls how the density
;; increases as height decreases. Smaller values make the
;; transition larger.
;; x - FogDensity *
;; exp2(-FogHeightFalloff *
;; (CameraWorldPosition.z - FogHeight))
;; y - FogHeightFalloff
;; z - CosTerminatorAngle
(defun-g get-exponential-height-fog ((frag-pos :vec3)
(cam-pos :vec3)
(fog-params :vec3)
(light-pos :vec3))
(let* ((cam-to-receiver (- frag-pos cam-pos))
(line-integral (* (x fog-params) (length cam-to-receiver)))
(line-integral
(if (> (abs (z cam-to-receiver)) .0001)
(* line-integral (/ (- 1 (exp2 (* (- (y fog-params)) (z cam-to-receiver))))
(* (y fog-params) (z cam-to-receiver))))
line-integral))
;; 1 in the direction of the light vector, -1 in the opposite direction
(cos-light-angle (dot (normalize (- light-pos frag-pos))
(normalize cam-to-receiver)))
(fog-color
(if (< cos-light-angle (z fog-params))
(mix (v! .5 .6 .7)
(* .5 (+ (v! .5 .6 .7) (v! .1 .1 .1)))
(vec3 (saturate (/ (1+ cos-light-angle)
(1+ (z fog-params))))))
(let ((alpha (saturate (/ (- cos-light-angle (z fog-params))
(- 1 (z fog-params))))))
(mix (* .5 (+ (v! .5 .6 .7) (v! .1 .1 .1)))
(v! .1 .1 .1)
(vec3 (* alpha alpha))))))
(fog-factor (saturate (exp2 (- line-integral)))))
(v! (* fog-color (- 1 fog-factor)) fog-factor)))
;;--------------------------------------------------
;; PBR - BRDF
;; https://learnopengl.com/PBR/Lighting
(defun-g fresnel-schlick ((cos-theta :float)
(f0 :vec3))
(+ f0
(* (- 1 f0)
(pow (- 1 cos-theta) 5))))
(defun-g distribution-ggx ((n :vec3)
(h :vec3)
(roughness :float))
(let* ((a (* roughness roughness))
(a2 (* a a))
(n-dot-h (max (dot n h) 0))
(n-dot-h2 (* n-dot-h n-dot-h))
(num a2)
(denom (1+ (* n-dot-h2 (1- a2))))
(denom (* +PI+ denom denom)))
(/ num denom)))
(defun-g geometry-schlick-ggx ((n-dot-v :float)
(roughness :float))
(let* ((r (1+ roughness))
(k (/ (* r r) 8))
(num n-dot-v)
(denom (+ (* n-dot-v (- 1 k))
k)))
(/ num denom)))
(defun-g geometry-smith ((n :vec3)
(v :vec3)
(l :vec3)
(roughness :float))
(let* ((n-dot-v (max (dot n v) 0))
(n-dot-l (max (dot n l) 0))
(ggx2 (geometry-schlick-ggx n-dot-v roughness))
(ggx1 (geometry-schlick-ggx n-dot-l roughness)))
(* ggx1 ggx2)))
(defun-g pbr-direct-lum ((light-pos :vec3)
(frag-pos :vec3)
(v :vec3)
(n :vec3)
(roughness :float)
(f0 :vec3)
(metallic :float)
(color :vec3))
(let* ((l (normalize (- light-pos frag-pos)))
(h (normalize (+ v l)))
(distance (length (- light-pos frag-pos)))
(radiance (v! 5 5 5))
;; pbr - cook-torrance brdf
(ndf (distribution-ggx n h roughness))
(g (geometry-smith n v l roughness))
(f (fresnel-schlick (max (dot h v) 0) f0))
;;
(ks f)
(kd (- 1 ks))
(kd (* kd (- 1 metallic)))
;;
(numerator (* ndf g f))
(denominator (+ .001
(* (max (dot n v) 0)
(max (dot n l) 0)
4)))
(specular (/ numerator denominator))
;; add to outgoing radiance lo
(n-dot-l (max (dot n l) 0))
(lo (* (+ specular (/ (* kd color) +PI+))
radiance
n-dot-l)))
lo))
(defun-g pbr-point-lum ((light-pos :vec3)
(frag-pos :vec3)
(v :vec3)
(n :vec3)
(roughness :float)
(f0 :vec3)
(metallic :float)
(color :vec3))
(let* ((l (normalize (- light-pos frag-pos)))
(h (normalize (+ v l)))
(distance (length (- light-pos frag-pos)))
(constant 1f0)
(linear .7)
(quadratic 1.8)
(attenuation (/ 1f0 (+ constant
(* linear distance)
(* quadratic distance distance))))
(light-color (v! .9 .9 .9))
(radiance light-color attenuation)
;; pbr - cook-torrance brdf
(ndf (distribution-ggx n h roughness))
(g (geometry-smith n v l roughness))
(f (fresnel-schlick (max (dot h v) 0) f0))
;;
(ks f)
(kd (* (- (vec3 1) ks)
(- 1 metallic)))
;;
(numerator (* ndf g f))
(denominator (* (max (dot n v) 0)
(max (dot n l) 0)
4))
(specular (/ numerator (max denominator .001)))
;; add to outgoing radiance lo
(n-dot-l (max (dot n l) 0)))
(* (+ specular (/ (* kd color) +PI+))
radiance
n-dot-l)))
;;--------------------------------------------------
;; Billboarding
(defun-g billboard-vert ((pos :vec3)
&uniform
(time :float)
(world-view :mat4))
(* world-view (v! 0 -6 -50 1)))
(defun-g billboard-frag ((uv :vec2)
&uniform
(tex :sampler-2d)
(time :float))
(let* ((color (texture tex uv)))
(values color
(v! (x color) 0 0 (w color)))))
(defun-g billboard-geom (&uniform (camera-pos :vec3)
(view-clip :mat4))
(declare (output-primitive :kind :triangle-strip
:max-vertices 4))
(let* ((p (s~ (gl-position (aref gl-in 0)) :xyz))
(to-camera (normalize (- camera-pos p)))
(up (v! 0 1 0))
(right (cross to-camera up)))
;;
(decf p (* 9 .5 right))
(emit ()
(* view-clip (v! p 1))
(v! 0 0))
;;
(incf (y p) 9f0)
(emit ()
(* view-clip (v! p 1))
(v! 0 1))
;;
(decf (y p) 9f0)
(incf p (* right 9))
(emit ()
(* view-clip (v! p 1))
(v! 1 0))
;;
(incf (y p) 9f0)
(emit ()
(* view-clip (v! p 1))
(v! 1 1))
(end-primitive)
(values)))
(defpipeline-g billboard-pipe (:points)
:vertex (billboard-vert :vec3)
:geometry (billboard-geom)
:fragment (billboard-frag :vec2))
;;--------------------------------------------------
;; glsl-atmosphere
;; https://github.com/wwwtyro/glsl-atmosphere/
;; RSI
;; ray-sphere intersection that assumes
;; the sphere is centered at the origin.
;; No intersection when result.x > result.y
(defun-g rsi ((r0 :vec3)
(rd :vec3)
(sr :float))
(let* ((a (dot rd rd))
(b (* 2 (dot rd r0)))
(c (- (dot r0 r0) (* sr sr)))
(d (- (* b b) (* 4 a c))))
(if (< d 0)
(v! 100000 -100000)
(v! (/ (- (- b) (sqrt d))
(* 2 a))
(/ (+ (- b) (sqrt d))
(* 2 a))))))
;; vec3 r normalized ray direction, typically a ray cast from the observers eye through a pixel
;; vec3 r0 ray origin in meters, typically the position of the viewer's eye
;; vec3 pSun the position of the sun
;; float iSun intensity of the sun
;; float rPlanet radius of the planet in meters
;; float rAtoms radius of the atmosphere in meters
;; vec3 kRlh Rayleigh scattering coefficient
;; vec3 kMie Mie scattering coefficient
;; float shRlh Rayleigh scale height in meters
;; float shMie Mie scale height in meters
;; float g Mie preferred scattering direction
(defun-g atmosphere ((r :vec3)
(r0 :vec3)
(p-sun :vec3)
(i-sun :float)
(r-planet :float)
(r-atmos :float)
(k-rlh :vec3)
(k-mie :float)
(sh-rlh :float)
(sh-mie :float)
(g :float)
(i-steps :uint)
(j-steps :uint))
(let* (;;(i-steps 3) ;; 16
;;(j-steps 2) ;; 8
(pi +PI+)
;; Normalize the sun and view directions
(p-sun (normalize p-sun))
(r (normalize r))
;; Calculate the step size of the
;; primary ray.
(p (rsi r0 r r-atmos)))
(if (> (x p) (y p))
(vec3 0f0)
(let* ((p (v! (x p)
(min (y p) (x (rsi r0 r r-planet)))))
(i-step-size (/ (- (y p) (x p))
i-steps))
;; Initialize the primary ray time.
(i-time 0f0)
;; Initialize accumulators for
;; Rayleigh and Mie scattering
(total-rlh (vec3 0f0))
(total-mie (vec3 0f0))
;; Initialize optical depth accum
;; for the primary ray.
(i-od-rlh 0f0)
(i-od-mie 0f0)
;; Calculate the Rayleigh
;; and Mie phases
(mu (dot r p-sun))
(mumu (* mu mu))
(gg (* g g))
(p-rlh (* (/ 3 (* 16 pi))
(+ 1 mumu)))
(p-mie (/ (* (/ 3 (* 8 pi))
(* (- 1 gg) (+ 1 mumu)))
(* (pow (- (+ 1 gg) (* 2 mu g))
1.5)
(* 2 gg))))
(i 0))
;; sample the primary key
(dotimes (i i-steps)
(let* (;; Calculate the primary ray sample position
(i-pos (+ r0 (* r (+ i-time (* i-step-size .5)))))
;; Calculate the height of the sample
(i-height (- (length i-pos) r-planet))
;; Calculate the optical depth of the Rayleigh
;; and Mie scattering for this step.
(od-step-rlh (* i-step-size (exp (/ (- i-height) sh-rlh))))
(od-step-mie (* i-step-size (exp (/ (- i-height) sh-mie)))))
;; Accumulate optical depth.
(incf i-od-rlh od-step-rlh)
(incf i-od-mie od-step-mie)
(let (;; Calculate the step size of the secondary ray
(j-step-size (/ (y (rsi i-pos p-sun r-atmos)) j-steps))
;; Initialize the secondary ray time
(j-time 0f0)
;; Initialize optical depth accumulators for the sec ray
(j-od-rlh 0f0)
(j-od-mie 0f0))
;; Sample the seconday ray
(dotimes (j j-steps)
(let* (;; Calculate the secondary ray sample position
(j-pos (+ i-pos (* p-sun (+ j-time (* j-step-size .5)))))
;; Calculate the height of the sample
(j-height (- (length j-pos) r-planet)))
;; Accumulate the optical depth
(incf j-od-rlh (* j-step-size (exp (/ (- j-height) sh-rlh))))
(incf j-od-mie (* j-step-size (exp (/ (- j-height) sh-mie))))
;; Increment the secondary ray time
(incf j-time j-step-size)))
;; Calculate attenuation
(let ((attn (exp (- (+ (* k-mie (+ i-od-mie j-od-mie))
(* k-rlh (+ i-od-rlh j-od-rlh)))))))
;; Accumulate scattering
(incf total-rlh (* od-step-rlh attn))
(incf total-mie (* od-step-mie attn))
;; Increment the primary ray time
(incf i-time i-step-size)))))
;; Calculate and return the final color
(* i-sun (+ (* p-rlh k-rlh total-rlh)
(* p-mie k-mie total-mie)))))))
;;--------------------------------------------------
;; WORKS???
;; http://www.voidcn.com/article/p-nvhpdsyj-yy.html
(defun-g linear-eye-depth ((d :float))
(let* ((n .1)
(f 400f0)
(zz (/ (/ (- 1 (/ f n)) 2) f))
(zw (/ (/ (+ 1 (/ f n)) 2) f)))
(/ 1 (+ (* zz d) zw))))
(defun-g read-depth ((z :float))
(let* ((pfn (+ 400 .1))
(mfn (- 400 .1))
(coef (* 2f0 .1)))
(/ coef (- pfn (* z mfn)))))
;; https://learnopengl.com/Advanced-OpenGL/Depth-testing
;; Because the linearized depth values range from near to far most of
;; its values will be above 1.0 and displayed as completely white. By
;; dividing the linear depth value by far in the main function we
;; convert the linear depth value to roughly the range [0, 1]. This
;; way we can gradually see the scene become brighter the closer the
;; fragments are to the projection frustum's far plane, which is
;; better suited for demonstration purposes.
(defun-g linearize-depth ((depth :float))
(let* ((near 0.1)
(far 400f0)
(z (- (* depth 2.0) 1.0)))
(/ (* 2.0 (* near far))
(- (+ far near) (* z (- far near))))))
;; Three.js - packaging.glsl.js
(defun-g view-zto-orthographic-depth ((view-z :float)
(near :float)
(far :float))
(/ (+ view-z near)
(- near far)))
(defun-g perspective-depth-to-view-z ((inv-clip-z :float)
(near :float)
(far :float))
(/ (* near far)
(- (* (- far near) inv-clip-z) far)))
(defun-g read-depth ((depth-sampler :sampler-2d)
(coord :vec2)
(camera-near :float)
(camera-far :float))
(let* ((frag-coord-z (x (texture depth-sampler coord)))
(view-z (perspective-depth-to-view-z frag-coord-z
camera-near
camera-far)))
(view-zto-orthographic-depth view-z camera-near camera-far)))
;;--------------------------------------------------
(defun-g fbm-hash ((p :vec2))
(fract
(* (sin (dot p (v! 41 289)))
45758.5453)))
(defun-g combine-god-frag ((uv :vec2)
&uniform
(sam-god :sampler-2d)
(sam :sampler-2d))
(let* ((color (mix (s~ (texture sam uv) :xyz)
(* *light-color* (s~ (texture sam-god uv) :xyz))
.1))
;; (color (+ (s~ (texture sam uv) :xyz)
;; (* *light-color* (s~ (texture sam-god uv) :xyz))))
(ldr (nineveh.tonemapping:tone-map-reinhard color *exposure*))
(luma (rgb->luma-bt601 ldr)))
(v! ldr luma)))
(defpipeline-g combine-god-pipe (:points)
:fragment (combine-god-frag :vec2))
(defun-g god-rays-frag ((uv :vec2)
&uniform
(res :vec2)
(time :float)
(sun-pos :vec2)
(sam :sampler-2d))
(let* (;;(uv (/ (s~ gl-frag-coord :xy) res))
;; (v2:+s (v2:*s (v2:/ (screen-coord (resolution (current-viewport)) (v! 0 0 -30))
;; (resolution (current-viewport)))
;; 2f0)
;; -1f0)
(uv uv)
(samples 10f0)
(decay .974)
(exposure .24)
(density .93)
(weight .36)
(color (s~ (texture sam uv) :xyz))
(occ (x color))
(obj (y color))
(dtc (* (- uv sun-pos)
(/ 1f0 samples)))
(illumdecay .4f0)
(dither (fbm-hash (+ uv (fract time)))))
(dotimes (i samples)
(decf uv dtc)
(let ((s (x (texture sam (+ (* dither dtc)
uv)))))
(multf s (* illumdecay weight))
(incf occ s)
(multf illumdecay decay)
))
(v! (+ (v! 0 0 0)
(* occ exposure))
1)
;;(vec4 occ)
))
;; https://stackoverflow.com/questions/3792481/how-to-get-screen-coordinates-from-a-3d-point-opengl
;; You then need to transform the [-1:1]^3 cube to window coordinates
;; by applying the Viewport transformation to it. window.x =
;; viewport.x + viewport.width * (cube.x+1)/2
(defun screen-coord (res &optional (pos (v! 0 0 -10)))
(let* ((pos4 (v! pos 1))
(cpos4 (m4:*v (world->view *currentcamera*)
pos4))
(cpos4 (m4:*v (projection *currentcamera*)
cpos4))
(w (w cpos4))
(ndc (v4:/s cpos4 w)))
;; https://stackoverflow.com/questions/42751427/transformations-from-pixels-to-ndc
(v2:abs (v2:/ (v! (+ (* (x res) .5 (x ndc))
(+ (* (x res) .5 ) 0))
(+ (* (y res) .5 (y ndc))
(+ (* (y res) .5))))
res))
;; https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glViewport.xml
;; (v! (+ (* (+ 1 (x ndc)) (/ (x res) 2)))
;; (+ (* (+ 1 (y ndc)) (/ (y res) 2))))
;; screen.x = ((view.w * 0.5) * ndc.x) +
;; ((w * 0.5) + view.x)
;; screen.y = ((view.h * 0.5) * ndc.y) +
;; ((h * 0.5) + view.y)
;;
;; (v2:abs (v2:/ (v! (+ .5 (* (x res)
;; (/ (+ 1 (x ndc)) 2)))
;; (+ .5 (* (y res)
;; (/ (- 1 (y ndc)) 2))))
;; res))
;; (v2:* (v2:+ (v2:/s (s~ cpos4 :xy) w)
;; (v! 1 1))
;; (v2:*s res .5))
))
;;--------------------------------------------------
;; Pipeline to create a BRDF 2d lut
;;--------------------------------------------------
;; ON INIT:
;;
;; (unless *f-brdf*
;; (setf *f-brdf*
;; (make-fbo (list 0 :element-type :rg16f :dimensions '(512 512))))
;; (setf *t-brdf* (attachment-tex *f-brdf* 0))
;; (setf *s-brdf*
;; (cepl:sample *t-brdf* :wrap :clamp-to-edge
;; :minify-filter :linear)))
;; ON DRAW LOOP:
;;
;; (unless *brdf*
;; (setf *brdf* T)
;; (setf (resolution (current-viewport)) (v! 512 512))
;; (map-g-into *f-brdf* #'brdf-pipe *bs*))
(defun-g integrate-brdf ((n-dot-v :float)
(roughness :float))
;; You might've recalled from the theory tutorial that the geometry
;; term of the BRDF is slightly different when used alongside IBL as
;; its k variable has a slightly different interpretation:
(labels ((geometry-schlick-ggx ((n-dot-v :float)
(roughness :float))
(let* ((a roughness)
(k (/ (* a a) 2))
(nom n-dot-v)
(denom (+ k (* n-dot-v (- 1 k)))))
(/ nom denom)))
(geometry-smith ((n :vec3)
(v :vec3)
(l :vec3)
(roughness :float))
(let* ((n-dot-v (max (dot n v) 0))
(n-dot-l (max (dot n l) 0))
(ggx2 (geometry-schlick-ggx n-dot-v roughness))
(ggx1 (geometry-schlick-ggx n-dot-l roughness)))
(* ggx1 ggx2))))
(let* ((v (v! (sqrt (- 1 (* n-dot-v n-dot-v)))
0
n-dot-v))
(a 0f0)
(b 0f0)
(n (v! 0 0 1)))
(dotimes (i 1024)
(let* (;; generates a sample vector that's biased towards the
;; preferred alignment direction (importance sampling).
(xi (hammersley-nth-2d 1024 i))
(h (importance-sample-ggx xi n roughness))
(l (normalize (+ (- v) (* 2 (dot v h) h))))
(n-dot-l (max (z l) 0))
(n-dot-h (max (z h) 0))
(v-dot-h (max (dot v h) 0)))
(when (> n-dot-l 0)
(let* ((g (geometry-smith n v l roughness))
(g-vis (/ (* g v-dot-h) (* n-dot-h n-dot-v)))
(fc (pow (- 1 v-dot-h) 5)))
(incf a (* (- 1 fc) g-vis))
(incf b (* fc g-vis))))))
(divf a 1024f0)
(divf b 1024f0)
(v! a b))))
(defun-g brdf-frag ((uv :vec2))
(integrate-brdf (x uv) (y uv)))
(defpipeline-g brdf-pipe (:points)
:fragment (brdf-frag :vec2))
;;--------------------------------------------------
;; Defered fog
;; https://github.com/Unity-Technologies/PostProcessing/
;; Hardcoded to work ONLY with perspective projection
(defun-g linear-01-depth ((z :float))
(let* ((far 400f0)
(near .1)
(z (* z (- 1 (/ far near)))))
(/ (+ z (/ far near)))))
;; PostProcessing/Shaders/StdLib.hlsl
;; PostProcessing/Shaders/Builtins/DeferredFog.shader
;; PostProcessing/Shaders/API/OpenGL.hlsl
;; PostProcessing/Shaders/Builtins/Fog.hlsl
(defun-g compute-fog-distance ((depth :float))
(let* ((far 400f0)
(near .1)
(dist (- (* depth far) near)))
dist))
;;
(defun-g compute-fog-exp2 ((z :float)
(density :float))
(let* ((fog 0f0)
(fog (* density z))
(fog (exp2 (* (- fog) fog))))
(saturate fog)))
(defun-g defered-fog ((fog-color :vec3)
(uv :vec2)
(tex :sampler-2d)
(depth-tex :sampler-2d))
(let* ((color (s~ (texture tex uv) :xyz))
(depth (x (texture depth-tex uv)))
(depth (linear-01-depth depth))
(dist (compute-fog-distance depth))
(fog (- 1f0 (compute-fog-exp2 dist .1))))
(mix color fog-color fog)))
| 31,291 | Common Lisp | .lisp | 763 | 29.165138 | 99 | 0.45462 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | f1f3a6152e67a83e7730e206b61babb07ca58d82ce9d684331b15e631c8f3b1c | 9,053 | [
-1
] |
9,054 | gme.lisp | azimut_shiny/lib/gme.lisp | (in-package :shiny)
;;::::::::::::::::::::::::::::::::::::::::::::::::::
;; Game-Music-Emu - cl-gme - helpers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; This is a way to load and play around with gme
;; Another approach possible might be load the whole file as many times
;; as voices are on the file and then use different helpers to play them.
;; Might be like that the transitions between adding voices and removing them
;; would be more seemles...dunno.
;; TODO: shorted hash keys
;;(ql:quickload :cl-gme/incudine)
;; Flip-flop buffer to avoid cuts while loading AND
;; ...still being able to free old cuts
(defvar *loading* (make-hash-table :test #'equal)
"temporal cache were new gme tracks are initially loaded
before being send to a dsp. KEY is the filename concatenated
with the number of node where is playing. VALUE are the actual
buffer objects.")
(defvar *playing* (make-hash-table :test #'equal)
"temporal cache")
(defun list-loading ()
(alexandria:maphash-keys #'print *loading*))
(defun list-playing ()
(alexandria:maphash-keys #'print *playing*))
(defun gmeclean ()
"frees global hashes of buffers and recreates them"
(alexandria:maphash-values #'incudine:free *playing*)
(clrhash *playing*)
(alexandria:maphash-values #'incudine:free *loading*)
(clrhash *loading*))
(defun gmebuffer (filename &key (len 1) (track-number 0) (offset 0) voices)
"returns a incudine buffer with the gme FILENAME loaded into it"
(assert (probe-file filename))
(let* ((rate 44100);; v
(chunk 4410) ;; This value is hardcoded on the .c file
(frames (* len 10 chunk))
(offset (* offset 10 chunk))
(buf (make-buffer (/ frames 2) :channels 2 :sample-rate rate))
(voices (ensure-list voices)))
(setf (buffer-file buf) (pathname filename))
(cl-gme:with-track (gmefile filename track-number :rate rate :voices voices)
(cl-gme::gmefile-to-buffer (buffer-data buf)
(cffi:mem-ref gmefile :pointer)
frames
offset))
(normalize-buffer buf .5)))
(defun gmeplay (filename node track-number
&key (amp 1) (rate 1)
(dur 1) (offset 0) voices
(left 1) (right 1)
(lpf 0) (hpf 0) (bpf 0)
(lpr .5) (hpr .5) (bpr .5)
(downsamp 0)
(loop-p t) load-only
(fade-curve 3) (fade-time 0f0))
"plays provided FILENAME TRACK-NUMBER in NODE id,
takes care of loading the file and swapping buffers for live coding
LOAD-ONLY just put the buffer in the global hash, do not play it
(gmeplay \"/home/sendai/Downloads/sf2/ff3.nsf\" 2 15
:amp .1
:dur 20
:offset 10
:voices 2
:rate 1
:fade-time 1
:fade-curve 2)"
(declare (type integer node track-number dur offset)
(type number rate amp)
(type boolean loop-p load-only))
(let ((alive (node-id (node node)))
(hashkey (format nil "~a~a" filename node))
(voices (ensure-list voices)))
(setf (gethash hashkey *loading*)
(gmebuffer filename
:track-number track-number
:len dur
:voices voices
:offset offset))
(unless load-only
(if alive
(set-controls
node
:buf (gethash hashkey *loading*)
:rate rate
:loop-p loop-p
:fade-curve fade-curve
:fade-time fade-time
:left left
:right right
:lpf lpf :hpf hpf :bpf bpf
:lpr lpr :hpr hpr :bpr bpr
:downsamp downsamp
:amp amp)
(bplay (gethash hashkey *loading*) rate 0 loop-p
:id node
:left left
:right right
:lpf lpf :hpf hpf :bpf bpf
:lpr lpr :hpr hpr :bpr bpr
:downsamp downsamp
:fade-curve fade-curve
:fade-time fade-time
:amp amp)))
(rotatef (gethash hashkey *loading*)
(gethash hashkey *playing*))
(incudine:free (gethash hashkey *loading*))))
| 4,316 | Common Lisp | .lisp | 106 | 31.179245 | 80 | 0.571565 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 9438ffe72e8cd3cc1f3abda4ed64cafa9526207134ce6f7015e78c6a1d2bb9ec | 9,054 | [
-1
] |
9,055 | buffers.lisp | azimut_shiny/lib/buffers.lisp | (in-package :shiny)
;; TODO:
;; - right now it uses (at) to stop (word-play),
;; might be buffer-play can support other thing
;; ... I could have used (buffer-read) and (phasor-loop)
;; ... on the other hand it makes easy to play backwards
;; - Make it quickload-able
;; - Add slice support. With start and stop as relative values
(defvar *buffers* (make-hash-table :test #'equal)
"Global cache for all buffers loaded through (bbufer-load).
Key is the (file-namestring). Example: \"sample.wav\"
Value is the actual buffer object.")
(defvar *sample-words* (make-hash-table :test #'equal))
(defvar *instruments* (make-hash-table))
(defvar *buffer-sets* (make-hash-table :test #'equal)
"stores the sets of each buffer, KEY is the file-namestring VALUE
is an (N 2) array")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; DSPs helpers - These assume a blocksize of 1
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-vug buffer-loop-play ((buffer buffer)
rate
start-pos
loopstart loopend)
(with-samples ((frame (phasor-loop rate start-pos loopstart loopend)))
(buffer-read buffer frame :interpolation :cubic)))
(dsp! play-lsample-f ((buf buffer) dur amp start-pos loopstart loopend rate
left right
lpf hpf bpf
lpr hpr bpr
reson resonq
(downsamp fixnum)
atk sus rel)
"Plays given buffer for DUR in seconds. If greater than buffer loops
from LOOPSTART to LOOPEND frame. It can be used to play an instrument
sample and sustain the looped part. Or to play a slice of audio alone from
the rest of the buffer."
(:defaults nil 1 .5 0 0 0 1
1 1
0 0 0
1 1 1
0 2
0
0 .9 .1)
(with-samples ((in (buffer-loop-play buf rate start-pos loopstart loopend))
(in (* in (envelope (make-envelope '(0 1 1 0) (list atk sus rel))
1 dur #'incudine:free))))
(incudine.vug:maybe-expand in)
;;
(unless (= 0d0 reson)
(setf in (incudine.vug:reson in reson resonq)))
;;
(unless (= 0 downsamp)
(setf in (incudine.vug:downsamp downsamp in)))
;;
(unless (= 0d0 lpf)
(setf in (incudine.vug:lpf in lpf lpr)))
(unless (= 0d0 hpf)
(setf in (incudine.vug:hpf in hpf hpr)))
(unless (= 0d0 bpf)
(setf in (incudine.vug:hpf in bpf bpr)))
(out (* amp (* left in))
(* amp (* right in)))))
(dsp! bplay ((buf buffer)
rate start-pos
(loop-p boolean) amp left right custom-id
lpf hpf bpf
lpr hpr bpr end-frame
(downsamp fixnum) reson resonq)
"Plays given buffer without control for how long is played, it gracefully
accepts negative rates or audio filters."
(:defaults (incudine:incudine-missing-arg "BUFFER")
1 0
NIL 1 1 1 1
0 0 0
2 2 2 0
0 0 2)
(with-samples
((in (buffer-play buf rate start-pos loop-p #'incudine:free end-frame)))
(incudine.vug:maybe-expand in)
(unless (= 0d0 reson)
(setf in (incudine.vug:reson in reson resonq)))
;;
(unless (= 0 downsamp)
(setf in (incudine.vug:downsamp downsamp in)))
;;
(unless (= 0d0 lpf)
(setf in (incudine.vug:lpf in lpf lpr)))
(unless (= 0d0 hpf)
(setf in (incudine.vug:hpf in hpf hpr)))
(unless (= 0d0 bpf)
(setf in (incudine.vug:hpf in bpf bpr)))
(out (* amp (* left in))
(* amp (* right in)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Buffer helpers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun list-buffers ()
(alexandria:hash-table-keys *buffers*))
(defun clean-buffers ()
(alexandria:maphash-values (lambda (x) (incudine:free x)) *buffers*)
(clrhash *buffers*))
(defun list-words ()
(alexandria:hash-table-keys *sample-words*))
(defun node-alive (id)
(node-id (node id)))
(defun amp-node
(time id &key (center 1f0) (radius .1) (period 1) (life 3))
(declare (sample time) (integer id))
"sends random rate changes to the node ID
LIFE is needed to avoid early check of the node"
(let ((alive (node-id (node id))))
(when (or alive (> life 0))
(set-control
id
:amp (funcall (cm:pick '+ '+ '+ '+ '+ '+ '-)
(cosr center radius 10)))
(aat (+ time (* *sample-rate* period))
#'amp-node it id :life (- life 1)))))
(defun corrupt-node
(time id &key (center 1f0) (radius .1) (period 1) (life 3))
(declare (sample time) (integer id))
"sends random rate changes to the node ID
LIFE is needed to avoid early check of the node"
(let ((alive (node-id (node id))))
(when (or alive (> life 0))
(set-control
id
:rate (funcall (cm:pick '+ '+ '+ '+ '+ '+ '-)
(cosr center radius 10)))
(aat (+ time (* *sample-rate* period))
#'corrupt-node it id :life (- life 1)))))
(defun pitch-to-ratio (p)
(declare (integer p))
"relative midi pitch to frequency ratio"
(expt 2 (/ p 12)))
(defun beat-to-ratio (beat-length sample-rate dur)
(declare (sample sample-rate) (number beat-length dur))
"given a BEAT-LENGTH and DURation in seconds returns a rate"
(let* ((samples-to-play (* dur sample-rate))
(samples-per-beat (/ samples-to-play beat-length))
(rate (/ samples-per-beat sample-rate)))
rate))
(defun bbuffer-load (filename &optional alias-key)
"buffer-load wrapper for global hash caching and easy access
FILENAME is a normal string of a path where to load the file
(bbuffer-load \"/home/sendai/curso/furi-dream-cc.wav\")"
(declare (type (or string pathname) filename))
(let* ((filepath (resolve-path filename))
(hkey (if alias-key
alias-key
(file-namestring filepath)))
(buf (gethash hkey *buffers*)))
(if (not buf)
(setf (gethash hkey *buffers*)
(buffer-load filepath))
buf)))
;;--------------------------------------------------
;; Single buffer play
(defun bbplay (buf &key (rate 1d0 rate-p) (rpitch 0 rpitch-p) (beat-length 1f0 beat-length-p)
(start-pos 0d0) (loop-p nil) (amp 1d0) (id 2 id-p)
(lpf 0) (hpf 0) (bpf 0)
(left 1d0) (right 1d0) (downsamp 1 downsamp-p) (pan .5 pan-p)
(lpr 2) (hpr 2) (bpr 2)
(reson 0) (resonq 2)
(end-pos 0 end-pos-p)
(set 0 set-p))
(declare (fixnum rpitch)
(boolean loop-p)
(number lpf hpf bpf lpr hpr bpr pan
reson resonq
end-pos
rate beat-length
amp left right)
(unsigned-byte downsamp set id))
"plays the provided buffer either by
PAN value between 0f0 and 1f0
RATE plays the buffer to play at rate
RPITCH bends the whole buffer rate to play to the new pitch offset
START-POS in samples
BEAT-LENGTH stretch the whole buffer to play for N beats"
(when (or (symbolp buf) (stringp buf) (characterp buf))
(let ((b (gethash buf *buffers*)))
(when b
(setf buf b))))
;; TODO: big check so we can send nil to beat-length without crashing
(when (incudine:buffer-p buf)
(let* ((sample-rate (buffer-sample-rate buf))
(frames (if end-pos-p
end-pos
(buffer-frames buf)))
(sets (if set-p
(gethash (file-namestring (buffer-file buf))
*buffer-sets*)
NIL))
(set (if (and set-p sets)
(mod set (array-dimension sets 0))
NIL))
(start-pos (if (and set-p sets)
(aref sets set 0)
start-pos))
(end-pos (if (and set-p sets)
(aref sets set 1)
frames))
(dur (/ (- end-pos start-pos)
sample-rate)))
(when rpitch-p
(mulf rate (pitch-to-ratio rpitch)))
(when beat-length-p
;; need to calculate the total duration in sec
;; to provide it to (beat-to-ratio
(mulf rate (beat-to-ratio beat-length
sample-rate
dur)))
(setf dur (/ dur (abs rate)))
;; "hack" to work with buffer-play vug
(when (< rate 0)
(setf start-pos (- frames (/ frames 20))))
(when pan-p
(setf pan (alexandria:clamp pan 0f0 1f0))
(cond ((> pan .5) (decf left (* 2 (- pan .5))))
((< pan .5) (decf right (* 2 (abs (- pan .5)))))))
(if (and set-p sets)
(if id-p
(play-lsample-f buf dur amp start-pos :rate rate
:lpf lpf :hpf hpf :bpf bpf
:lpr lpr :hpr hpr :bpr bpr
:left left :right right
:reson reson :resonq resonq
:sus 1 :rel 0
:downsamp downsamp
:id id)
(play-lsample-f buf dur amp start-pos :rate rate
:lpf lpf :hpf hpf :bpf bpf
:lpr lpr :hpr hpr :bpr bpr
:reson reson :resonq resonq
:sus 1 :rel 0
:downsamp downsamp
:left left :right right))
(if id-p
(bplay buf rate start-pos loop-p amp left right
:lpf lpf :hpf hpf :bpf bpf
:lpr lpr :hpr hpr :bpr bpr
:reson reson :resonq resonq
:downsamp downsamp
:id id)
(bplay buf rate start-pos loop-p amp left right
:lpf lpf :hpf hpf :bpf bpf
:lpr lpr :hpr hpr :bpr bpr
:reson reson :resonq resonq
:downsamp downsamp)))
dur)))
;;------------------------------------------------------
;; Description: These one help slicing buffers into smaller pieces and
;; reference those by a shortname.
;;
;; Slice of a single buffer, dedicated to words or phrases
(defstruct phrase
"file-namestring and time in seconds at which start playing
and for how long"
filename
start-at
dur)
(defun put-phrase (word filename start-at dur)
(declare (string word filename) (number start-at dur))
"creates a reference on global hash for WORD in FILENAME
begining at START-AT for DUR
(put-phrase \"nothing\" \"furi-better-cc.wav\" 1.7 1.9)"
(setf (gethash word *sample-words*)
(make-phrase :filename filename
:start-at start-at
:dur dur)))
(defun word-play
(phrase &key (rate 1) (rpitch 1 rpitch-p) (beat-length 1 beat-length-p)
(loop-p nil) (amp 1f0) (id 2 id-p)
corrupt
(downsamp 0 downsamp-p)
(left 1f0) (right 1f0) (pan 1f0 pan-p)
(lpf 0) (hpf 0) (bpf 0)
(lpr 1) (hpr 1) (bpr 1)
(corrupt-center 1f0)
(corrupt-radius .1)
(corrupt-period 1))
(declare (integer rpitch id) (boolean loop-p))
"bplay wrapper to play the phrase provided
(word-play \"time\")
(word-play \"time\" :rate 2)
(word-play \"time\" :rpitch 7)
(word-play \"time\" :beat-length 4)"
(when (or (and phrase (stringp phrase))
(and phrase (not (eq phrase :end-of-data))))
(let* ((obj (gethash phrase *sample-words*))
;; Seconds
(str (phrase-start-at obj))
(dur (phrase-dur obj))
(buf (gethash (phrase-filename obj) *buffers*))
(sample-rate (buffer-sample-rate buf))
;; Frames
(start-pos (* sample-rate str))
(end-pos (+ start-pos (* sample-rate dur))))
;; pitch to ratio - from sonic-pi
(when rpitch-p
(mulf rate (pitch-to-ratio rpitch)))
;; Update duration now based on the rate
(setf dur (/ dur (abs rate)))
;; play for beat-length
(when beat-length-p
(mulf rate (beat-to-ratio beat-length
sample-rate
dur)))
;; change where to start when played backwards
(when (< rate 0)
(rotatef start-pos end-pos))
(when pan-p
(setf pan (alexandria:clamp pan 0f0 1f0))
(cond ((> pan .5) (decf left (* 2 (- pan .5))))
((< pan .5) (decf right (* 2 (abs (- pan .5)))))))
;; start voice
(if id-p
(play-lsample-f buf dur amp start-pos
:downsamp downsamp
:rate rate
:left left
:right right
:lpf lpf :hpf hpf :bpf bpf
:lpr lpr :hpr hpr :bpr bpr
:id id)
(play-lsample-f buf dur amp start-pos
:downsamp downsamp
:rate rate
:left left
:right right
:lpf lpf :hpf hpf :bpf bpf
:lpr lpr :hpr hpr :bpr bpr
:amp amp))
(when corrupt
(corrupt-node (now)
id
:center corrupt-center
:radius corrupt-radius
:period corrupt-period))
T))) ;; ?
;;--------------------------------------------------
;; An instrument is composed of different sound files
;; that can be referenced by calling one function with
;; different pitches. They also might need a sustain to
;; play longer than designed without change pitch.
;; NOTE: Using some of ormf's code.
;;--------------------------------------------------
(defclass instrument ()
((name :initarg :name
:documentation "relative filename path")
(dir :initarg :dir
:documentation "absolute directory path where to look for samples")
(keys :initarg :keys :initform (make-array 127 :initial-element nil)
:documentation "stores key class elements")))
(defun make-instrument (name directory)
(declare (symbol name) (string directory))
(unless (gethash name *instruments*)
(setf (gethash name *instruments*)
(make-instance 'instrument
:name name
:dir directory))))
(defun list-instruments ()
(alexandria:hash-table-keys *instruments*))
(defun clean-instruments ()
(clean-buffers)
(clrhash *instruments*))
;;--------------------------------------------------
(defclass key ()
((filename :initarg :filename
:documentation
"just filename without path, used to lookup into *buffers* hash")
(keynum :initarg :keynum :documentation "midi keynum")
(startpos :initarg :startpos :documentation "initial start position")
(loopstart :initarg :loopstart :documentation "loop start position")
(loopend :initarg :loopend :documentation "loop end position")))
(defun get-pure-keys (keys)
"Returns a list of keys that match the array index and thus
won't be pitchbended."
(loop
:for i :from 0
:for ckey :across keys :when (and ckey (= i (slot-value ckey 'keynum)))
:collect i))
(defun get-new-mappings-hash (akeys)
(loop
:for (x y) :on (get-pure-keys akeys)
:with first-p = T
:with hkeys = (make-hash-table)
:finally (return hkeys)
:do
(cond ((and first-p x y)
(setf first-p nil)
;; At least 2 notes
(appendf (gethash x hkeys)
(append (iota x)
(iota (round (/ (- y x) 2))
:start (+ 1 x))))
(appendf (gethash y hkeys)
(iota (- y (+ x (round (/ (- y x) 2))))
:start (+ x (round (/ (- y x) 2))))))
;; Only 1 note
((and first-p x)
(appendf (gethash x hkeys)
(append (iota x :start 0)
(iota (- 126 x) :start (1+ x)))))
;; Middle
((and x y)
(appendf (gethash x hkeys)
(iota (round (/ (- y x) 2))
:start x))
(appendf (gethash y hkeys)
(iota (round (/ (- y x) 2))
:start (+ x (round (/ (- y x) 2))))))
;; Final sequence
((and (not y) (not first-p) x)
(appendf (gethash x hkeys)
(iota (- 126 x) :start (1+ x)))))))
(defun fill-notes (keynum iname)
(let* ((akeys (slot-value (gethash iname *instruments*) 'keys)))
(loop :for k :in (gethash keynum (get-new-mappings-hash akeys))
:do (setf (aref akeys k) (aref akeys keynum)))))
(defun push-note (iname keynum filename &optional (startpos 0) loopstart loopend)
(declare (symbol iname) (unsigned-byte keynum) (string filename))
(when-let ((instrument (gethash iname *instruments*)))
(with-slots (dir keys) instrument
(let* ((fullpath (concatenate 'string dir filename))
(buf (bbuffer-load fullpath))
(buf-size (buffer-size buf)))
(setf loopend buf-size
loopstart buf-size)
(setf (aref keys keynum)
(make-instance 'key
:filename filename
:keynum keynum
:startpos startpos
:loopstart loopstart
:loopend loopend))
(fill-notes keynum iname)))))
(defun push-note-parsed (iname filename &optional (startpos 0) loopstart loopend)
(declare (symbol iname) (string filename))
(when-let ((instrument (gethash iname *instruments*))
(keynum (note-name-to-midi-number filename)))
(with-slots (dir keys) instrument
(let* ((fullpath (concatenate 'string dir filename))
(buf (bbuffer-load fullpath))
(buf-size (buffer-size buf)))
(setf loopend buf-size
loopstart buf-size)
(setf (aref keys keynum)
(make-instance 'key
:filename filename
:keynum keynum
:startpos startpos
:loopstart loopstart
:loopend loopend))
(fill-notes keynum iname)))))
(defun load-instrument (iname)
(when-let ((instrument (gethash iname *instruments*)))
(with-slots (dir) instrument
(loop :for f :in (directory (concatenate 'string dir "*.wav"))
:do (push-note-parsed iname (file-namestring f))))))
(defun play-instrument (name nkeynum
&key (dur 1) (amp 1) (rpitch 0)
(id 222 id-p)
(downsamp 0)
(reson 0)
(left 1) (right 1)
(lpf 0) (hpf 0) (bpf 0)
(lpr 1) (hpr 1) (bpr 1))
(declare (symbol name) (integer nkeynum) (number dur amp rpitch))
(with-slots (keys) (gethash name *instruments*)
(with-slots (filename loopend loopstart keynum) (aref keys nkeynum)
(let* ((buf (gethash filename *buffers*))
(relative-pitch (- nkeynum keynum))
(rate (pitch-to-ratio (if (not (= 0 rpitch))
rpitch
relative-pitch))))
(if id-p
(play-lsample-f buf dur amp
:id id
:rate rate
:downsamp downsamp
:reson reson
:lpf lpf :hpf hpf :bpf bpf
:lpr lpr :hpr hpr :bpr bpr
:left left :right right)
(play-lsample-f buf dur amp
:rate rate
:downsamp downsamp
:reson reson
:lpf lpf :hpf hpf :bpf bpf
:lpr lpr :hpr hpr :bpr bpr
:left left :right right))))))
| 21,103 | Common Lisp | .lisp | 494 | 30.080972 | 93 | 0.503599 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | e1d436f4f52f0ba69224c8aa01bf20eea0270f4e4f34f1ca6084751ff1d40fef | 9,055 | [
-1
] |
9,056 | musicutils.lisp | azimut_shiny/lib/musicutils.lisp | (in-package :shiny)
;; Nice keys2 - Program names
;; Nice-Keys-Ultimate-V2.3.sf2
;; $ echo "inst 1" | fluidsynth /path/to/FluidR3_GM.sf2 |
;; | tr '[[:upper:]]' '[[:lower:]]'
;; | tr -dc '[[:alnum:]]\n '
;; | tr ' ' '-'
;; | sed -e 's/^\(..\)-\(.*\)/\*nk-\2\* \1/g'
;; | sed 's/^/(defvar /g'
;; | sed 's/$/)/g'
(defun cumsum (l)
"> (cumsum '(20 30 40 50 60))
(20 50 90 140 200)"
(loop
:for x :in l
:with z = 0
:collect (incf z (if (listp x) (car x) x))))
(defun d2o (l)
"durations to offsets"
(cons 0f0 (cumsum (cdr l))))
(setf *random-state* (make-random-state t))
;; https://stackoverflow.com/questions/6158990/generating-randoms-numbers-in-a-certain-range-for-common-lisp
(defun rrandom (start end)
(+ start (random (+ 1 (- end start)))))
;; rotate list
;; https://programmingpraxis.com/2010/10/12/rotate-an-array/
(defun rotate (lst arg)
(cond ((null lst) lst)
((= (mod arg (length lst)) 0) lst)
(t (rotate (nconc (cdr lst) (list (car lst))) (- arg 1)))))
(defun my-rotate (length shift)
"Return a list of given LENGTH, rotated by SHIFT."
(nconc
(loop for i from (1+ shift) to (- length shift -2) collect i)
(loop for i from 1 to shift collect i)))
(defun rotate-list (list shift)
"Rotate the given LIST by the specified SHIFT."
(let ((len (length list)))
(setq shift (mod shift len)) ; handle circular shifts
(append (nthcdr (- len shift) list)
(butlast list shift))))
(defun random-list (mylist)
(let* ((n (length mylist))
(r (random n)))
(nth r mylist)))
;; cl-losh/losh.lisp
(defun random-elt (seq &optional (generator #'random))
"Return a random element of `seq`, and whether one was available.
This will NOT be efficient for lists.
Examples:
(random-elt #(1 2 3))
=> 1
T
(random-elt nil)
=> nil
nil
"
(let ((length (length seq)))
(if (zerop length)
(values nil nil)
(values (elt seq (funcall generator length)) t))))
;; ----------------------
;; functional-composition
;; https://github.com/ctford/functional-composition
;; ----------------------
(declaim (inline midihz))
(defun midihz (midi)
(declare (fixnum midi) (optimize (speed 3)))
(* 8.1757989156f0
(expt 2 (* midi .0833333f0))))
;; ---------------------
;; https://en.wikipedia.org/wiki/Musical_note
;; where 69 is the number of semitones between
;; C|-1 (note 0) and A|4
;; --------------------
(defun hzmidi (hz)
(round (+ 69 (* 12 (log (/ hz 440) 2)))))
;; ---------------------
;; Euclidian composition
;; code from: cl-patterns
;; ---------------------
(defun bjorklund (pulses &optional steps (offset 0))
"Generate a list representing a Euclidean rhythm using the Bjorklund algorithm. PULSES is the number of \"hits\" in the sequence, STEPS is number of divisions of the sequence, and OFFSET is the number to rotate the sequence by. This function returns a list, where 1 represents a note and 0 represents a rest. If you want to use bjorklund in a pattern, you may be more interested in `pbjorklund' instead, which returns events with the correct duration and type.
Example: (bjorklund 3 7) ;=> (1 0 1 0 1 0 0)
See also: `pbjorklund'"
(if (and (null steps) (typep pulses 'ratio))
(bjorklund (numerator pulses) (denominator pulses))
(progn
(assert (> steps 0) (steps))
(assert (>= steps pulses) (pulses))
(labels ((from-array (arr)
(destructuring-bind (a b) (split arr)
(if (and (> (length b) 1) (> (length a) 0))
(from-array (lace a b))
(alexandria:flatten (append a b)))))
(split (arr)
(let ((index (position (car (last arr)) arr :test #'equal)))
(list (subseq arr 0 index)
(subseq arr index))))
(lace (a b)
(append (loop
:for x :in a
:for i :from 0
:collect (list x (nth i b)))
(when (<= (length a) (length b))
(subseq b (length a))))))
(alexandria:rotate
(from-array
(append (make-list pulses :initial-element (list 1))
(make-list (- steps pulses) :initial-element (list 0))))
offset)))))
;; ---------------------
;; Algorithmic composition
;; https://quod.lib.umich.edu/s/spobooks/bbv9810.0001.001/1:18/--algorithmic-composition-a-gentle-introduction-to-music?rgn=div1;view=fulltext
;; ---------------------
(defun 1-over-f (number)
(do* ((counter 0 (incf counter))
(blue (+ 1 (random 5)) (if (= counter 4)
(+ 1 (random 5)) blue))
(green (+ 1 (random 5)) (if (or
(= counter 2)
(= counter 4)
(= counter 6))
(+ 1 (random 5)) green))
(red (+ 1 (random 5)) (+ 1 (random 5)))
(total (+ blue green red) (+ blue green red))
(the-list (cons total ()) (cons total the-list)))
((= counter (- number 1)) (reverse the-list))))
(defun brownian-motion (start number-of-notes)
(do* ((counter 0 (incf counter))
(the-array (make-array 7 :initial-contents
'(-3 -2 -1 0 1 2 3)))
(note start (+ note (aref the-array (random 7))))
(the-list (cons start ()) (cons note the-list)))
((= counter (- number-of-notes 1)) (reverse the-list))))
;; http://stevelosh.com/blog/2016/08/playing-with-syntax/
(defmacro mulf (place factor)
`(setf ,place (* ,place ,factor)))
(defmacro divf (place divisor)
`(setf ,place (/ ,place ,divisor)))
;; Set if not defined, needs a better name (?
(defmacro setp (var values)
`(when (null ,var)
(setf ,var ,values)))
;;--------------------------------------------------
;; from Fluxus Fluxa
(defun zmod (number divisor &optional (rest 0))
"zero module - play every N, where number is samples
> (zmod (get-internal-real-time) 4)"
(= (mod number divisor) rest))
(defun zmodt (divisor &optional (rest 0))
(zmod (get-universal-time) divisor rest))
;;--------------------------------------------------
(defun b2d (bin-integer)
(reduce (lambda (x y) (+ (* 2 x) y))
(loop :for c :in
(mapcar #'parse-integer
(mapcar #'string
(coerce (string bin-integer) 'list))) :collect c)))
;;--------------------------------------------------
(defun merge-beats (beats notes &optional (rot 0 rot-def))
"takes a list of rhythms on a 1 and 0 form
and a list of notes, it will place the notes on the 1 slots
leaving notes of if necessary"
(when rot-def
(setf notes (rotate notes rot)))
(loop :for beat :in beats
:collect (if (> beat 0)
(pop notes)
0)))
;;--------------------------------------------------
;; Visual utils
;;--------------------------------------------------
(defun make-trigger (&optional (max-life 1))
"thing/closure that has 1 live until is regen
unless is bulletproof in which case is alive forever"
(let* ((mf max-life)
(alive mf)
(bulletproof nil))
(lambda (sym)
(cond ((eq sym 'bulletproof) (setf bulletproof t
alive mf))
((eq sym 'bulletproof-p) bulletproof)
((eq sym 'curse) (setf bulletproof nil))
((eq sym 'alive) (setf alive mf
bulletproof nil))
((eq sym 'alive-p) alive)
((eq sym 'bleed) (progn
(when (> alive 0)
(decf alive .05))
alive))
((eq sym 'shoot) (if bulletproof
mf
(if (> alive 0)
(progn (setf alive 0) mf)
0)))))))
;; (defmacro with-trigger ((trigger t-trigger) &body body)
;; "makes a mortal trigger-once call"
;; (let ((it (intern "IT")))
;; `(let ((,it ,t-trigger))
;; (callback ,t-trigger #'funcall ,trigger 'alive)
;; ,@body)))
(defmacro with-trigger ((trigger) &body body)
"makes a mortal trigger-once call"
`(progn
(funcall ,trigger 'alive)
,@body))
(defmacro with-trigger-expire ((trigger dur) &body body)
"makes a inmortal trigger-once call"
`(progn
(funcall ,trigger 'bulletproof)
(at (+ (now) (* ,dur 44100d0)) #'(lambda () (funcall ,trigger 'curse)))
,@body))
;; <3
;; Might be I can generalize the pick and pickl of CM too.
(defun pick-random-list (list &optional (end 0))
"pick a random number of elements from a list, up to max elements,
useful if you have a 4note chord that you want to avoid"
(let* ((l (max end (length list)))
(n (- l (random l))))
(loop :for x :in list :collect x :repeat n)))
;; like overtone's choose-n
(defun pickn (n l)
"get n random elements from list"
(subseq (cm:shuffle l)
0 (min (length l) n)))
;; Apparently same idea of nudruz.lisp
(defgeneric nths (lnth l)
(:documentation "get nth elements from lnth list")
(:method ((lnth list) l)
(let ((len (1- (length l))))
(remove nil (loop :for i :in lnth :collect (nth (min i len) l)))))
(:method ((lnth fixnum) l)
(nth lnth l)))
(defun nth-set (n new-value l)
"Change the value at n on l for new-value
> (nth-set 1 20 '(60 70 80 90 100))
(60 20 80 90 100)"
(when (not (listp l))
(setf l (list l)))
(loop :for i :upfrom 0
:for e :in l
:collect
(if (= n i)
new-value
e)))
(defun nth-inc (n inc-by l)
"Increment by inc-by the value at n on l
> (nth-inc 1 -5 '(30 40 50 60 70 80))
(30 35 50 60 70 80)"
(when (not (listp l))
(setf l (list l)))
(loop :for i :upfrom 0
:for e :in l
:collect
(if (= n i)
(+ e inc-by)
e)))
(defun lrandom-sum (n &optional (min .2) (random .5) zero-p)
"returns a list of N elements starting with zero
of (1- random) numbers"
(declare (number n min random))
(let ((lran (loop :repeat (1- n) :collect (+ min (random random)))))
(if zero-p
(append '(0) (loop :for i :in lran :with z = 0 :collect (setf z (+ i z))))
(loop :for i :in lran :with z = 0 :collect (setf z (+ i z))))))
(defun lrandom (n &optional (min .2) (random .5) zero-p)
"returns a list of N elements starting with zero
of (1- random) numbers"
(declare (number n min random))
(let ((lran (loop :repeat n :collect (+ min (random random)))))
(if zero-p
(append '(0) lran)
lran)))
(defun l-add (add n)
"Returns a list with N and N+ADD
SHINY> (l-add 5 60)
(60 65)"
(list n (+ add n)))
(defun palin (l)
"> (palin '(1 2 3 4))
(1 2 3 4 3 2 1)"
(loop
:for e :in l
:with queue
:do (push e queue)
:finally (return (append (reverse queue) (subseq queue 1)))))
;;--------------------------------------------------
(defgeneric extend (n &rest nths))
(defmethod extend ((n list) &rest nths)
"Extends list of notes, using last value
>(extend '(68 71 75 85) 5)
(68 71 75 85 90)"
(declare (list nths) (optimize (speed 3)))
(let ((l (car (last n))))
(append (butlast n) (apply #'extend l nths))))
(defmethod extend ((n fixnum) &rest nths)
"Extends note into a list with given offsets, using last value
> (extend (+ -12 50) 12 6)
(38 50 44)"
(declare (fixnum n) (list nths) (optimize (speed 3)))
(let ((notes
(mapcar (lambda (x) (the fixnum (+ (the fixnum n) (the fixnum x)))) nths)))
(push n notes)))
(defgeneric pc-extend (n pc &rest nths))
(defmethod pc-extend ((n fixnum) (pc list) &rest nths)
(declare (optimize (speed 3)))
(let ((notes
(mapcar (lambda (x) (pc-relative n x pc)) nths)))
(push n notes)))
(defmethod pc-extend ((n list) (pc list) &rest nths)
(let ((l (car (last n))))
(append (butlast n) (apply #'pc-extend l nths))))
;;--------------------------------------------------
(defun split-string (s)
(declare (type string s))
(cl-ppcre:split :whitespace-char-class s))
(defun split-string-and-add (s &rest rest)
(declare (type string s))
(if rest
(append (cl-ppcre:split :whitespace-char-class s) rest)
(cl-ppcre:split :whitespace-char-class s)))
(defun at-times (time time-offsets &rest args)
(declare (type double-float time)
(type list time-offsets)
(optimize (speed 3)))
(mapcar
(lambda (o)
(apply #'at (+ time (calc-beats o))
args))
time-offsets))
;; From nudruz.lisp
(defun mod12 (input)
"MOD12 -- returns number or list, mod 12 [old function]
(mod12 '(23 36)) = (11 0)"
(cond ((eql input 'r) 'r)
((numberp input) (mod input 12))
(t (mapcar #'mod12 input))))
(defun random-mute (l &optional (mute-prob .5))
"takes a list L and returns a new list with the same elements
but some replaced with zero"
(declare (type list l)
(type single-float mute-prob))
(loop :for note :in l :collect
(if (> (random 1f0) mute-prob)
note
0)))
(defun zbeat (time beat)
"Returns true when TIME matches is at BEAT"
(declare (type double-float time)
(type number beat))
(zerop (mod time (calc-beats beat))))
| 13,530 | Common Lisp | .lisp | 352 | 31.627841 | 462 | 0.55138 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | bfea71e93e70aaac5f54ba6d714f36082d2feec99009e1d0490926b46d53a93c | 9,056 | [
-1
] |
9,057 | molecular.lisp | azimut_shiny/lib/molecular.lisp | (in-package :shiny)
;; --------------------------------------------------------------------
;; The rules for the algorithm are as follows :
;;
;; two different note lengths need to be defined, e.g. "4" and "3"
;; a scale needs to be defined, e.g. C major (the white keys on a piano), let's say we start on the E note, the list of notes will then contain : E, F, G, A, B, C
;; a pattern length needs to be defined, e.g. 4 bars
;;
;; The algorithm will then function like so (keeping the above definitions in mind) :
;;
;; the first note of the scale (E) is played at the length of the first defined note length (4)
;; each time the duration of the played note has ended, the NEXT note in the scale (F) is played
;; once the first pattern length has been reached (4 bars), a new pattern will start
;; the previously "recorded" pattern will loop its contents indefinitely while the new patterns are created / played
;; if a newly played note sounds simultaneously with another note from a PREVIOUS pattern, the note length will change (in above example from 4 to 3).
;; this will be the new note length to use for ALL SUBSEQUENT added notes, until another simultaneously played note is found, leading it to switch back to the previous note length (in above example, back to 4).
;; as the pattern is now played over an existing one, it is likely that notes will be played in unison, leading to the switching of note length
;; as more patterns are accumulated, a perfectly mathematical pattern of notes are weaving in and out of the notes of the other patterns
;;
;; https://github.com/igorski/molecular-music-generator
;; --------------------------------------------------------------------
(defvar *mtempos* '())
(defvar *p* '())
(defvar *n* nil)
(defun mbox-show ()
(loop
:for i :in (reverse *p*)
:for ii :below 100
:do (destructuring-bind (n d c b) i
(print (format nil "~5A~10A~10A~10A~A" ii n d c b)))))
;; (defun spattern ())
;; (defun ppattern ())
(defun spattern (time notes pattern lengths r)
"Repeats the given pattern infinitly. You might want to comment the push to *mtempos* once the pattern are all done. Also you can play around by adding a probabily to NOT play the pattern. Instead of just fade away.
TIME the (now) time in samples where the sample will begin.
NOTES a list midi notes to play
PATTERN a list with 0's and 1's that indicate when to play the beat
LENGTHS a list of duration in beats a note should play
R is the midi channel used."
(let ((pbeat (loop :for beat :in pattern
:and nbeat :upto 64
:when (= 1 beat)
:collect nbeat)))
;; Take the list of beats where a note is played
;; pbeat = '(0 4 8 32) and schedule it
(loop :for cbeat :in pbeat
:do (push cbeat *mtempos*))
(push (list (next notes 't) (next lengths 't) r pattern) *p*)))
;; I need to use (mod) to get the next beat where there is a note
(defun ppattern (time lpattern notes length1 length2 &key
(cbeat 0)
(ibeat 0)
(chan 2)
(pchan 0)
accumbeats
accumnotes
accumlengths
play
pbeat)
(if (not (null notes))
(let ((nbeat (+ .5 cbeat))
(nibeat (+ 1 ibeat))
(nchan (if (= 9 (+ 1 chan)) (+ 2 chan) (+ 1 chan)))
(npchan (mod (+ pchan 1) 2))
(t-nbeat (+ time .5))
(note (first notes)))
;; play now
(if (or (eq play 'yes)
(= pbeat ibeat))
(progn
(setf notes (cdr notes)
pbeat (mod (+ ibeat (* length1 2))
lpattern))
(push note accumnotes)
(push 1 accumbeats)
(push length1 accumlengths))
(push 0 accumbeats))
;; reset when the next .5 beat is the last beat of the pattern
;; if not is business as usual and we stick with this pattern
(if (= lpattern nibeat)
(progn
;; (print "endpattern")
(spattern time
(new cycle :of (reverse accumnotes) :repeat 1)
(reverse accumbeats)
(new cycle :of (reverse accumlengths) :repeat 1)
chan)
;; This works to match agains the prev NOT the global
(if (and (= 1 (first accumbeats))
(= pbeat 0))
(progn
(print "endswap")
(ppattern time lpattern notes length2 length1
:pbeat pbeat
:chan nchan
:pchan npchan))
(ppattern time lpattern notes length1 length2
:pbeat pbeat
:chan nchan
:pchan npchan)))
(if (and (= pbeat (mod nibeat lpattern))
(find pbeat *mtempos*))
(progn
;; (print "middle swap")
(ppattern time lpattern notes length2 length1
:accumnotes accumnotes
:accumbeats accumbeats
:accumlengths accumlengths
:cbeat nbeat
:chan chan
:ibeat nibeat
:pbeat pbeat))
(progn
(ppattern time lpattern notes length1 length2
:accumnotes accumnotes
:accumbeats accumbeats
:accumlengths accumlengths
:cbeat nbeat
:chan chan
:ibeat nibeat
:pbeat pbeat)))))))
(defun mbox (time lpattern note length1 length2 bottom up pc
&optional startchan)
(setf *mtempos* nil)
(setf *p* nil)
(setf *n* nil)
(let* ((midinote (cm:keynum note))
(notes (loop
:for x :from bottom :to up
:collect (pc-relative midinote x pc)))
(notes (rest notes)))
(setf *n* notes)
(ppattern time lpattern notes length1 length2 :play 'yes)
(setf *p* (reverse *p*))))
;; Macro for common play
(defmacro mbox-play (index volume beat-duration note-duration-mul channel)
(let ((fname (intern (format nil "~A-~A" 'mplay index)))
(fname-loop (intern (format nil "%~A-~A" 'mplay index))))
`(let ((p-volume ,volume)
(p-note-duration-mul ,note-duration-mul)
(p-beat-duration ,beat-duration)
(index ,index)
(p-channel ,channel)
(p-durations nil))
(defun ,fname-loop (time
notes beats durations raw-durations)
(let ((beat (next beats)))
(when (= 1 beat)
(let ((note (next notes))
(duration (next durations)))
(p time note p-volume (* duration p-note-duration-mul) p-channel))))
(aat (+ time p-beat-duration) #',fname-loop
it
notes beats durations raw-durations))
(defun ,fname ()
(destructuring-bind (notes durations channel beats) (nth index (reverse *p*))
(declare (ignore channel))
(setf p-durations durations)
(,fname-loop (quant (* (length (cadddr (first *p*))) ;; length pattern
p-beat-duration))
(make-cycle notes) (make-cycle beats)
(make-cycle durations) durations))))))
;; macro for custom play
(defmacro mbox-custom (index
;;volume
beat-duration
;;note-duration-mul channel
&body body)
(let ((fname (intern (format nil "~A-~A" 'mplay index)))
(fname-loop (intern (format nil "%~A-~A" 'mplay index))))
`(let (;;(p-volume ,volume)
;;(p-note-duration-mul ,note-duration-mul)
(p-beat-duration ,beat-duration)
(index ,index)
;;(p-channel ,channel)
(p-durations nil))
(defun ,fname-loop (time
notes beats durations raw-durations)
(let ((beat (next beats)))
(when (= 1 beat)
(let ((note (next notes))
(duration (next durations)))
,@body)))
(aat (+ time p-beat-duration) #',fname-loop
it
notes beats durations raw-durations))
(defun ,fname ()
(destructuring-bind (notes durations channel beats) (nth index (reverse *p*))
(declare (ignore channel))
(setf p-durations durations)
(,fname-loop (quant (* (length (cadddr (first *p*))) ;; length pattern
p-beat-duration))
(make-cycle notes)
(make-cycle beats)
(make-cycle durations)
durations))))))
(defun merge-beats (beats &optional merged)
"SLIME> (merge-beats '((0 0 0 1) (1 0 0 0)))
(1 0 0 1)"
(let ((a (car beats))
(b (if merged
merged
(cadr beats))))
(if (and a b)
(merge-beats
(cddr beats)
(loop
:for x :in a
:for y :in b
:collect
(if (or (= x 1) (= y 1))
1
0)))
merged)))
(defun get-mbeats (start end)
(declare (integer start end))
(merge-beats (mapcar #'cadddr (subseq *p* start end))))
(defun get-mnotes (start end)
(declare (integer start end))
(mapcar #'caar (subseq *p* start end)))
| 10,265 | Common Lisp | .lisp | 220 | 32.677273 | 217 | 0.505783 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 4ec2d1ba13c6067bce0c6d4a7903b30509f23be1920fda7151fa34e9ed9c4f9e | 9,057 | [
-1
] |
9,058 | incudine.lisp | azimut_shiny/lib/incudine.lisp | (in-package #:shiny)
;; General incudine helpers go here
;; (format) took from fmt.pdf
(defun vug-values (sym &optional (brief T))
"1 COLUMN - pretty prints the parameters of a vug named SYM"
(multiple-value-bind (names values) (incudine.vug:vug-lambda-list sym)
(loop
:for index :from 0
:for name :in names
:for value :in values :do
(if brief
(when (and (not (search "UNUSE" (string (first name))))
(not (search "PLUGIN" (string (first name)))))
(format T
"~& ~2D ~20@A ~8D"
;;"~a ~a ~a~%"
index (first name) value))
(format T
"~& ~2D ~20@A ~8D"
;;"~a ~a ~a~%"
index (first name) value))))
(values))
;; TODO: remove UNUSED
(defun vug-values-2 (sym)
"2 COLUMN - pretty prints the parameters of a vug named SYM"
(multiple-value-bind (names values) (incudine.vug:vug-lambda-list sym)
(format T "~:{~& ~3D ~20@A ~2D - ~3D ~20@A ~2D~}"
(loop
:for index :from 0 :by 2
:for (name1 name2) :on names :by #'cddr
:for (value1 value2) :on values :by #'cddr :collect
(list index (first name1) value1
(1+ index) (first name2) value2))))
(values))
;; BEATS
(declaim (inline calc-beats))
(defun calc-beats (offset)
(declare ;;(type alexandria:non-negative-real offset)
(optimize (speed 3)))
(the double-float (* *SAMPLE-RATE* (* (sample offset) (spb *TEMPO*)))))
;; SECONDS
;; (declaim (inline calc-beats))
;; (defun calc-beats (offset)
;; (declare ;;(type alexandria:non-negative-real offset)
;; (optimize (speed 3)))
;; (the double-float (* *SAMPLE-RATE* offset)))
(defun beat ()
"returns the current beat, double precision"
(declare (type double-float *sample-rate*))
(/ (now) (* *sample-rate* (spb *tempo*))))
(defun rbeat ()
"returns the current beat, floor to integer"
(floor (beat)))
| 2,057 | Common Lisp | .lisp | 53 | 30.867925 | 73 | 0.560341 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 31b8d9d6f41218445cce264658fa648d1cd92811aeb714087fac8f045f0fb405 | 9,058 | [
-1
] |
9,059 | assets.lisp | azimut_shiny/lib/assets.lisp | (in-package #:shiny)
;; CEPL HELPERS
(defun mynow ()
;; Just some number that increases over time that we use
;; in a bunch of places
(/ (get-internal-real-time)
1000f0))
;;--------------------------------------------------
;; From cepl.tests
(defmacro with-free (name thing &body body)
(let ((name (or name (gensym "thing"))))
`(let ((,name ,thing))
(unwind-protect (progn ,@body)
(free ,name)))))
(defmacro with-free* (bindings &body body)
`(let* ,bindings
(unwind-protect (progn ,@body)
,@(loop :for (name) :in bindings :collect
`(free ,name)))))
;;------------------------------------------------------------
;; Helpers for tangent-space calculations
;; FIXME: They seem wrong on spheres, probably on everything else too?
(defstruct-g tb-data
(tangent :vec3)
(bitangent :vec3))
;; From play-with-verts, based on:
;; https://learnopengl.com/Advanced-Lighting/Normal-Mapping
(defun calc (verts i0 i1 i2)
"returns a list pair of tangent and bitangent"
(let* ((pos1 (pos (aref-c verts i0)))
(pos2 (pos (aref-c verts i1)))
(pos3 (pos (aref-c verts i2)))
(uv1 (tex (aref-c verts i0)))
(uv2 (tex (aref-c verts i1)))
(uv3 (tex (aref-c verts i2)))
;;
(edge1 (v3:- pos2 pos1))
(edge2 (v3:- pos3 pos1))
(delta-uv1 (v3:- uv2 uv1))
(delta-uv2 (v3:- uv3 uv1))
;;
(f (/ 1.0 (- (* (x delta-uv1) (y delta-uv2))
(* (x delta-uv2) (y delta-uv1)))))
;;
(tangent1
(v3:normalize
(v! (* f (- (* (y delta-uv2) (x edge1))
(* (y delta-uv1) (x edge2))))
(* f (- (* (y delta-uv2) (y edge1))
(* (y delta-uv1) (y edge2))))
(* f (- (* (y delta-uv2) (z edge1))
(* (y delta-uv1) (z edge2)))))))
(bitangent1
(v3:normalize
(v! (* f (+ (* (- (x delta-uv2)) (x edge1))
(* (x delta-uv1) (x edge2))))
(* f (+ (* (- (x delta-uv2)) (y edge1))
(* (x delta-uv1) (y edge2))))
(* f (+ (* (- (x delta-uv2)) (z edge1))
(* (x delta-uv1) (z edge2))))))))
(list tangent1 bitangent1)))
(defun tbdata-from-vertex-and-indices (g-verts g-indices)
(let* ((verts (pull1-g g-verts))
(indices (pull-g g-indices))
(result (make-gpu-array
nil :dimensions (first (dimensions verts))
:element-type 'tb-data)))
(with-gpu-array-as-c-array (data result)
(loop :for (i0 i1 i2)
:on indices
:by #'cdddr
:do (let ((pair (calc verts i0 i1 i2)))
(setf (aref-c data i0) pair)
(setf (aref-c data i1) pair)
(setf (aref-c data i2) pair))))
result))
;;------------------------------------------------------------
;; Meshes
;;
;; We cache the data based on the the arguments so we don't
;; get lots of instances in memory
(defvar *meshes* (make-hash-table :test #'equal))
(defun sphere
(&optional (radius 1f0)
(lines-of-latitude 30)
(lines-of-longitude 30) has-tangents)
(declare (boolean has-tangents))
(let ((key (list radius has-tangents)))
(or (gethash key *meshes*)
(destructuring-bind (vert index)
(nineveh.mesh.data.primitives:sphere-gpu-arrays
:radius radius
:lines-of-latitude lines-of-latitude
:lines-of-longitude lines-of-longitude)
(setf (gethash key *meshes*)
(if has-tangents
(make-buffer-stream
(list vert (tbdata-from-vertex-and-indices vert index))
:index-array index)
(make-buffer-stream vert :index-array index)))))))
(defun box (&optional (w 1f0) (h 1f0) (d 1f0) has-tangents)
(declare (boolean has-tangents))
(let ((key (list w h d has-tangents)))
(or (gethash key *meshes*)
(destructuring-bind (vert index)
(nineveh.mesh.data.primitives:box-gpu-arrays :width w
:height h
:depth d)
(setf (gethash key *meshes*)
(if has-tangents
(make-buffer-stream
(list vert (tbdata-from-vertex-and-indices vert index))
:index-array index)
(make-buffer-stream vert :index-array index)))))))
(defun cylinder (&optional (radius 1f0) (height 1f0) has-tangents)
(declare (boolean has-tangents))
(let ((key (list radius height has-tangents)))
(or (gethash key *meshes*)
(destructuring-bind (vert index)
(nineveh.mesh.data.primitives:cylinder-gpu-arrays :radius radius
:height height)
(setf (gethash key *meshes*)
(if has-tangents
(make-buffer-stream
(list vert (tbdata-from-vertex-and-indices vert index))
:index-array index)
(make-buffer-stream vert :index-array index)))))))
(defun cone (&optional (radius 1f0) (height 1f0) has-tangents)
(declare (boolean has-tangents))
(let ((key (list radius height has-tangents)))
(or (gethash key *meshes*)
(destructuring-bind (vert index)
(nineveh.mesh.data.primitives:cone-gpu-arrays :radius radius
:height height)
(setf (gethash key *meshes*)
(if has-tangents
(make-buffer-stream
(list vert (tbdata-from-vertex-and-indices vert index))
:index-array index)
(make-buffer-stream vert :index-array index)))))))
(defun lattice
(&optional (width 100f0) (height 100f0) (x 500) (y 500) has-tangents)
(declare (boolean has-tangents))
(let ((key (list :lat width height x y has-tangents)))
(or (gethash key *meshes*)
(destructuring-bind (vert index)
(nineveh.mesh.data.primitives:lattice-gpu-arrays
:width width
:height height
:x-segments x
:y-segments y)
(setf (gethash key *meshes*)
(if has-tangents
(make-buffer-stream
(list vert (tbdata-from-vertex-and-indices vert index))
:index-array index)
(make-buffer-stream vert :index-array index)))))))
;;----------------------------------------
;; Dirt - image loader into CEPL sampler
(defvar *samplers* (make-hash-table :test #'equal))
(defun free-all-tex ())
(defun get-tex (path &optional (force nil) (mipmap t) (image-format :rgba8))
(when force
(let ((s (gethash path *samplers*)))
(when s
(free (sampler-texture s)))
(remhash path *samplers*)))
(let ((absolutep (uiop:absolute-pathname-p path)))
(or (gethash path *samplers*)
(setf (gethash path *samplers*)
(cepl:sample
(dirt:load-image-to-texture
(if absolutep
path
(asdf:system-relative-pathname :shiny path))
image-format
mipmap
t))))))
;;--------------------------------------------------
;; Assimp - 3d object loader
(defstruct-g assimp-mesh
(pos :vec3)
(normal :vec3)
(uv :vec2)
(tangent :vec3)
(bitangent :vec3))
(defun assimp-mesh-to-stream (mesh)
(declare (ai:mesh mesh))
(with-slots ((vertices ai:vertices)
(faces ai:faces)
(normals ai:normals)
(texture-coords ai:texture-coords)
(tangents ai:tangents)
(bitangents ai:bitangents))
mesh
(let ((texture-coords (elt texture-coords 0)))
(assert (= (length bitangents)
(length tangents)
(length normals)
(length vertices)
(length texture-coords)))
(let ((v-arr (make-gpu-array nil :dimensions (length vertices)
:element-type 'assimp-mesh))
(i-arr (make-gpu-array nil :dimensions (* 3 (length faces))
:element-type :ushort)))
(with-gpu-array-as-c-array (c-arr i-arr)
(loop
:for indices :across faces
:for i :from 0 :by 3
:do (setf (aref-c c-arr i) (aref indices 0)
(aref-c c-arr (+ i 1)) (aref indices 1)
(aref-c c-arr (+ i 2)) (aref indices 2))))
(with-gpu-array-as-c-array (c-arr v-arr)
(loop
:for v :across vertices
:for n :across normals
:for ta :across tangents
:for bt :across bitangents
:for tc :across texture-coords
:for i :from 0
:for a := (aref-c c-arr i)
:do (setf (assimp-mesh-pos a) v
(assimp-mesh-normal a) n
(assimp-mesh-tangent a) ta
(assimp-mesh-bitangent a) bt
(assimp-mesh-uv a) (v! (x tc) (y tc)))))
(make-buffer-stream v-arr :index-array i-arr)))))
;;--------------------------------------------------
;; Cubemap
(defun make-cubemap-tex (&rest paths)
"Returns a gpu texture from the provided images"
(assert (= 6 (length paths)))
(with-c-arrays-freed
(ca (mapcar (lambda (p)
(dirt:load-image-to-c-array
(asdf:system-relative-pathname :shiny p)))
paths))
(make-texture ca :element-type :rgb8 :cubes t)))
| 9,929 | Common Lisp | .lisp | 238 | 30.163866 | 77 | 0.502224 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 1627138f75c1c5bc60a45486abf4f082af26c1bf48045823f6c81657e3905782 | 9,059 | [
-1
] |
9,060 | alsaseq.lisp | azimut_shiny/lib/alsaseq.lisp | (in-package #:shiny)
;; (midihelper:start-midihelper)
(defvar *alsaseq* nil)
(defun alsaseq-start ()
(unless *alsaseq*
(midihelper:start-midihelper)
(setf *alsaseq* t)))
(defun alsaseq-pgmchange (channel program)
(midihelper:send-event (midihelper:ev-pgmchange channel program)))
(defun alsaseq-pan (channel pan)
(midihelper:send-event (midihelper:ev-cc channel 10 pan)))
(midihelper:send-event (midihelper:ev-pgmchange 0 52))
;; (p)
;; remove pan
;; replace method name
;; macro replaced noteon & noteoff
(defgeneric play-midi-note (time pitch velocity duration channel))
;; Stop reusing p here. WHY?
(defmethod play-midi-note ((time double-float) (pitch list) (velocity fixnum) (duration number) (channel fixnum))
"Play chord of notes"
(map nil (lambda (p)
(declare (fixnum p))
(when (> duration 0)
(at time #'midihelper:send-event (midihelper:ev-noteon channel p velocity))
(at (+ time (calc-beats duration)) #'midihelper:send-event (midihelper:ev-noteoff channel p velocity))))
pitch))
(defmethod play-midi-note ((time double-float) (pitch list) (velocity fixnum) (duration number) (channel list))
"Play chord of notes, on provided channels"
(map nil (lambda (p c)
(declare (fixnum p c))
(play-midi-note time p velocity duration c))
pitch
channel))
(defmethod play-midi-note ((time double-float) (pitch fixnum) (velocity fixnum) (duration number) (channel fixnum))
"Play given pitch"
(when (and (< 0 pitch 127)
(> duration 0))
(at time #'midihelper:send-event (midihelper:ev-noteon channel pitch velocity))
(at (+ time (calc-beats duration)) #'midihelper:send-event (midihelper:ev-noteoff channel pitch velocity))
pitch))
(defmethod play-midi-note ((time double-float) (pitch fixnum) (velocity fixnum) (duration symbol) (channel fixnum))
"Play given pitch, at CM rythm"
(let ((d (cm:rhythm duration)))
(when (> d 0)
(at time #'midihelper:send-event (midihelper:ev-noteon channel pitch velocity))
(at (+ time (calc-beats d)) #'midihelper:send-event (midihelper:ev-noteoff channel pitch velocity))
pitch)))
(defmethod play-midi-note ((time double-float) (pitch symbol) (velocity fixnum) (duration symbol) (channel fixnum))
"Play given note on american notation, at CM rhythm"
(unless (and (eql :_ pitch) (eql 'cm::r pitch) (eql NIL pitch))
(let ((n (if (keywordp pitch) (note pitch) (cm:keynum pitch)))
(d (cm:rhythm duration)))
(declare (fixnum n))
(when (> d 0)
(at time #'midihelper:send-event (midihelper:ev-noteon channel n velocity))
(at (+ time (calc-beats d)) #'midihelper:send-event (midihelper:ev-noteoff channel n velocity))
n))))
(defmethod play-midi-note ((time double-float) (pitch symbol) (velocity fixnum) (duration number) (channel fixnum))
"Play given note on american notation"
(when (and (> duration 0)
(not (eql NIL pitch))
(not (eql :_ pitch))
(not (eql 'cm::r pitch)))
(let ((n (if (keywordp pitch) (note pitch) (cm:keynum pitch))))
(declare (fixnum n))
(at time #'midihelper:send-event (midihelper:ev-noteon channel n velocity))
(at (+ time (calc-beats duration)) #'midihelper:send-event (midihelper:ev-noteoff channel n velocity))
n)))
;;--------------------------------------------------
(defgeneric play-midi-arp (time notes velocity duration channel offset)
(:documentation "Play the given notes as an arpeggio"))
;; Single note, single all
(defmethod play-midi-arp ((time double-float) (notes number) (velocity fixnum) (duration number) (channel fixnum) (offset number))
(when (>= offset 0)
(play-midi-note (+ time (calc-beats offset)) notes velocity duration channel)))
;; Single note, multiple other things
(defmethod play-midi-arp ((time double-float) (notes number) (velocity list) (duration number) (channel fixnum) (offset number))
(let* ((lnotes (length velocity))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(map nil (lambda (v o)
(declare (fixnum v))
(play-midi-note (+ time (calc-beats o)) notes v duration channel))
velocity
offsets)))
(defmethod play-midi-arp ((time double-float) (notes number) (velocity fixnum) (duration list) (channel fixnum) (offset number))
(let* ((lnotes (length duration))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(map nil (lambda (d o)
(play-midi-note (+ time (calc-beats o)) notes velocity d channel))
duration
offsets)))
(defmethod play-midi-arp ((time double-float) (notes number) (velocity fixnum) (duration number) (channel fixnum) (offset list))
(map nil (lambda (o)
(when (>= o 0)
(play-midi-note (+ time (calc-beats o)) notes velocity duration channel)))
offset))
(defmethod play-midi-arp ((time double-float) (notes number) (velocity list) (duration number) (channel fixnum) (offset list))
(map nil (lambda (v o)
(declare (fixnum v))
(when (>= o 0)
(play-midi-note (+ time (calc-beats o)) notes v duration channel)))
velocity
offset))
(defmethod play-midi-arp ((time double-float) (notes number) (velocity fixnum) (duration list) (channel fixnum) (offset list))
(map nil (lambda (d o)
(when (>= o 0)
(play-midi-note (+ time (calc-beats o)) notes velocity d channel)))
duration
offset))
;; Multiple notes
(defmethod play-midi-arp ((time double-float) (notes list) (velocity fixnum) (duration number) (channel fixnum) (offset number))
(let* ((lnotes (length notes))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(map nil (lambda (n o)
;; (declare (fixnum n) (number o))
(play-midi-note (+ time (calc-beats o)) n velocity duration channel))
notes
offsets)))
(defmethod play-midi-arp ((time double-float) (notes list) (velocity fixnum) (duration number) (channel list) (offset number))
(let* ((lnotes (length notes))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(map nil (lambda (n o c)
(declare (fixnum c))
(play-midi-note (+ time (calc-beats o)) n velocity duration c))
notes
offsets
channel)))
(defmethod play-midi-arp ((time double-float) (notes list) (velocity list) (duration number) (channel fixnum) (offset number))
(let* ((lnotes (length notes))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(map nil (lambda (n o v)
(declare (fixnum v))
(play-midi-note (+ time (calc-beats o)) n v duration channel))
notes
offsets
velocity)))
(defmethod play-midi-arp ((time double-float) (notes list) (velocity list) (duration number) (channel list) (offset number))
(let* ((lnotes (length notes))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(map nil (lambda (n o v c)
(declare (fixnum v c))
(play-midi-note (+ time (calc-beats o)) n v duration c))
notes
offsets
velocity
channel)))
(defmethod play-midi-arp ((time double-float) (notes list) (velocity fixnum) (duration list) (channel fixnum) (offset number))
(let* ((lnotes (length notes))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(map nil (lambda (n o d)
;;(declare (fixnum n))
(play-midi-note (+ time (calc-beats o)) n velocity d channel))
notes
offsets
duration)))
(defmethod play-midi-arp ((time double-float) (notes list) (velocity fixnum) (duration list) (channel list) (offset number))
(let* ((lnotes (length notes))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(map nil (lambda (n o c d)
(declare (fixnum c))
(play-midi-note (+ time (calc-beats o)) n velocity d c))
notes
offsets
channel
duration)))
(defmethod play-midi-arp ((time double-float) (notes list) (velocity list) (duration list) (channel fixnum) (offset number))
(let* ((lnotes (length notes))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(map nil (lambda (n o v d)
(declare (fixnum v))
(play-midi-note (+ time (calc-beats o)) n v d channel))
notes
offsets
velocity
duration)))
(defmethod play-midi-arp ((time double-float) (notes list) (velocity list) (duration list) (channel list) (offset number))
(let* ((lnotes (length notes))
(offsets (loop :for i :from 0 :by offset :collect i :repeat lnotes)))
(map nil (lambda (n o v c d)
(declare (fixnum v c))
(play-midi-note (+ time (calc-beats o)) n v d c))
notes
offsets
velocity
channel
duration)))
(defmethod play-midi-arp ((time double-float) (notes list) (velocity fixnum) (duration number) (channel fixnum) (offset list))
(map nil (lambda (n o)
;;(declare (fixnum n))
(play-midi-note (+ time (calc-beats o)) n velocity duration channel))
notes
offset))
(defmethod play-midi-arp ((time double-float) (notes list) (velocity fixnum) (duration number) (channel list) (offset list))
(map nil (lambda (n o c)
(declare (fixnum c))
(play-midi-note (+ time (calc-beats o)) n velocity duration c))
notes
offset
channel))
(defmethod play-midi-arp ((time double-float) (notes list) (velocity list) (duration number) (channel fixnum) (offset list))
(map nil (lambda (n o v)
(declare (fixnum v))
(play-midi-note (+ time (calc-beats o)) n v duration channel))
notes
offset
velocity))
(defmethod play-midi-arp ((time double-float) (notes list) (velocity list) (duration number) (channel list) (offset list))
(map nil (lambda (n o v c)
(declare (fixnum v c))
(play-midi-note (+ time (calc-beats o)) n v duration c))
notes
offset
velocity
channel))
(defmethod play-midi-arp ((time double-float) (notes list) (velocity fixnum) (duration list) (channel fixnum) (offset list))
(map nil (lambda (n o d)
;;(declare (fixnum n))
(play-midi-note (+ time (calc-beats o)) n velocity d channel))
notes
offset
duration))
(defmethod play-midi-arp ((time double-float) (notes list) (velocity fixnum) (duration list) (channel list) (offset list))
(map nil (lambda (n o c d)
(declare (fixnum c))
(play-midi-note (+ time (calc-beats o)) n velocity d c))
notes
offset
channel
duration))
(defmethod play-midi-arp ((time double-float) (notes list) (velocity list) (duration list) (channel fixnum) (offset list))
(map nil (lambda (n o v d)
(declare (fixnum v))
(play-midi-note (+ time (calc-beats o)) n v d channel))
notes
offset
velocity
duration))
(defmethod play-midi-arp ((time double-float) (notes list) (velocity list) (duration list) (channel list) (offset list))
(map nil (lambda (n o v c d)
(declare (fixnum v c))
(play-midi-note (+ time (calc-beats o)) n v d c))
notes
offset
velocity
channel
duration))
| 11,681 | Common Lisp | .lisp | 246 | 39.947154 | 130 | 0.623501 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | e9e8378eeb6ae544eda78eb0b16834bbff88998d8308c63e77270af106b9b3e3 | 9,060 | [
-1
] |
9,061 | foxdot-play.lisp | azimut_shiny/lib/foxdot/foxdot-play.lisp | (in-package #:shiny)
;;
;; Description: Loaders and players for foxdot sounds
;;
(defvar *fx-samples* (make-hash-table)
"Hash with array of buffers.")
(defvar *fx-path* "/home/sendai/.local/lib64/python3.4/site-packages/FoxDot/snd/"
"Directory where to search for FoxDot samples, overwrite as needed.")
;; lib/Buffers.py
(defvar *fx-non-alpha-sounds*
'(("semicolon" . ":")
("ampersand" . "&")
("asterix" . "*")
("at" . "@")
("bar" . "|")
("caret" . "^")
("colon" . ":")
("dollar" . "$")
("equals" . "=")
("exclamation" . "!")
("forwardslash" . "/")
("greaterthan" . ">")
("hash" . "#")
("hyphen" . "-")
("lessthan" . "<")
("percent" . "%")
("plus" . "+")
("question" . "?")
("tilde" . "~")
("backslash" . "\\")
("1" . "1")
("2" . "2")
("3" . "3")
("4" . "4"))
"alist of sample folder name to symbol string used in fx-play")
(defun fx-guess-path (path)
(if (uiop:absolute-pathname-p path)
path
(concatenate 'string *fx-path* path)))
(defun fx-clear (&optional global-clear)
"NOTE: to free buffers from memory use (clean-buffers)"
(clrhash *fx-samples*)
(when global-clear
(clean-buffers))
t)
(defun fx-load (path key)
"loads sounds in PATH into the *FX-SAMPLES* hash cache under KEY
VALUE is and extendable array that keeps each sample for KEY
PATH can be a .wav file or a directory"
(let ((resolved-path (fx-guess-path path))
(key (if (stringp key) (char key 0) key)))
(cond ((uiop:directory-exists-p resolved-path)
(remhash key *fx-samples*)
(loop :for file :in (uiop:directory-files ;; ensure trailing slash
(uiop:directory-exists-p resolved-path))
:do (fx-load file key)))
((uiop:file-exists-p resolved-path)
(let ((buffer (bbuffer-load resolved-path)))
(if-let ((buffers (gethash key *fx-samples*)))
(vector-push-extend buffer buffers)
(let ((init (make-array 1 :initial-contents `(,buffer)
:adjustable T :fill-pointer 1)))
(setf (gethash key *fx-samples*) init)))))
(t (error "PATH provides not valid...")))))
(defun fx-load-all ()
"loads all sounds in *FX-PATH* into *FX-SAMPLES*"
(loop :for dir :in (uiop:subdirectories *fx-path*)
:for letter := (lastcar (pathname-directory dir))
:if (str:alphap letter)
:do (fx-load (merge-pathnames dir "lower") letter)
(fx-load (merge-pathnames dir "upper") (str:upcase letter)))
(loop :for dir :in (uiop:subdirectories (merge-pathnames *fx-path* "_"))
:for letter := (lastcar (pathname-directory dir))
:for letter-symbol := (cdr (assoc letter *fx-non-alpha-sounds* :test #'equal))
:do (fx-load dir letter-symbol)))
(defun resolve-patterns-in-list (list)
(declare (type list list))
(if (some #'cm:pattern? list)
(resolve-patterns-in-list (mapcar #'cm:next list))
list))
(defun fx-play (key &rest rest &key (sample 0) (dur 1) &allow-other-keys)
(etypecase key
(cm::pattern
(apply #'fx-play (next key) rest)) ;; when this happens?
(string
(apply #'fx-play (char key 0) rest))
(character
(when-let* ((buffers (gethash key *fx-samples*))
(n-buffers (fill-pointer buffers))
(buffer (aref buffers (mod sample n-buffers))))
(remf rest :sample)
(remf rest :dur)
(apply #'bbplay buffer rest)))
(list
(when-let* ((_ key)
(sounds (resolve-patterns-in-list key))
(n-sounds (length sounds))
(offsets (loop :repeat n-sounds
:for i :from 0d0 :by (/ (coerce dur 'double-float)
n-sounds)
:summing i :into total
:collect total)))
(mapcar (lambda (n o)
(declare (type double-float o))
(apply #'at
(+ (now) (calc-beats o))
#'fx-play
n
rest))
key
offsets)))))
| 4,454 | Common Lisp | .lisp | 111 | 30.936937 | 86 | 0.517186 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 0793bce9c48b551c4f0e2fbf2b923438c4356e026ce283b002cecdaf0a30c82d | 9,061 | [
-1
] |
9,062 | foxdot.lisp | azimut_shiny/lib/foxdot/foxdot.lisp | (in-package #:shiny)
;;
;; Description: misc utils from foxdot
;;
;; https://github.com/Qirky/FoxDot/blob/master/FoxDot/lib/Utils/__init__.py
(defun pulses-to-durations (pulses)
" Returns a list of durations based on pulses (1s) and blanks (0s).
Data should be a list of [1,0] where 1 is a pulse."
(loop :for i :in (cdr pulses)
:for c :from 1
:with seq = '()
:with count = 1
:finally (progn
(push count seq)
(return (reverse seq)))
:do (if (= i 1)
(progn
(push count seq)
(setf count 1))
(incf count 1))))
;; https://github.com/Qirky/FoxDot/blob/master/FoxDot/lib/Patterns/Sequences.py
(defun pdur (n k &optional (start 0) (dur .25))
"Returns the *actual* durations based on Euclidean rhythms (see PEuclid) where dur
is the length of each step.
::
>>> PDur(3, 8)
P[0.75, 0.75, 0.5]
>>> PDur(5, 16)
P[0.75, 0.75, 0.75, 0.75, 1]"
;; If we have more pulses then steps, double the steps and decrease the duration
(declare (type unsigned-byte start))
(loop :while (> n k)
:do (mulf k 2)
(divf dur 2))
(let ((pattern (pulses-to-durations (bjorklund n k))))
(when (not (= 0 start))
(setf pattern (alexandria:rotate pattern start)))
(mapcar (lambda (x) (* dur x)) pattern)))
;; TODO: Player methods, they are like the pattern modifiers below
;; but applied to a playing pattern.
;; https://github.com/Qirky/FoxDot/blob/master/FoxDot/lib/Players.py
;;--------------------------------------------------
;; TODO: Player Patterns
;;
;; <> - To separate patterns you want to play together.
;; () - Grouping characters in round brackets laces the pattern so
;; that on each play through of the sequence of samples, the next
;; character in the group's sample is played.
;; [] - Using square brackets will force the enclosed samples to
;; played in the same time span as a single character e.g. `--[--]`
;; will play two hi-hat hits at a half beat then two at a quarter
;; beat.
;; {} - You can play a random sample from a selection by using curly
;; braces in your Play String
;; || - play a sample NR , being x the sample symbol and N the number of
;; the sample as in |xN| also possible to use () [] {}
;;--------------------------------------------------
;; Pattern methods
;; http://docs.foxdot.org/docs/patterns/pattern-methods/
;; https://github.com/Qirky/FoxDot/blob/master/FoxDot/lib/Patterns/Main.py
;;------------------------------
;; shuffle(n=1) =~
;; (cm:shuffle list) =~
;; (next (make-weighting '(1 2 3)) 10)
;;
;; Returns the pattern with it’s contents in a random order and n is
;; the number of permutations:
(defun fx-shuffle (l)
(cm:shuffle l))
;;------------------------------
;; reverse() =~ (reverse)
;; Returns the pattern with its contents in reverse order. Nested
;; patterns / groups are *not* reversed.
(defun fx-reverse (l)
(reverse l))
;;------------------------------
;; mirror()
;; Returns a pattern with its contents in reverse order, including
;; nested patterns and groups:
;;------------------------------
;; sort(*args, **kwargs) =~ (sort)
;; Returns a pattern with the values sorted in order. The args and
;; **kwargs are those that are supplied to Python’s builtin sorted
;; function but this returns a Pattern as opposed to a list.
(defun fx-sort (l f)
(sort l f))
;;------------------------------
;; stutter(n=2)
;; Returns a new pattern with each value repeated n number of
;; times. If n is a pattern itself, then each value is repeated by the
;; number at the same index in the given pattern.
(defgeneric fx-stutter (l n)
(:documentation
"> (stutter '(1 2 3) 2)
(1 1 2 2 3 3)
> (stutter '(1 2 3 4) '(1 3))
(1 2 2 2 3 4 4 4)")
(:method ((l list) (n fixnum))
(loop :for item :in l
:append (loop :repeat n :collect item)))
(:method ((l list) (n list))
(loop :for item :in l
:append (prog1 (loop :repeat (car n) :collect item)
(setf n (alexandria:rotate n)))))
(:method (l (n fixnum))
(repeat n (ensure-list l))))
;;------------------------------
;; arp(seq)
(defun fx-arp (l n)
"Returns a new pattern with each item repeated len(seq) times and
incremented by the values in seq. Useful for arpeggiating.
> (arp '(0 1 2 3) '(0 4))
(0 4 1 5 2 6 3 7)"
(declare (type list n l))
(loop :for note :in l
:append (loop :for offset :in n :collect (+ note offset))))
;;------------------------------
;; splice(seq, *seqs)
;; Takes one or more patterns to “splice” into the original
;; pattern. The new pattern returned is made up of the values from the
;; original and given sequences in an alternated fashion.
;; https://github.com/vseloved/rutils/blob/master/core/list.lisp
(defun fx-splice (list &rest lists)
"Return a list whose elements are taken from LIST and each of LISTS like this:
1st of list, 1st of 1st of lists,..., 1st of last of lists, 2nd of list,...
> (splice '(0 1 2 3) '(a b c))
(0 A 1 B 2 C)"
(apply #'mapcan (lambda (&rest els)
els)
list lists))
;;------------------------------
;; invert()
(defun fx-invert (l)
"Creates an inverted version of pattern by subtracting its values
from the largest value in the pattern such that the largest value
in the pattern becomes the smallest (and vice versa) and the
difference between other values and the min/max are swapped:
> (fx-invert '(2 5 1 11))
(9 6 10 0)"
(declare (type list l))
(let ((max (extremum l #'>)))
(loop :for item :in l
:collect (- max item))))
;;------------------------------
;; shufflets(n = 4)
(defun fx-shufflets (l n)
"Returns a new pattern that contains the original pattern as a
PGroup in random order of length n.
> (fx-shufflets '(1 2 3 4) 3)
((4 1 3 2) (3 1 4 2) (3 2 1 4))"
(declare (type list l) (type unsigned-byte n))
(loop :repeat n
:collect (cm:shuffle l)))
;;------------------------------
;; pivot(i)
(defun fx-pivot (l n)
"Returns a new pattern that is a reversed version of the original
but then rotated such that the element at index i is still in the
same place."
(declare (type list l) (type unsigned-byte n))
(let* ((len (length l))
(mid (/ len 2)))
(if (> n mid)
(progn
(setf n (1- (- len n)))
(setf l (rotate (reverse l) (1+ (* 2 (mod n len))))))
(setf l (reverse (rotate l (1+ (* 2 (mod n len)))))))
l))
;;------------------------------
;; accum(n=None)
(defun fx-accum (l &optional (n (length l)))
"Returns a pattern that is equivalent to the list of sums of that
pattern up to that index (the first value is always 0). The
argument n specifies the length of the new pattern. When n is None
then the new pattern takes the length of the original.
> (fx-accum '(1 2 3 4) 8)
(0 1 3 6 10 11 13 16)"
(declare (type list l) (type unsigned-byte n))
(loop :for i :in (repeat (1- n) l)
:with s = '(0)
:with prev = 0
:finally (return (reverse s))
:do (let ((current (+ i prev)))
(push current s)
(setf prev current))))
;;------------------------------
;; stretch(size)
(defun fx-stretch (l n)
"Returns a pattern that is repeated until the length is equal to size."
(declare (type list l) (type unsigned-byte n))
(repeat n l))
;;------------------------------
;; trim(size)
(defun fx-trim (l n)
"Like stretch but the length cannot exceed the length of the
original pattern."
(declare (type list l) (type unsigned-byte n))
(repeat (min (length l) n) l))
;;------------------------------
;; ltrim(size)
(defun fx-itrim (l n)
"Like trim but removes items from the start of the pattern, not the end."
(declare (type list l) (type unsigned-byte n))
(reverse (repeat (min (length l) n) (reverse l))))
;;------------------------------
;; loop(n)
;;------------------------------
;; duplicate(n)
;; Like loop but retains the nested patterns such that the first value
;; in the nests are used on the first iteration through the duplicated
;; sequence etc.
(defun fx-duplicate (l n)
"Repeats the pattern n times. Useful when chaining together multiple
patterns. Nested patterns are taken into consideration when
looping."
(let* ((len (length l))
(n2 (* len n)))
(repeat n2 l)))
;;------------------------------
;; iter
;; Like loop but does not take nested patterns into account when
;; calculating the length.
;;------------------------------
;; swap(n)
;; Swaps the places of values in the pattern. When n is 2 then values
;; next to each other are swapped, when n is 3 then values next but 1
;; are swapped, and so on.
;; FIXME: returns a shorter list than FoxDot
(defun fx-swap (l n)
(loop :for d :from 0 :by n
:for u :from n :by n :to (length l)
:append (reverse (subseq l d u))))
;;------------------------------
;; rotate(n)
;; Returns a pattern with the original pattern’s values shifted left
;; in order by n number of places. Negative numbers shift the values
;; right.
(defgeneric fx-rotate (l n)
(:method ((l sequence) (n fixnum))
(alexandria:rotate l n))
(:method ((l vector) (n list))
(loop :for rot :in n
:append (coerce (alexandria:rotate l (- rot))
'list)))
(:method ((l list) (n list))
(loop :for rot :in n
:append (alexandria:rotate l (- rot)))))
;;------------------------------
;; sample(n) =~ (choose-n) =~ (pickn)
(defun fx-sample (l n)
"Returns an n-length pattern with randomly selected values from the
original pattern."
(subseq (alexandria:shuffle l) 0 n))
;;------------------------------
;; palindrome()
;; Appends the reverse of a pattern onto itself such that is creates a
;; palindrome of numbers.
(defun fx-palindrome (l)
(appendf l (reverse l)))
(defun fx-palindrome2 (l)
(appendf l (reverse (butlast l))))
;;------------------------------
;; alt(seq)
;; Replaces the pattern with that of seq. Useful if you want to use an
;; alternate pattern and assign it using the every method.
;;
;; !???
;;------------------------------
;; norm()
;; Returns a pattern with all the values normalised such that every
;; value in the new pattern is between 0 and 1.
(defun fx-norm (l)
(let ((max (* 1f0 (extremum l #'>))))
(loop :for item :in l :collect
(/ item max))))
;;------------------------------
;; undup()
;; Removes any consecutive duplicate values so that there are no
;; repeated values in the pattern.
(defun fx-undup (l)
(remove-duplicates l))
;;------------------------------
;; limit(func, value)
;; Returns a new pattern generated by appending values from the
;; original until func(pattern) exceeds value. The func argument must
;; be a valid function, such as len or sum.
;;------------------------------
;; replace(sub, repl)
;; Returns a new pattern with values equal to sub replaced with repl.
(defun fx-replace (l sub repl)
(substitute repl sub l))
;;------------------------------
;; submap(mapping)
;; Similar to replace but takes a dictionary of sub to repl values to
;; replace multiple items.
;; FIXME? do it backwars? Iterate and then lookup?
(defun fx-submap (l alist)
(declare (type list l) (type cons alist))
(loop :for (sub . repl) :in alist
:collect (setf l (substitute repl sub l)))
l)
;;------------------------------
;; layer(method, *args, **kwargs)
;; Zips the original pattern with itself but with method called on
;; itself, which must be a string name of a valid pattern method
;; (similar to Player.every). However, the method argument can also be
;; a function (example below).
;;------------------------------
;; every(n, method, *args, **kwargs)
;; Repeats the original pattern n times and applies the Pattern method
;; (specified as a string) on the last repetition with args and kwargs
;; supplied.
;;------------------------------
;; map(callable)
;; Returns a new Pattern with the callable argument called on every
;; item in the pattern.
;;------------------------------
;; extend(seq)
;; Extends the Pattern with seq in place i.e. it returns None as
;; opposed to a new Pattern. This is more efficient than the concat
;; method for combining multiple sequences into one Pattern.
;;------------------------------
;; concat(seq)
;; Returns a new Pattern with the contents of seq appended onto the
;; end of the original Pattern. The special __or__ method (which uses
;; the | syntax) also calls this method.
;;------------------------------
;; zip(seq)
;; “Zipping” is the process of combining two sequences into one where
;; each element is a group that contains the items from each sequence
;; at the same index. If the sequences are of different lengths then
;; then they are zipped up to the length of the lowest common multiple
;; of both lengths.
;;------------------------------
;; offadd(value, dur=0.5)
;; Adds value to the Pattern, zips with the original, and delays the
;; zipped value by dur using the PGroupPrime class.
;;------------------------------
;; offmul(value, dur=0.5)
;; Similar to offadd but multiplies the values as opposed to adding.
;;------------------------------
;; offlayer(method, dur=0.5, *args, **kwargs)
;; Similar to offadd and offmul but uses a user-specified method or
;; function instead of addition/multiplication. The method argument
;; must be a valid name of a Pattern method as a string or a callable
;; object such as a function. Any extra arguments or keyword arguments
;; are supplied after the duration to delay the layer, therefore
;; duration must be supplied if supplying arguments as part of *args.
;;------------------------------
;; amen()
;; Replicates the rhythm and order of the famous “amen break” based on
;; a kick-drum, hi-hat, snare-drum, hi-hat sequence. Listen to the
;; example below:
;; (defun amen (pat &optional (size 2))
;; "merges and laces the first and last two items such that a
;; drum pattern \"x-o-\" would become \"(x[xo])-o([-o]-)\""
;; (let ((new '()))
;; (loop :for n :in (myrange (lcm (length pat) 4))
;; :do )))
;; TimeVar has a series of values that it changes between after a
;; pre-defined number of beats and is created using a var object with
;; the syntax
;; var([list_of_values],[list_of_durations]).
;;
;; TODO: subvars on vars parameter. var([0,5,2[3,6]],[8,6,1,1])
(defun var (vars n-beats)
"Returns a function, that returns a value from VARS, a new one if N-BEATS have passed.
> (defvar *var1* (var '(1 2) 4))
> (funcall *var1*)
1
> (cm:next *var1*)
2"
(declare (type list vars))
(let ((start-beat (beat))
(current-beat 0d0)
(elapsed-beats 0d0)
(var-index 0)
(beat-index 0)
(beats (ensure-list n-beats)))
(lambda ()
(setf current-beat (beat))
(setf elapsed-beats (- current-beat start-beat))
;;
(when (> elapsed-beats (nth beat-index beats))
(setf start-beat current-beat)
(setf var-index (mod (1+ var-index) (length vars)))
(setf beat-index (mod (1+ beat-index) (length beats))))
(nth var-index vars))))
;; Like csound nth-beat but accepts 2 lists
(defun ivar (vars at-beats)
"Inplace var()"
(let* ((vars (ensure-list vars))
(n-vars (length vars))
(at-beats (repeat n-vars (ensure-list at-beats)))
(beat (beat))
(sum (reduce #'+ at-beats))
(curr-beat (mod beat sum))
(sum-beats (loop :for i :in at-beats :summing i :into all :collect all))
(var-pos (position-if (lambda (n) (< curr-beat n))
sum-beats)))
(nth var-pos vars)))
(defun linvar (vars n-beats)
(declare (type list vars))
(let ((start-beat (beat))
(current-beat 0d0)
(elapsed-beats 0d0)
(var-index 0)
(beat-index 0)
(beats (ensure-list n-beats)))
(lambda ()
(setf current-beat (beat))
(setf elapsed-beats (- current-beat start-beat))
;;
(when (> elapsed-beats (nth beat-index beats))
(setf start-beat current-beat)
(setf var-index (mod (1+ var-index) (length vars)))
(setf beat-index (mod (1+ beat-index) (length beats))))
(alexandria:lerp (/ elapsed-beats (nth beat-index beats))
(nth 0 vars)
(nth 1 vars)))))
;; FIXME: fix lerp from 0-1 to 0-1-0
(defun ilinvar (vars n-beat)
"Inplace linvar()"
(declare (type list vars)
(type number n-beat))
(assert (length= 2 vars))
(let ((beat (mod (beat) n-beat)))
(coerce (alexandria:lerp (/ beat n-beat)
(nth 0 vars)
(nth 1 vars))
'single-float)))
(defun often ()
(= (mod (beat) 32)
(serapeum:random-in-range 1 8)))
(defun sometimes ()
(= (mod (beat) 32)
(serapeum:random-in-range 8 32)))
(defun rarely ()
(= (mod (beat) 32)
(serapeum:random-in-range 32 64)))
;;.sometimes("amp.trim", 3)
;; def often(self, *args, **kwargs):
;; """ Calls a method every 1/2 to 4 beats using `every` """
;; return self.every(PRand(1, 8)/2, *args, **kwargs)
;; def sometimes(self, *args, **kwargs):
;; """ Calls a method every 4 to 16 beats using `every` """
;; return self.every(PRand(8, 32)/2, *args, **kwargs)
;; def rarely(self, *args, **kwargs):
;; """ Calls a method every 16 to 32 beats using `every` """
;; return self.every(PRand(32, 64)/2, *args, **kwargs)
;; def every(self, n, cmd, args=()):
;; def event(f, n, args):
;; f(*args)
;; self.schedule(event, self.now() + n, (f, n, args))
;; return
;; self.schedule(event, self.now() + n, args=(cmd, n, args))
;; return
| 17,849 | Common Lisp | .lisp | 457 | 35.188184 | 88 | 0.599239 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 62d8f3fa2f643a6b045579a72f0aec57af3853b329baf12602e5491f69065064 | 9,062 | [
-1
] |
9,063 | foxdot-grammar.lisp | azimut_shiny/lib/foxdot/foxdot-grammar.lisp | (in-package #:shiny)
;;--------------------------------------------------
;; Pattern support similar to the one that Foxdot's
;; play() provides
(cl-lex:define-string-lexer foxdot-lexer
("[A-Za-z-@_*+~/:&|^$=!/#%?~\\\\.1234]"
(return (values :variable (char $@ 0))))
("<" (return (values :left-pat :left-pat)))
(">" (return (values :right-pat :right-pat)))
("\\[" (return (values :left-square :left-square)))
("\\]" (return (values :right-square :right-square)))
("\\(" (return (values :left-paren :left-paren)))
("\\)" (return (values :right-paren :left-paren)))
("{" (return (values :left-brace :left-brace)))
("}" (return (values :right-brace :right-brace)))
("\\s" (return (values :null NIL))))
(defun lex-line (string)
"REPL helper to test lexer"
(loop :with lexer := (foxdot-lexer string)
:for tok := (funcall lexer)
:while tok
:collect tok))
;;--------------------------------------------------
(defun mc (&rest elements)
(cm:new cm:cycle :of elements :for 1))
(defun mw (&rest elements)
(let ((weighted-elements ;; accept plain lists, like for []
(loop :for e :in elements
:collect (list e :weight 1))))
(cm:new cm:weighting :of weighted-elements :for 1)))
(yacc:define-parser foxdot-parser
(:start-symbol expression)
(:terminals
(:left-pat :right-pat ;; <> - pattern (also cycle)
:left-paren :right-paren ;; () - cycle
:left-brace :right-brace ;; {} - random
:left-square :right-square ;; [] - list
:null :variable))
(expression (term #'list) ;; NOTE: hardcoded list since it doesn't work otherwise
(term expression
(lambda (a b)
(verbose:debug :foxdot "dig: ~a || ~a~%" a b)
(cond ((and (atom a) (listp b)) (append (list a) b))
((and (listp a) (atom b)) (append a (list b)))
((and (atom a) (atom b)) (list a b))
;; NOTE: in the case the thing to put together are
;; two different patterns put them together list,
;; otherwise just cons them.
;; FIXME: might be this can part of the grammar???
((and (listp a) (listp b)
(not (listp (car b)))
(not (length= 1 (symbol-name (car b)))))
(list a b))
(t (cons a b))))))
(term :null
(:variable (lambda (x)
(verbose:debug :foxdot "quote: ~a~%" x)
`(quote ,x)))
cycle
heap
random
group)
(cycle (:left-paren expression :right-paren
(lambda (_l e _r) (declare (ignore _l _r))
(verbose:debug :foxdot "cycle: ~a~%" e)
(cons 'mc e))))
(heap (:left-square expression :right-square
(lambda (_l e _r) (declare (ignore _l _r))
(verbose:debug :foxdot "heap: ~a~%" e)
(cons 'list e))))
(random (:left-brace expression :right-brace
(lambda (_l e _r) (declare (ignore _l _r))
(verbose:debug :foxdot "random: ~a~%" e)
(cons 'mw e))))
(group (:left-pat expression :right-pat
(lambda (_l e _r) (declare (ignore _l _r))
(verbose:debug :foxdot "group: ~a~%" e)
(cons 'mc e)))))
(defun fx-pat (pat &optional (eval t))
(let* (;; given that we are going to get a cycle anyway
;; we just force a cycle around the pattern given
;; avoiding having to update the grammar (HACKS!)
;;(pattern pat (format NIL "(~a)" pat))
;;(pattern pat)
;; NOTE: Naive fix of input string
(raw-patterns (if (and (char= #\< (aref pat 0))
(char= #\> (aref pat (1- (length pat)))))
pat
(progn
(verbose:debug :foxdot "forcing pattern between \< \>~%")
(format NIL "\<~a\>" pat))))
(lisp-patterns (yacc:parse-with-lexer (foxdot-lexer raw-patterns)
foxdot-parser))
(cm-patterns (mapcar #'eval lisp-patterns)))
(if eval
(if (length= 1 cm-patterns) (first cm-patterns) cm-patterns)
(if (length= 1 lisp-patterns) (first lisp-patterns) lisp-patterns))))
(defun fx-pats (pat &optional (eval t))
(ensure-list (fx-pat pat eval)))
| 4,887 | Common Lisp | .lisp | 99 | 36.131313 | 87 | 0.464742 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | c966584c5eab171f33497d6a54f9a98133671c6691be05b2b5e256e1e665124d | 9,063 | [
-1
] |
9,064 | box.lisp | azimut_shiny/examples/box.lisp | ;;;; somecepl.lisp
(in-package #:shiny)
;;; "somecepl" goes here. Hacks and glory await!
(defvar *box* nil)
(defvar *vert-stream* nil)
(defun-g draw-verts-vert-stage ((vert g-pnt) &uniform (resolution :vec2) (time :float)
(perspective :mat4))
(let* ((pos (pos vert))
(w (+ 1.6 (z pos)))
(pos (+ pos (v! (sin time) 0 -4)))
)
(* perspective (v! pos 1))))
(defun-g draw-verts-frag-stage (&uniform (resolution :vec2) (time :float))
(v! 0 1 0 0))
(defpipeline-g draw-verts-pipeline ()
:vertex (draw-verts-vert-stage g-pnt)
:fragment (draw-verts-frag-stage))
(defun now ()
(/ (float (get-internal-real-time))
3000))
(defun draw! ()
(step-host)
(setf (resolution (current-viewport))
(surface-resolution (current-surface *cepl-context*)))
(clear)
(map-g #'draw-verts-pipeline *box*
:resolution (viewport-resolution (current-viewport))
:time (now)
:perspective (rtg-math.projection:perspective
(x (resolution (current-viewport)))
(y (resolution (current-viewport)))
0.1 30f0 60f0))
(swap))
(defun init ()
(when *vert-stream*
(free *vert-stream*))
(setf *box* (box 1.0 1.0 1.0)))
(def-simple-main-loop play (:on-start #'init)
(draw!))
| 1,353 | Common Lisp | .lisp | 39 | 27.897436 | 86 | 0.582949 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 9f0ebc11462d77d8d32b9ded0b44d84f86794c214ef648215fecdd52c46ec799 | 9,064 | [
-1
] |
9,065 | resolutionplay.lisp | azimut_shiny/examples/resolutionplay.lisp | (in-package :shiny)
(defun-g vert ((vert :vec2))
(v! vert 0 1))
(defun-g frag (&uniform
(resolution :vec2)
(time :float))
(let* ((c (s~ gl-frag-coord :xy))
(cc (/ time 100))
(c (* c (mod cc 10)))
(r (/ c resolution)))
(v3! (* (x r) (y r)))))
(defpipeline-g mario ()
:vertex (vert :vec2)
:fragment (frag))
(defun reset ())
(defun mynow ()
(* .1 (get-internal-real-time)))-
(defun game-step ()
(clear)
(map-g #'mario (get-quad-stream-v2)
:time (mynow)
:resolution (viewport-resolution
(current-viewport)))
(swap))
(def-simple-main-loop runplay (:on-start #'reset)
(game-step))
| 703 | Common Lisp | .lisp | 26 | 21.192308 | 49 | 0.534328 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 4cd1bbfa6bbe238be5ff20d6afeeb30252848ac9661ed0ec4d6367c57644dd1c | 9,065 | [
-1
] |
9,066 | spiritdeck.lisp | azimut_shiny/examples/spiritdeck.lisp | ;;;; somecepl.lisp
(in-package #:shiny)
;;; "somecepl" goes here. Hacks and glory await!
(defvar *gpu-verts-arr* nil)
(defvar *gpu-index-arr* nil)
(defvar *vert-stream* nil)
(defun-g draw-verts-vert-stage ((vert :vec2))
(v! vert 0 1))
;; float stroke(float x, float s, float w){
;; float d = step(s,x+w*.5) -
;; step(s,x-w*.5);
;; return clamp(d, 0., 1.);
;; }
(defun-g gstroke ((x :float) (s :float) (w :float))
(let* ((d (- (step s (+ x (* .5 w)))
(step s (- x (* .5 w))))))
(clamp d 0.0 1.0))
)
(defun-g grotate ((st :vec2) (a :float))
(let* ((st (* (mat2 (cos a)
(* -1 (sin a))
(sin a)
(cos a))
(- st (v2! .5)))))
(+ (v2! .5) st)))
(defun-g aastep ((threshold :float) (value :float))
(let* ((afwidth (* 0.7 (length (v! (dFdx value) (dFdy value))))))
(smoothstep (- threshold afwidth) (+ threshold afwidth) value)))
(defun-g aastep ((threshold :float) (value :float))
(step threshold value))
(defun-g gfill ((x :float) (size :float))
(- 1.0 (aastep size x)))
(defun-g rectSDF ((st :vec2) (s :vec2))
(let* ((st (- (* st (v2! 2.0)) (v2! 1.0))))
(max (abs (/ (x st) (x s)))
(abs (/ (y st) (y s))))))
; Title: The stone
(defun-g draw-verts-frag-stage (&uniform (resolution :vec2))
(let* ((st (v! (/ (x gl-frag-coord) (x resolution))
(/ (y gl-frag-coord) (y resolution))))
(st (grotate st (radians 45.)))
(color (gfill (rectSDF st (v2! 1.)) .4))
(color (* color (- 1.0 (gstroke (x st) .5 .02))))
(color (* color (- 1.0 (gstroke (y st) .5 .02)))))
(v! color color color 1.0)
)
)
; Title: Temperance
(defun-g draw-verts-frag-stage (&uniform (resolution :vec2))
(let* ((st (v! (/ (x gl-frag-coord) (x resolution))
(/ (y gl-frag-coord) (y resolution))))
(offset (* .15 (cos (* 3.1415 (y st)))))
(color (+ (v3! (gstroke (x st) (+ .28 offset) .1))
(v3! (gstroke (x st) (+ .5 offset) .1))
(v3! (gstroke (x st) (+ .72 offset) .1)))))
(v! color 1.0)
))
(defun-g draw-verts-frag-stage (&uniform (resolution :vec2))
(let* ((st (v! (/ (x gl-frag-coord) (x resolution))
(/ (y gl-frag-coord) (y resolution))))
(color (v! (step .5 (x st))
(step .5 (x st))
(step .5 (x st)))))
(v! color 1.0)
))
;; // Number: VIII
;; // Title: Strength
;; // Author: Patricio Gonzalez Vivo
;; uniform vec2 u_resolution;
;; void main() {
;; vec3 color = vec3(0.);
;; vec2 st = gl_FragCoord.xy/u_resolution;
;; color += step(.5+cos(st.y*PI)*.25,
;; st.x);
;; gl_FragColor = vec4(color,1.);
;; }
(defun-g draw-verts-frag-stage (&uniform (resolution :vec2))
(let* ((st (v! (/ (x gl-frag-coord) (x resolution))
(/ (y gl-frag-coord) (y resolution))))
(color (v! (step (+ .5 (* .25 (cos (* (y st) 3.14159))) ) (x st))
(step (+ .5 (* .25 (cos (* (y st) 3.14159))) ) (x st))
(step (+ .5 (* .25 (cos (* (y st) 3.14159))) ) (x st)))))
(v! color 1.0)
))
;; // Number: XIII
;; // Title: Death
;; // Author: Patricio Gonzalez Vivo
;; uniform vec2 u_resolution;
;; void main() {
;; vec3 color = vec3(0.);
;; vec2 st = gl_FragCoord.xy/u_resolution;
;; color += step(.5,(st.x+st.y)*.5);
;; gl_FragColor = vec4(color,1.);
;; }
(defun-g draw-verts-frag-stage (&uniform (resolution :vec2))
(let* ((st (v! (/ (x gl-frag-coord) (x resolution))
(/ (y gl-frag-coord) (y resolution))))
(color (v! (step .5 (* .5 (+ (y st) (x st))))
(step .5 (* .5 (+ (y st) (x st))))
(step .5 (* .5 (+ (y st) (x st))))
)))
(v! color 1.0)
))
;; // Title: The Wall
;; // Author: Patricio Gonzalez Vivo
;; uniform vec2 u_resolution;
;; void main() {
;; vec3 color = vec3(0.);
;; vec2 st = gl_FragCoord.xy/u_resolution;
;; color += stroke(st.x, .5, .15);
;; gl_FragColor = vec4(color,1.);
;; }
(defun-g draw-verts-frag-stage (&uniform (resolution :vec2)
(step :float)
(other :float)
(time :float))
(let* ((st (v! (/ (x gl-frag-coord) (x resolution))
(/ (y gl-frag-coord) (y resolution))))
(color (v! (gstroke (x st) step .15)
(gstroke (x st) (sin (+ step time)) .1)
(gstroke (x st) (cos other) .1))))
(v! color 1.0)
))
(defpipeline-g draw-verts-pipeline ()
:vertex (draw-verts-vert-stage :vec2)
:fragment (draw-verts-frag-stage))
(defun now ()
(* .001 (get-internal-real-time)))
(defun draw! ()
(step-host)
(setf (resolution (current-viewport))
(surface-resolution (current-surface (cepl-context))))
(clear)
(map-g #'draw-verts-pipeline *vert-stream*
:step (cm:interp *current-note* 30 0.0 90 1.0)
:other (cm:interp *other-note* 30 0.0 90 1.0)
:time (now)
:resolution (viewport-resolution (current-viewport)))
(swap))
(defparameter *current-note* 40)
(defparameter *other-note* 40)
(defun init ()
(when *gpu-verts-arr*
(free *gpu-verts-arr*))
(when *gpu-index-arr*
(free *gpu-index-arr*))
(when *vert-stream*
(free *vert-stream*))
(setf *gpu-verts-arr*
(make-gpu-array
(list (v! -1.0 1.0)
(v! -1.0 -1.0)
(v! 1.0 -1.0)
(v! 1.0 1.0))
:element-type :vec2))
(setf *gpu-index-arr*
(make-gpu-array
(list 0 1 2
0 2 3)))
(setf *vert-stream*
(make-buffer-stream *gpu-verts-arr*
:index-array *gpu-index-arr*)))
(def-simple-main-loop play (:on-start #'init)
(draw!))
| 6,045 | Common Lisp | .lisp | 164 | 29.487805 | 77 | 0.490937 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 3352d2253a223d81d018f35ed6be095034d68e2d59afa661157636577d5a9d19 | 9,066 | [
-1
] |
9,067 | incudinepiano2.lisp | azimut_shiny/examples/incudinepiano2.lisp | (in-package :shiny)
;; https://sourceforge.net/p/incudine/mailman/message/31182999/
;; small sample-player example for incudine. For this to work you'll
;; need to adjust the path to *ssdir* and put the Bosen_mf_... samples
;; into *ssdir*.
;;
;; This file is in the public domain. Use at own risk. No guarantees
;; whatsoever.
;;(defparameter *ssdir* #.(or *compile-file-pathname* *load-pathname*))
(defparameter *ssdir* "/home/sendai/Downloads/morepiano/piano-sampler-incudine/")
(defparameter *ssdir-f* "/home/sendai/Downloads/samples/pianosample/SalamanderGrandPianoV2_44.1khz16bit/44.1khz16bit/")
(setf *ssdir* "/home/sendai/Downloads/morepiano/piano-sampler-incudine/")
(setf *ssdir-f* "/home/sendai/Downloads/samples/pianosample/SalamanderGrandPianoV2_44.1khz16bit/44.1khz16bit/")
(defstruct lsample
"structure for a sample with two loop-points. The structure also
contains a slot for the sample buffer data."
file
buffer
(keynum +sample-zero+ :type incudine.util:sample)
(loopstart +sample-zero+ :type incudine.util:sample)
(loopend +sample-zero+ :type incudine.util:sample))
(defun generate-lsample-map (lsample-defs &key (ssdir *ssdir*))
"map a list of sample defs of the form (filename keymap-upper-bound
original-keynum loopstart loopend) into a freshly allocated lookup
array containing an lsample-struct entry for 127 keynums. The buffer
slots of the lsamples are filled with the sample data. The array is
returned."
(let ((lsample-map (make-array 128 :adjustable nil :element-type 'lsample)))
(loop
:for lsample-def
:in (sort lsample-defs #'(lambda (x y) (< (second x) (second y))))
:with array-idx = -1
:do (destructuring-bind
(file keymap-upper-bound keynum loopstart loopend)
lsample-def
(let ((lsample ;;; make lsample from lsample-def and fill slots
(let ((full-name (merge-pathnames file ssdir)))
(make-lsample :file full-name
:buffer (buffer-load full-name)
:keynum (incudine.util:sample keynum)
:loopstart (incudine.util:sample loopstart)
:loopend (incudine.util:sample loopend)))))
(do () ;;; fill array with references to the lsample
((>= array-idx keymap-upper-bound))
(setf (aref lsample-map (incf array-idx)) lsample)))))
lsample-map))
;; (defparameter *piano-map*
;; (generate-lsample-map
;; '(("BOSEN_mf_A0_mn.wav" 36 33 121642 197454)
;; ("BOSEN_mf_D1_mn.wav" 43 38 93488 166611);
;; ("BOSEN_mf_C2_mn.wav" 51 48 95464 151802)
;; ("BOSEN_mf_F2_mn.wav" 58 53 77922 137052)
;; ("BOSEN_mf_D#3_mn.wav" 68 63 82246 132839)
;; ("BOSEN_mf_C#4_mn.wav" 76 73 64379 104238)
;; ("BOSEN_mf_F#4_mn.wav" 81 78 57945 59609)
;; ("BOSEN_mf_B4_mn.wav" 127 83 48970 50748)) :ssdir *ssdir*))
;; (defparameter *piano-map-f*
;; (generate-lsample-map
;; '(("A0v10.wav" 36 33 121642 197454) ;k
;; ("D#1v10.wav" 43 38 93488 166611) ;?
;; ("C2v10.wav" 51 48 95464 151802) ;k
;; ("F#2v10.wav" 58 53 77922 137052) ;?
;; ("D#3v10.wav" 68 63 82246 132839) ;k
;; ("C4v10.wav" 76 73 64379 104238) ;?
;; ("F#4v10.wav" 81 78 57945 59609) ;k
;; ("C5v10.wav" 127 83 48970 50748)) :ssdir *ssdir-f*)) ;?
(defparameter *piano-map-f*
(generate-lsample-map
'(("A0v10.wav" 21 21 100000 500000) ;k
("A2v10.wav" 45 45 100000 500000 )
("A2v10.wav" 45 45 100000 500000 )
("A4v10.wav" 69 69 100000 500000 )
("A6v10.wav" 93 93 100000 500000 )
("C1v10.wav" 24 24 100000 500000 )
("C3v10.wav" 48 48 100000 500000 )
("C5v10.wav" 72 72 100000 500000 )
("C7v10.wav" 96 96 100000 500000 )
("D#1v10.wav" 27 27 100000 500000 )
("D#3v10.wav" 51 51 100000 500000 )
("D#5v10.wav" 75 75 100000 500000 )
("D#7v10.wav" 99 99 100000 500000 )
("F#2v10.wav" 42 42 100000 500000 )
("F#4v10.wav" 66 66 100000 500000 )
("F#6v10.wav" 90 90 100000 500000 )
("A1v10.wav" 33 33 100000 500000 )
("A3v10.wav" 57 57 100000 500000 )
("A5v10.wav" 81 81 100000 500000 )
("A7v10.wav" 105 105 100000 500000 )
("C2v10.wav" 36 36 100000 500000 )
("C4v10.wav" 60 60 100000 500000 )
("C6v10.wav" 84 84 100000 500000 )
("C8v10.wav" 108 108 100000 500000 )
("D#2v10.wav" 39 39 100000 500000 )
("D#4v10.wav" 63 63 100000 500000 )
("D#6v10.wav" 87 87 100000 500000 )
("F#1v10.wav" 30 30 100000 500000 )
("F#3v10.wav" 54 54 100000 500000 )
("F#5v10.wav" 78 78 100000 500000 )
("F#7v10.wav" 102 102 100000 500000 )) :ssdir *ssdir-f*)) ;?
(declaim (inline get-lsample))
(defun get-lsample (keynum map)
(aref map (min keynum 127)))
;; example: (get-lsample 61 *piano-map*)
;; -> #S(LSAMPLE
;; :FILE "/home/orm/work/snd/csound/BOSEN_mf_D#3_mn.wav"
;; :BUFFER #<BUFFER :FRAMES 132917 :CHANNELS 1 :SR 44100.0>
;; :KEYNUM 63
;; :LOOPSTART 82246
;; :LOOPEND 132839)
(declaim (inline ct->fv))
(defun ct->fv (steps)
"halfsteps to ratio"
(expt #.(coerce 2.0 'incudine.util:sample)
(* steps #.(coerce 1/12 'incudine.util:sample))))
(defparameter *env1* (make-envelope '(0 1 1 0) '(0 .9 .1)))
(define-vug buffer-loop-play
((buffer buffer) rate start-pos loopstart loopend)
(with-samples
((frame (phasor-loop rate start-pos loopstart loopend)))
(buffer-read buffer frame :interpolation :cubic)))
;; (dsp! play-lsample (keynum dur amp)
;; (with ((lsample (get-lsample (sample->fixnum keynum) *piano-map*)))
;; ; (with ((lsample (get-lsample keynum *piano-map*)))
;; (with-samples ((rate (ct->fv (- keynum (lsample-keynum lsample))))
;; (loopstart (lsample-loopstart lsample))
;; (loopend (lsample-loopend lsample)))
;; (with ((buffer (lsample-buffer lsample)))
;; (stereo (* amp
;; (envelope *env1* 1 dur #'incudine:stop)
;; (buffer-loop-play buffer rate 0 loopstart loopend)))))))
(dsp! play-lsample-f (keynum dur amp)
(with ((lsample (get-lsample (sample->fixnum keynum) *piano-map-f*)))
; (with ((lsample (get-lsample keynum *piano-map-f*)))
(with-samples
((rate (ct->fv (- keynum (lsample-keynum lsample))))
(loopstart (lsample-loopstart lsample))
(loopend (lsample-loopend lsample)))
(with ((buffer (lsample-buffer lsample)))
(stereo (* amp
(envelope *env1* 1 dur #'incudine:stop)
(buffer-loop-play buffer rate 0 loopstart loopend)))))))
;; examples:
#|
(play-lsample (+ 50 (random 30)) 3 0.6)
(play-lsample-f (+ 50 (random 30)) 3 .6)
(play-lsample 60 3 .6)
(play-lsample-f 60 3 .6)
(loop
for x from 1 to 200
for time = (now) then (+ time (* *sample-rate* (random 0.05)))
for amp = (+ 0.2 (random 0.2)) then (+ 0.2 (random 0.2))
do (at time #'play-lsample (+ 70 (random 20.0)) 2 amp))
|#
#|
(beatme 60)
(flush-pending)
|#
;; --------------------------------------------------------------------
;; Playfield
;; --------------------------------------------------------------------
(defun beatme (root)
(play-lsample-f root .35 .3)
(at (+ (now) #[2 b]) #'beatme 60))
(defvar *myscale* nil)
(setf *myscale* (scale 0 'lydian))
(setf *myscale* (scale 0 'aeolian))
;; Random notes within the scale
(defun testscale ()
(play-lsample-f (qcosr *myscale* 60 7 3) 3.0 .3)
(at (+ (now) #[1 b]) #'testscale))
;; Random chord from the scale
(defun testchord ()
(mapcar (lambda (x) (play-lsample-f x 3.0 .3))
(make-chord 50 60 (cosr 2 1 .2) *myscale*))
(at (+ (now) #[2 b]) #'testchord))
#|
(testscale)
(testchord)
|#
;; --------------------------------------------------------------------
;; GOTO 2014 • Programming In Time - Live Coding for Creative Performances
;; https://www.youtube.com/watch?v=Sg2BjFQnr9s
;; --------------------------------------------------------------------
#|
(defun seq-test (&optional (root 60))
(let* ((newroot (random-list (cdr (assoc root '((60 58 55)
(58 60 56)
(56 55 58)
(55 60 56)))))))
(dsp-seq
(play-lsample (+ root -12) .35 .3)
(play-lsample (+ -5 root) .35 .3)
;(play-lsample (- root 12) 1 .2 :id 2)
;(play-lsample (+ 12 root) 1 .2 :id 3)
(seq-test newroot))))
|#
(setf (bpm *tempo*) 120)
;; trying "markov chains" from extempore demo
(defun left (&optional (root 60))
(let* ((newroot (random-list (cdr (assoc root '((60 58)
(58 60)))))))
(play-lsample-f (- root 12) 2. .25)
(at (+ (now) #[3/2 b]) #'play-lsample-f (+ -5 root) 2. .3)
(at (+ (now) #[4 b]) #'left newroot)))
(defun left (&optional (root 60))
(let* ((newroot (random-list (cdr (assoc root '((60 58 55)
(58 60 56)
(56 55 58)
(55 60 56)))))))
(play-lsample-f (- root 12) 1.9 .25)
(at (+ (now) #[3/2 b]) #'play-lsample-f (+ -5 root) 1.9 .27)
(at (+ (now) #[4 b]) #'left newroot)))
(defvar *root* nil)
(setf *root* 60)
(defvar *myscale* nil)
(setf *myscale* (scale 0 'aeolian))
(defun left ()
(setf *root* (random-list (cdr (assoc *root* '((60 58 55)
(58 60 56)
(56 55 58)
(55 60 56))))))
(play-lsample-f (- *root* 12) 1.9 .2)
(at (tempo-sync #[3/2 b]) #'play-lsample-f (+ -5 *root*) 1.9 .1)
(at (tempo-sync #[4 b]) #'left))
(defun right ()
(play-lsample-f (round (cosr *root* 7 3/2)) 1.4 .1)
(at (tempo-sync #[.5 b]) #'right)
)
(defun right ()
(play-lsample-f (round (qcosr *myscale* *root* 7 3/2)) 1.4 .1)
(at (tempo-sync #[.5 b]) #'right)
)
(left)
(right)
(flush-pending)
;; --------------------------------------------------------------------
;;
;; --------------------------------------------------------------------
(defvar *myscale* nil)
(setf *myscale* '(0 2 3 5 7 8 10) )
(setf *myscale* '(0 1 3 5 6 8 10) )
(defun right ()
(play-lsample-f (qcosr *myscale* 60 7 3/4) 1. .2)
(at (+ (now) #[.5 b]) #'right)
)
(defun right ()
(play-lsample-f (random-list '(53 55 60 65 67)) 1.1 .2)
(at (+ (now) #[.5 b]) #'right)
)
(defvar *tun*
(make-tuning :notes '(16/15 9/8 6/5 5/4 4/3 7/5 3/2 8/5 5/3 9/5 15/8 2/1)
:description "Basic JI with 7-limit tritone. Robert Rich: Geometry"))
(defun right ()
(play-lsample-f (random-list (subseq (buffer->list *tun*) 30 37)) 2. .1)
(at (+ (now) #[.5 b]) #'right)
)
;; --------------------------------------------------------------------
;; Playground 2
;; --------------------------------------------------------------------
(defvar *root* nil)
(setf *root* 0)
(defvar *degree* nil)
(setf *degree* 'i)
(defun pchord ()
(play-lsample-f 60 1. .8)
(play-lsample-f 64 1. .8)
(play-lsample-f 67 1. .8)
)
(pchord)
(defun dancingl (dur)
(play-lsample-f 36
(* dur (cosr .6 .3 1/7))
(cosr .6 .3 1/7))
(aat (+ (now) #[2 b]) #'dancingl (random-list '(1 2/3))))
(dancingl 4)
#|
(left)
(incudine:free 0)
(flush-pending)
(right)
(dancingl 2/3)
|#
;; --------------------------------------------------------------------
;; src/overtone/examples/compositions/piano_phase.clj
;; --------------------------------------------------------------------
#|
(defn player
[t speed notes]
(let [n (first notes)
notes (next notes)
t-next (+ t speed)]
(when n
(at t
(sampled-piano (note n)))
(apply-by t-next #'player [t-next speed notes]))))
|#
(defvar *piece* nil)
(setf *piece* '(:E4 :F#4 :B4 :C#5 :D5 :F#4 :E4 :C#5 :B4 :F#4 :D5 :C#5))
(setf (bpm *tempo*) 100)
(defun player (time speed notes)
(let ((n (first notes))
(notes (cdr notes))
(t-next (+ time speed)))
(when n
(play-lsample-f (note-name-to-midi-number (symbol-name n)) 5.0 .3)
(at t-next #'player t-next speed notes))))
(let ((time (now)))
(player (now) #[.338 b] (repeat 1000 *piece*))
(player (now) #[.335 b] (repeat 1000 *piece*)))
;; --------------------------------------------------------------------
;; Extempore - An Overview
;; https://vimeo.com/21956071
;; at 11:30
;; --------------------------------------------------------------------
#|
(define loop
(lambda (beat dur root)
(for-each (lambda (p offset)
(play (+ offset) sampler p 100 (* 2.0 dur)))
(pc:make-chord 40 (cosr 75 10 1/32) 5
(pc:chord root (if (member root '(10 8))
'^7
'-7)))
'(1/3 1 3/2 1 2 3))
(callback (*metro* (+ beat (* .5 dur))) 'loop (+ dur beat)
dur
(if (member root '(0 8))
(random '(2 7 10))
(random '(0 8))))))
(loop (*metro* get-beat 4) 4 0)
|#
(defvar *beat-offset* nil)
(setf *beat-offset* '(1/3 1 3/2 1 2 3))
(setf *beat-offset* '(1/3 4 1 1.5))
(setf (bpm *tempo*) 100)
(setf (bpm *tempo*) 60)
(defun sometune (dur root)
(let ((time (now)))
(at (+ time #[3 b]) #'play-lsample-f 36 5.0 1.0)
(mapcar (lambda (x y)
(at (+ time #[y b]) #'play-lsample-f x 9.0 1.0))
(make-chord 40
(cosr 75 10 1/32)
5
(chord root (if (member root '(10 8))
'^7
'-7)))
*beat-offset*)
(at (+ time #[dur b]) #'sometune
dur
(if (member root '(0 8))
(random-list '(2 7 10))
(random-list '(0 8))))))
(setf *beat-offset* (reverse *beat-offset*))
(setf *beat-offset* '(0 0.1 1/3 0.7 0.9 0.9))
(setf *beat-offset* '(0 0.2 1/3 0.5 0.8))
(setf *beat-offset* '(0 0.2 0.4 0.6 0.8))
(setf *beat-offset* '(0 0.1 0.2 0.3 0.4))
(setf *beat-offset* '(0 0.1 0.11 0.13 0.15 0.17 0.2 0.4 0.5 0.55 0.6 0.8))
(sometune 4 0)
#|
(incudine:free 0)
(flush-pending)
|#
;; --------------------------------------------------------------------
;; Ben S.
;; A late christmas
;; --------------------------------------------------------------------
#|
(define loop1
(lambda (beat dur)
(play piano 60 50 dur)
(callback (*metro* (+ beat (* .5 dur))) 'loop1 (+ beat dur) dur)))
|#
(defun loop1 (beat dur)
(play-lsample-f 60 dur .4)
(print beat)
(print dur)
(at (+ (now)
(+ #[beat b] (* .5 #[dur b]))) #'loop1 (+ beat dur) dur))
(loop1 3 2)
;; --------------------------------------------------------------------
;; "A study in Keith"
;; https://www.youtube.com/watch?v=tQIQwQnX3hA
;; https://gist.github.com/CircuV/0834dbbd2034b82b7706
;; --------------------------------------------------------------------
#|
(define chords
(lambda (time degree dur)
(println time degree dur)
(if (member degree '(i)) (set! dur 3))
(for-each
(lambda (p)
(play-midi-note
(*metro* time)
*midi-out*
p
(real->integer (+ 50 (* 20 (cos (* pi time)))))
(*metro* 'dur dur)
0))
(pc:make-chord 50 70 2 (pc:diatonic 0 '- degree))
)
(callback (*metro* (+ time (* 0.5 dur))) 'chords (+ time dur)
(random (assoc degree '((i vii)
(vii i))))
dur)))
|#
(defvar *myscale* nil)
(setf *myscale* (scale 0 'aeolian))
(setf (bpm *tempo*) 100)
(defun chords (degree dur)
(if (member degree '(i)) (setf dur 3))
(mapcar
(lambda (p) (play-lsample-f p 3.0 .4))
(make-chord 50 70 2 (diatonic 0 '- degree)))
(at (+ (now) #[dur b]) #'chords
(random-list (assoc degree '((i vii)
(vii i))))
dur))
(chords 'i 3)
#|
(define chords
(lambda (time degree dur)
(if (member degree '(i)) (set! dur 3.0))
(println time degree dur)
(for-each (lambda (p)
(let* ((dur1 (* dur (random '(0.5 1))))
(dur2 (- dur dur1)))
(play-midi-note (*metro* time) *midi-out* p
(real->integer(+ 50 (* 20 (cos (* pi time)))))
(*metro* 'dur dur1) 0)
(if (> dur2 0)
(play-midi-note (*metro* (+ time dur1)) *midi-out*
(pc:relative p (random '(-2 -1 1 2))
(pc:scale 0 'aeolian))
(real->integer (+ 50 (* 20 (cos (* pi (+ time dur1))))))
(*metro* 'dur dur2) 0 ))))
(pc:make-chord 50 70 2 (pc:diatonic 0 '- degree)))
(callback (*metro* (+ time (* 0.5 dur))) 'chords (+ time dur)
(random (assoc degree '((i vii)
(vii i))))
(random (list 1 2 3)))))
|#
(defun chords (degree dur)
; (if (member degree '(i)) (setf dur 3.0))
(if (member degree '(i)) (setf dur (random-list '(3.0 6.0))))
; 4:00
(let* ((nnote (car (diatonic 0 '- degree))))
;; Hack needed when degree returns 2 , which is converted by pcrrandom in -1
(if (= nnote 2) (setf nnote (cadr (diatonic 0 '- degree))))
(play-lsample-f (pcrrandom 40 50 (list nnote))
dur .4))
(mapcar
(lambda (p) (let* ((dur1 (* dur (random-list '(0.5 1))))
(dur2 (- dur dur1)))
(play-lsample-f p dur1 .4)
(if (> dur2 0)
(at (+ (now) #[dur1 b]) #'play-lsample-f
(relative p (random-list '(-2 -1 1 2)) (scale 0 'aeolian))
dur1
.4))))
; (make-chord 50 70 2 (diatonic 0 '- degree)))
(make-chord 50 70 3 (diatonic 0 '- degree)))
(at (+ (now) #[dur b]) #'chords
; (random-list (assoc degree '((i vii)
; (vii i))))
;; (random-list (assoc degree '((i vii)
;; (vii i v)
;; (v i))))
(random-list (assoc degree '((i vii)
(vii i v)
(v i vi)
(vi ii)
(ii v vii))))
(random-list '(1 2 3))))
;; --------------------------------------------------------------------
;; DANCING PHALANGES
;; --------------------------------------------------------------------
(setf (bpm *tempo*) 110)
(setf (bpm *tempo*) 80)
(defvar *root* nil)
(setf *root* 0)
(defvar *degree* nil)
(setf *degree* 'i)
(defvar *scale* nil)
(setf *scale* (scale 0 'phrygian))
(defun melody (ms rs)
(if (not ms)
'done
(let ((p (car ms)))
(play-lsample-f (quant (+ 48 *root* p) *scale*)
(* (car rs) (cosr .9 .2 1/2)) .9)
(play-lsample-f (quant (+ 55 *root* p) *scale*)
(* (car rs) (cosr .9 .2 1/2)) .9)
(at (+ (now) #[(car rs) b]) #'melody (cdr ms) (cdr rs))
)))
(defun right (degree)
(setf *degree* degree)
(setf *root* (car (diatonic 0 '- degree)))
(at (+ (now) #[4 b]) #'right (random-list (cdr (assoc degree '((i n6 iii vii)
(n6 v7)
(iii v7)
(vii vi)
(vi vii v7 v7)
(v7 i))))))
)
(right 'i)
(defun left (dur)
(if (> (random 1.0) .85) (melody '(0 1 0 -1) '(1/3 2/3 2/3 1)))
(play-lsample-f (+ 48 *root*) (* dur (cosr .9 .3 1/7)) (cosr .6 .3 1/2))
(play-lsample-f 36 (* dur (cosr .9 .3 1/7)) (cosr .6 .3 1/2))
(at (tempo-sync #[dur b]) #'left (random-list '(1 2/3))))
(progn
(right 'i)
(left 2/3)
)
(flush-pending)
;; --------------------------------------------------------------------
;; Another late christmas
;; --------------------------------------------------------------------
(defun loop1 (beat dur)
;; (play-lsample-f 60 dur .3)
(play-lsample-f (if (= (mod (get-internal-real-time) 12) 0)
67
(random-list '(60 60 60 58)))
dur .3)
(at (tempo-sync #[(* .5 dur) b]) #'loop1 (+ beat .5) dur))
;; (at (+ (now) #[(* .5 dur) b]) #'loop1 (+ beat .5) dur))
(flush-pending)
(defun s ()
;; '(0)
'(0 2 3 5 7 10)
)
(defun loop2 (dlist pitch slist)
(if (car slist)
(play-lsample-f (relative pitch (car slist) (s))
(car dlist)
.3))
(at (tempo-sync #[(car dlist) b]) #'loop2 (rotate dlist -1) pitch (rotate slist -1)))
;; (at (+ (now) #[(car dlist) b]) #'loop2 (rotate dlist -1) pitch (rotate slist -1)))
(loop1 0 1)
(loop2 '(1 1/2 1/2 1/2 1/2) 63 '(2 1 2 0 nil))
;; Ah!...tempo...I mean beat...without it I cannot sync two things...dah!
| 21,227 | Common Lisp | .lisp | 543 | 31.941068 | 119 | 0.493642 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 03264ad1d869808c5073fe0cfe6e8071f54c3427d8d4cb3c6f609cdb117b3ae3 | 9,067 | [
-1
] |
9,068 | 20180305.lisp | azimut_shiny/examples/20180305.lisp | (in-package :shiny)
#|
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv=fragCoord.xy/iResolution.xy-.5;
uv.y*=iResolution.y/iResolution.x;
vec3 dir=vec3(uv*zoom,1.);
float time=iTime*speed+.25;
vec3 from=vec3(1.,.5,0.5);
from+=vec3(time*2.,time,-2.);
float s=0.1,fade=1.;
vec3 v=vec3(0.);
for (int r=0; r<volsteps; r++) {
vec3 p=from+s*dir*.5;
p = abs(vec3(tile)
-mod(p,vec3(tile*2.)));
float pa,a=pa=0.;
for (int i=0; i<iterations; i++) {
p=abs(p)/dot(p,p)
-formuparam;
a+=abs(length(p)-pa);
pa=length(p);
}
float dm=max(0.,darkmatter-a*a*.001); //dark matter
a*=a*a; // add contrast
v+=vec3(s,s*s,s*s*s*s)
*a
*brightness
*fade;
}
fragColor = vec4(v*.01,1.);
}
// Star Nest by Pablo Román Andrioli
// This content is under the MIT License.
#define iterations 17
#define formuparam 0.53
#define volsteps 20
#define stepsize 0.1
#define zoom 0.800
#define tile 0.850
#define speed 0.010
#define brightness 0.0015
#define darkmatter 0.300
#define distfading 0.730
#define saturation 0.850
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
//get coords and direction
vec2 uv=fragCoord.xy/iResolution.xy-.5;
uv.y*=iResolution.y/iResolution.x;
vec3 dir=vec3(uv*zoom,1.);
float time=iTime*speed+.25;
vec3 from=vec3(1.,.5,0.5);
from+=vec3(time*2.,time,-2.);
//volumetric rendering
float s=0.1,fade=1.;
vec3 v=vec3(0.);
for (int r=0; r<volsteps; r++) {
vec3 p=from+s*dir*.5;
p = abs(vec3(tile)
-mod(p,vec3(tile*2.)));
//<- tiling fold
float pa,a=pa=0.;
for (int i=0; i<iterations; i++) {
p=abs(p)/dot(p,p)
-formuparam;
//<- the magic formula
a+=abs(length(p)-pa); // absolute sum of average change
pa=length(p);
}
float dm=max(0.,darkmatter-a*a*.001); //dark matter
a*=a*a; // add contrast
if (r>6) fade*=1.-dm; // dark matter, don't render near
//v+=vec3(dm,dm*.5,0.);
v+=fade;
v+=vec3(s,s*s,s*s*s*s)
*a
*brightness
*fade;
// coloring based on distance
fade*=distfading; // distance fading
s+=stepsize;
}
v=mix(vec3(length(v)),v,saturation); //color adjust
fragColor = vec4(v*.01,1.);
}
|#
(defclass actor ()
((pos :initform (v! 0 0 0) :initarg :pos)
(rot :initform 0f0 :initarg :rot)
(scale :initform 1f0 :initarg :scale)
(rows :initform 1f0 :initarg :rows)
(speed :initform 1f0 :initarg :speed)
(width :initform 1f0 :initarg :width)
(columns :initform 1f0 :initarg :columns)
(visual :initarg :visual)))
(defvar *screen-height* 1f0)
(defvar *actors* nil)
(defun mynow ()
;; Just some number that increases over time that we use
;; in a bunch of places
(/ (get-internal-real-time)
1000f0))
(defvar *gpu-verts-arr* nil)
(defvar *gpu-index-arr* nil)
(defvar *vert-stream* nil)
;; --------------------------------------------------
;;(defvar *cube-stream* nil)
(defvar *cam-pos* (v! 0 0 0))
(defvar *blend* (make-blending-params))
;; --------------------------------------------------
(defvar *samplers* (make-hash-table :test #'equal))
(defun load-tex (rel-path)
(or (gethash rel-path *samplers*)
(let* ((path (asdf:system-relative-pathname :somecepl rel-path))
(tex (load-image-to-texture path)))
(setf (gethash rel-path *samplers*)
(sample tex)))))
;; --------------------------------------------------
(defun-g vert ((vert :vec2) &uniform
(scale :float)
(pos :vec3)
(width :float)
(screen-height :float)
(screen-ratio :float))
(values (v! (/ (+ (s~ pos :xy)
(* scale vert))
(v! (* screen-ratio (/ 1f0 width))
screen-height))
0 1)
(+ (v2! .5) (* vert .5))))
(defun-g frag ((uv :vec2)
&uniform
(speed :float)
(rows :float)
(columns :float)
(time :float)
(resolution :vec2)
(sam :sampler-2d)
(cam-pos :vec3))
;; 8 = width size
;; time ...mod does not matter...
;; .125 = 1/8
;; -1 ...flip vertically
;; /2 ... pick one row of the two
(let* (
(time (* speed time))
(mtime (if (equal columns 1)
(mod time columns)
(floor (mod time columns))))
(vx (+ (* (* -1 mtime)
(/ 1f0 columns))
(/ (x uv)
columns)))
(vy (/ (* -1 (y uv))
rows))
;;; (vx (* (cos time) vx))
;;; (vy (* (cos time) vy))
;;; wibble
(t-uv (v! vx vy))
(color (texture sam t-uv))
)
color))
;; --------------------------------------------------
(defpipeline-g mario ()
:vertex (vert :vec2)
:fragment (frag :vec2))
(defun init ()
(setf *screen-width* 1f0)
;; (setf (clear-color) (v! .46 .57 .69 1))
(setf (clear-color) (v! 0 0 0 1))
(setf *actors* nil)
(unless *actors*
(setf *actors*
(make-array 0 :element-type 'actor
:adjustable t
:fill-pointer 0))
(vector-push-extend
(make-instance
'actor
:visual (load-tex "parallax-forest-front-trees.png")
:columns 1f0
:speed .5f0
:width 2f0
:rows 1f0) *actors*)
(vector-push-extend
(make-instance
'actor
:visual (load-tex "scottpilgrim_multiple.png")
:columns 8f0
:scale .3f0
:speed 7f0
:pos (v! 0 -.6 0)
:rows 2f0) *actors*))
(when *gpu-verts-arr*
(free *gpu-verts-arr*))
(when *gpu-index-arr*
(free *gpu-index-arr*))
(when *vert-stream*
(free *vert-stream*))
(setf *gpu-verts-arr*
(make-gpu-array
(list (v! -1.0 1.0)
(v! -1.0 -1.0)
(v! 1.0 -1.0)
(v! 1.0 1.0))
:element-type :vec2))
(setf *gpu-index-arr*
(make-gpu-array
(list 0 1 2
0 2 3)))
(setf *vert-stream*
(make-buffer-stream *gpu-verts-arr*
:index-array *gpu-index-arr*)))
(defun draw! ()
(step-host)
(clear)
(let ((res (surface-resolution (current-surface))))
(setf (resolution (current-viewport))
res)
(with-setf* ((depth-test-function) nil)
(with-blending *blend*
(loop :for x :across *actors* :do
(with-slots (rows speed width columns pos scale visual) x
(map-g #'mario *vert-stream*
:time (mynow)
:rows rows
:speed speed
:columns columns
:scale scale
:screen-height *screen-height*
:width width
:screen-ratio (/ (x res) (y res))
:pos pos
:resolution res
:sam visual
:cam-pos *cam-pos*))))))
(swap)
)
(def-simple-main-loop runplay (:on-start #'init)
(draw!))
| 7,253 | Common Lisp | .lisp | 241 | 22.506224 | 70 | 0.51332 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 2abf27ce78c9b083fa22f1928428451d19efa98f1430adb7403da73d33f1702e | 9,068 | [
-1
] |
9,069 | simpleincudine.lisp | azimut_shiny/examples/simpleincudine.lisp | ;;;; somecepl.lisp
(in-package #:shiny)
;; ----------------------------------
;; ----------------------------------
;; From Music V family.
(define-vug rms (in hp)
(:defaults 0 60)
(with-samples ((b (- 2 (cos (* hp *twopi-div-sr*))))
(c2 (- b (sqrt (the non-negative-sample (1- (* b b))))))
(c1 (- 1 c2))
(in2 (* in in))
(q +sample-zero+))
(sqrt (the non-negative-sample (~ (+ (* c1 in2) (* c2 it)))))))
(dsp! rms-master-out-test2 ()
(setf (bus 100)
(rms (audio-out 0))))
(defun rms-master ()
(coerce (incudine.util:barrier (:memory) (bus 100)) 'single-float))
(rms-master-out-test2 :id 100 :tail 0)
(rms-master)
;; ----------------------------------
;; ----------------------------------
(defvar env2 (make-perc .001 .4))
(dsp! env-test-3 (freq amp pos (env envelope) gate)
(foreach-channel
(cout (pan2 (* (envelope env gate 1 #'stop)
(sine freq amp 0))
pos))))
(defun seq-test (rep freq amp pos)
(when (plusp rep)
(dsp-seq (env-test-3 freq amp pos env2 1)
(env-test-3 (* freq 7/4) amp pos env2 1)
(env-test-3 (* freq 2) amp pos env2 1)
(seq-test (1- rep) freq amp pos))))
(defun phr1 (time)
(at time #'seq-test 8 200 .3 .5)
(at (+ time #[2 b]) #'seq-test 6 400 .3 .4)
(at (+ time #[4 b]) #'seq-test 4 600 .3 .6))
(setf (bpm *tempo*) 120)
(phr1 (now))
;; ----------------------------------
;; "somecepl" goes here. Hacks and glory await!
;; ----------------------------------
(defvar *gpu-verts-arr* nil)
(defvar *gpu-index-arr* nil)
(defvar *vert-stream* nil)
(defun-g draw-verts-vert-stage ((vert :vec2))
(v! vert 0 1))
(defun-g draw-verts-frag-stage (&uniform (resolution :vec2)
(time :float)
(rms :float))
(let* ((st (v! (/ (x gl-frag-coord) (x resolution))
(/ (y gl-frag-coord) (y resolution))))
(color (v! (step .5 (x st))
(step .5 (x st))
(step .5 (x st)))))
(v! rms rms rms 1.0)
))
(defpipeline-g draw-verts-pipeline ()
:vertex (draw-verts-vert-stage :vec2)
:fragment (draw-verts-frag-stage))
(defun draw! ()
(step-host)
(setf (resolution (current-viewport))
(surface-resolution (current-surface (cepl-context))))
(clear)
(map-g #'draw-verts-pipeline *vert-stream*
:resolution (viewport-resolution (current-viewport))
:time (mynow)
:rms .52)
(swap))
(defun runinit ()
(when *gpu-verts-arr*
(free *gpu-verts-arr*))
(when *gpu-index-arr*
(free *gpu-index-arr*))
(when *vert-stream*
(free *vert-stream*))
(setf *gpu-verts-arr*
(make-gpu-array
(list (v! -1.0 1.0)
(v! -1.0 -1.0)
(v! 1.0 -1.0)
(v! 1.0 1.0))
:element-type :vec2))
(setf *gpu-index-arr*
(make-gpu-array
(list 0 1 2
0 2 3)))
(setf *vert-stream*
(make-buffer-stream *gpu-verts-arr*
:index-array *gpu-index-arr*)))
(def-simple-main-loop runplay (:on-start #'runinit)
(draw!))
| 3,250 | Common Lisp | .lisp | 94 | 27.265957 | 74 | 0.489933 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | d0ebe056a90e9514f50537e5c63a82e09ad8a86b8d43c0b7eac0b49e975b6ab4 | 9,069 | [
-1
] |
9,070 | class29.lisp | azimut_shiny/examples/class29.lisp | ;;;; somecepl.lisp
(in-package #:shiny)
;;; "somecepl" goes here. Hacks and glory await!
(defvar *gpu-verts-arr* nil)
(defvar *gpu-index-arr* nil)
(defvar *vert-stream* nil)
(defparameter *texture* nil)
(defvar *offset* nil)
(defun-g draw-verts-vert-stage ((vert :vec2))
(values (v! vert 0 1)
(+ (v2! 0.5) (* vert 0.5))))
(defun-g draw-verts-frag-stage ((uv :vec2) &uniform (resolution :vec2)
(time :float)
(sam :sampler-2d)
(offset :vec2))
(let* ((st (/ (s~ gl-frag-coord :xy)
(v! 1024. 768.) ))
; (v (* 5.0 0.4))
; (mode 0.0)
; (scTime (* time .01))
(dt0 (* 100. (y st) (step (+ 0.8 (* 0.8 (sin time)))
(mod time 1.0))))
(dt (* 10. (x st) (step (+ 0.5 (* 0.5 (sin time)))
(mod time 1.0))))
(dt2 (* 10. (y st) (step (+ 0.5 (* 0.5 (sin time)))
(mod time 1.0))))
(dx 100.)
(color (texture sam uv))
(color2 (v! (s~ (texture sam (+ uv (v2! (* dx (x offset)) 0.0)) ) :xyz)
1.0))
(color3 (v! (s~ (texture sam (+ uv (v2! (* -100.0 (x offset)) 0.0)) ) :xyz)
1.0))
(minVX (step 0.2
(* 5.0 (mod (+ (x st) dt) 0.2))))
(minVY (step 0.2
(* 5.0 (mod (+ (y st) dt2) 0.2))))
(color2 (mix color2 color minVX))
(color3 (mix color3 color2 minVY))
)
;(v2! )
;color3
(v! (z color2) (y color3) (x color2) 1.0)
))
(defpipeline-g draw-verts-pipeline ()
:vertex (draw-verts-vert-stage :vec2)
:fragment (draw-verts-frag-stage :vec2))
(defun draw! ()
(step-host)
(setf (resolution (current-viewport))
(surface-resolution (current-surface *cepl-context*)))
(clear)
(map-g #'draw-verts-pipeline *vert-stream*
:resolution (viewport-resolution (current-viewport))
:time (mynow)
:sam *texture*
:offset *offset*)
(swap))
(defun init ()
(when *gpu-verts-arr*
(free *gpu-verts-arr*))
(when *gpu-index-arr*
(free *gpu-index-arr*))
(when *vert-stream*
(free *vert-stream*))
(setf *gpu-verts-arr*
(make-gpu-array
(list (v! -1.0 1.0)
(v! -1.0 -1.0)
(v! 1.0 -1.0)
(v! 1.0 1.0))
:element-type :vec2))
(setf *texture* (tex "patitos.png"))
(setf *offset*
(v! (/ 1.0 (first (dimensions (sampler-texture *texture*))))
(/ 1.0 (second (dimensions (sampler-texture *texture*))))))
(setf *gpu-index-arr*
(make-gpu-array
(list 0 1 2
0 2 3)))
(setf *vert-stream*
(make-buffer-stream *gpu-verts-arr*
:index-array *gpu-index-arr*)))
(def-simple-main-loop play (:on-start #'init)
(draw!))
| 3,008 | Common Lisp | .lisp | 84 | 26.238095 | 84 | 0.47075 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | e9f8f4811a68d67ec32e21809355083c4b3eabba7d6e5437609c5603e6772b13 | 9,070 | [
-1
] |
9,071 | incudine-env.lisp | azimut_shiny/examples/incudine-env.lisp | ;;;; somecepl.lisp
(in-package #:shiny)
;;; "somecepl" goes here. Hacks and glory await!
(defvar *gpu-verts-arr* nil)
(defvar *gpu-index-arr* nil)
(defvar *vert-stream* nil)
(defvar *env1* nil)
(defun-g draw-verts-vert-stage ((vert :vec2))
(v! (- vert (v2! .4) ) 0 1))
(defun-g draw-verts-frag-stage (&uniform (resolution :vec2))
(v4! 1.0))
(defpipeline-g draw-verts-pipeline (:points)
:vertex (draw-verts-vert-stage :vec2)
:fragment (draw-verts-frag-stage))
(defun draw! ()
(step-host)
(setf (resolution (current-viewport))
(surface-resolution (current-surface *cepl-context*)))
(clear)
(map-g #'draw-verts-pipeline *vert-stream*
:resolution (viewport-resolution (current-viewport)))
(swap))
(defun init ()
(when *gpu-verts-arr*
(free *gpu-verts-arr*))
(when *gpu-index-arr*
(free *gpu-index-arr*))
(when *vert-stream*
(free *vert-stream*))
;; (when *env1*
;; (incudine:free *env1*))
;; (setf *env1*
;; (make-envelope '(0 1 0) '(.2 .8) :curve :exp))
;; (setf *gpu-verts-arr*
;; (make-gpu-array (loop for beats below 0.99 by .001 collect (v! beats (coerce (envelope-at *env1* beats) 'single-float)))
;; :element-type :vec2))
(setf *env1*
(make-perc .001 .4))
(setf *gpu-verts-arr*
(make-gpu-array
(loop for beats below 0.39 by .001
collect
(v! beats (coerce (envelope-at *env1* beats) 'single-float)))
:element-type :vec2))
(setf *vert-stream*
(make-buffer-stream *gpu-verts-arr*
:primitive :points)))
(def-simple-main-loop play (:on-start #'init)
(draw!))
| 1,672 | Common Lisp | .lisp | 49 | 29.204082 | 131 | 0.61236 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 75c3e32a5f3cf45c9b97c0bff9dcbd7ed97c49460ab8ff8787a99f1d028baa2e | 9,071 | [
-1
] |
9,072 | incudine-song.lisp | azimut_shiny/examples/incudine-song.lisp | (in-package :shiny)
; (cl-patterns::scale :MINOR)
(defvar scl-arch_sept '(28/27 16/15 9/8 32/27 4/3 112/81 3/2 14/9 8/5 27/16 16/9 2/1 ))
(defvar env2 (make-perc .001 .4))
(setf (bpm *tempo*) 120)
; ----------------
(dsp! env-test-3 (freq amp pos (env envelope) gate)
(foreach-channel
(cout (pan2 (* (envelope env gate 1 #'stop)
(sine freq amp 0))
pos))))
; ----------------
(defun seq-test (rep freq amp pos scale)
(when (plusp rep)
(dsp-seq (env-test-3 freq amp pos env2 1)
(env-test-3 (* freq (nth 5 scale)) amp pos env2 1)
(env-test-3 (* 2 freq) amp pos env2 1)
(seq-test (1- rep) freq amp pos scale))))
(defun seq-test (rep freq amp pos scale)
(when (plusp rep)
(print "running")
(dsp-seq (env-test-3 freq amp pos env2 1)
(env-test-3 (* freq (scl-nth (random (length scale)) scale)) amp pos env2 1)
(env-test-3 (* freq (scl-nth (random (length scale)) scale)) amp pos env2 1)
(env-test-3 (* freq (scl-nth (random (length scale)) scale)) amp pos env2 1)
(seq-test (1- rep) freq amp pos scale))))
(defun seq-test (rep freq amp pos scale)
(when (plusp rep)
(dsp-seq (env-test-3 freq amp pos env2 1)
(env-test-3 (* freq (nth 1 scale)) amp pos env2 1)
(env-test-3 (* freq (nth 2 scale)) amp pos env2 1)
(env-test-3 (* freq (nth 3 scale)) amp pos env2 1)
(env-test-3 (* freq (nth 4 scale)) amp pos env2 1)
(env-test-3 (* freq (nth 5 scale)) amp pos env2 1)
(env-test-3 (* freq (nth 6 scale)) amp pos env2 1)
(env-test-3 (* freq (nth 6 scale)) amp pos env2 1)
(env-test-3 (* freq (nth 7 scale)) amp pos env2 1)
(env-test-3 (* freq (nth 8 scale)) amp pos env2 1)
(env-test-3 (* freq (nth 9 scale)) amp pos env2 1)
(env-test-3 (* freq (nth 10 scale)) amp pos env2 1)
(seq-test (1- rep) freq amp pos scale))))
(defun seq-test (rep freq amp pos)
(when (plusp rep)
(dsp-seq (env-test-3 freq amp pos env2 1)
(env-test-3 (* freq (nth 5 scl-arch_sept)) amp pos env2 1)
(env-test-3 (* freq (nth 7 scl-arch_sept)) amp pos env2 1)
(seq-test (1- rep) freq amp pos))))
(defun seq-test (rep freq amp pos)
(when (plusp rep)
(dsp-seq (env-test-3 freq amp pos env2 1)
(env-test-3 (* freq 7/4) amp pos env2 1)
(env-test-3 (* freq 2) amp pos env2 1)
(seq-test (1- rep) freq amp pos))))
; ----------------
(defun phr1 (time scale)
(at time #'seq-test 8 200 .4 .5 scale)
(at (+ time #[2 b]) #'seq-test 6 400 .4 .4 scale)
(at (+ time #[4 b]) #'seq-test 4 600 .4 .6 scale))
(defun phr1 (time)
(at time #'seq-test 8 200 .4 .5)
(at (+ time #[2 b]) #'seq-test 6 400 .4 .4)
(at (+ time #[4 b]) #'seq-test 4 600 .4 .6))
| 2,917 | Common Lisp | .lisp | 62 | 39.16129 | 89 | 0.545775 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 314ced5d3cd8562c276217965fe3e906c8ce1b1203099f975fd52a267c075940 | 9,072 | [
-1
] |
9,073 | incudine1sc.lisp | azimut_shiny/examples/incudine1sc.lisp | (in-package :shiny)
(defparameter s1env (make-envelope '(0 1 0) '(.2 1)))
(define-vug s1 (f a e g d q)
(* a
(envgen e g d #'incudine:free)
(bpf (+ (- (phasor f (coerce (random 1.) 'double-float)) .5)
(- (phasor f (coerce (random 1.) 'double-float)) .5))
f
q)))
(dsp! synth1 (f a (e envelope) g d q)
(let ((s (s1 f a e g d q)))
(out s s)))
(defparameter minor #(0 2 3 5 7 8 10 12))
(defun minor (n)
(+ n (aref minor (random (length minor)))))
(defun xx (n b a time)
(let ((b2 (1+ (random b))))
(synth1 (minor n)
(+ .9 (random a))
s1env
.3
b2
7)
(at (+ time #[b2 beat])
#'xx n b a (+ time #[b2 beat]))))
(defun incudine1 ()
(setf (bpm *tempo*) 120)
(xx 200 8 .5 (now))
(at (+ (now) #[4 beat])
#'xx 260 8 .5 (+ (now) #[4 beat])))
(incudine1)
(flush-pending)
(incudine:free 0)
| 923 | Common Lisp | .lisp | 33 | 22.424242 | 66 | 0.500566 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 37fd67b9f3aa979141d7898fcd6c3c259f99a799526d2815eaacf1e88703aaad | 9,073 | [
-1
] |
9,074 | passes.lisp | azimut_shiny/examples/passes.lisp | (in-package :shiny)
#|
float sphereSDF(vec3 p) {
return length(p) - 1.0;
}
|#
#|
/**
* Part 1 Challenges
* - Make the circle yellow
* - Make the circle smaller by decreasing its radius
* - Make the circle smaller by moving the camera back
* - Make the size of the circle oscillate using the sin() function and the iTime
* uniform provided by shadertoy
*/
const int MAX_MARCHING_STEPS = 255;
const float MIN_DIST = 0.0;
const float MAX_DIST = 100.0;
const float EPSILON = 0.0001;
|#
;; /**
;; * Signed distance function for a sphere centered at the origin with radius 1.0;
;; */
;; float sphereSDF(vec3 samplePoint) {
;; return length(samplePoint) - 1.0;
;; }
(defun-g rm-sphere ((p :vec3))
(- (length p) 1.0))
;; /**
;; * Signed distance function describing the scene.
;; *
;; * Absolute value of the return value indicates the distance to the surface.
;; * Sign indicates whether the point is inside or outside the surface,
;; * negative indicating inside.
;; */
;; float sceneSDF(vec3 samplePoint) {
;; return sphereSDF(samplePoint);
;; }
(defun-g rm-scene ((sample-point :vec3))
(rm-sphere sample-point))
;; /**
;; * Return the shortest distance from the eyepoint to the scene surface along
;; * the marching direction. If no part of the surface is found between start and end,
;; * return end.
;; *
;; * eye: the eye point, acting as the origin of the ray
;; * marchingDirection: the normalized direction to march in
;; * start: the starting distance away from the eye
;; * end: the max distance away from the ey to march before giving up
;; */
;; float shortestDistanceToSurface(vec3 eye, vec3 marchingDirection, float start, float end) {
;; float depth = start;
;; for (int i = 0; i < MAX_MARCHING_STEPS; i++) {
;; float dist = sceneSDF(eye + depth * marchingDirection);
;; if (dist < EPSILON) {
;; return depth;
;; }
;; depth += dist;
;; if (depth >= end) {
;; return end;
;; }
;; }
;; return end;
;; }
(defun-g shortest-distance-to-surface ((eye :vec3)
(marching-direction :vec3)
(start :float)
(end :float))
(let* ((depth start))
(for (i 0) (< i 255) (++ i)
(let* ((dist (rm-scene (+ eye (* depth marching-direction)))))
(when (< dist .0001)
depth)))))
#|
/**
* Return the normalized direction to march in from the eye point for a single pixel.
*
* fieldOfView: vertical field of view in degrees
* size: resolution of the output image
* fragCoord: the x,y coordinate of the pixel in the output image
*/
vec3 rayDirection(float fieldOfView, vec2 size, vec2 fragCoord) {
vec2 xy = fragCoord - size / 2.0;
float z = size.y / tan(radians(fieldOfView) / 2.0);
return normalize(vec3(xy, -z));
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec3 dir = rayDirection(45.0, iResolution.xy, fragCoord);
vec3 eye = vec3(0.0, 0.0, 5.0);
float dist = shortestDistanceToSurface(eye, dir, MIN_DIST, MAX_DIST);
if (dist > MAX_DIST - EPSILON) {
// Didn't hit anything
fragColor = vec4(0.0, 0.0, 0.0, 0.0);
return;
}
fragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
|#
(defun-g vert ((vert :vec2))
(v! vert 0 1))
(defun-g frag (&uniform
(resolution :vec2)
(time :float))
(let* ((max-marching-steps 255)
(min-dist 0f0)
(max-dist 100f0)
(epsilon 0.0001))
(v! 1 1 0 0)))
(defun-g frag (&uniform
(resolution :vec2)
(time :float))
(let* ((c (s~ gl-frag-coord :xy))
(cc (/ time 100))
(c (* c (mod cc 10)))
(r (/ c resolution)))
(v3! (* (x r) (y r)))))
(defpipeline-g mario ()
:vertex (vert :vec2)
:fragment (frag))
(defun reset ())
(defun mynow ()
(* .1 (get-internal-real-time)))
(defun game-step ()
(clear)
(map-g #'mario (get-quad-stream-v2)
:time (mynow)
:resolution (viewport-resolution
(current-viewport)))
(swap))
(def-simple-main-loop runplay (:on-start #'reset)
(game-step))
| 4,224 | Common Lisp | .lisp | 132 | 27.636364 | 94 | 0.604972 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 08c3ca6080b88269df072b28d0be2317e5040ce17beef60ce0dd9a5d8334594c | 9,074 | [
-1
] |
9,075 | 20180306.lisp | azimut_shiny/examples/20180306.lisp | (in-package :shiny)
;; https://ansimuz.itch.io/parallax-forest
;; http://terraria.wikia.com/wiki/Bunny
;; https://konbe.deviantart.com/art/GS-Homura-running-sprite-sheet-393600955
;; https://konbe.deviantart.com/art/GS-Kyubey-running-sprite-sheet-395294156
(defclass actor ()
((name :initform (error "set a name") :initarg :name :accessor debug-name)
(pos :initform (v! 0 0 0) :initarg :pos)
(rot :initform 0f0 :initarg :rot)
(scale :initform 1f0 :initarg :scale)
(rows :initform 1f0 :initarg :rows)
(speed :initform 1f0 :initarg :speed)
(direction :initform 0 :initarg :direction)
(width :initform 1f0 :initarg :width)
(columns :initform 1f0 :initarg :columns)
(visual :initarg :visual)))
(defclass walking (actor) ())
(defvar *actors* nil)
(defgeneric update (actor)
(:method ((actor actor)))
(:method ((actor walking))
(with-slots (pos speed) actor
(when (or (< (x pos) -2.1)
(> (x pos) 2.1))
(setf *actors*
(remove-if (lambda (x) (equal x actor)) *actors*)))
(v3:incf pos (v3! (* .0001 speed) 0 0)))))
(defvar *screen-height* 1f0)
(defvar *screen-width* 1f0)
(defun mynow ()
;; Just some number that increases over time that we use
;; in a bunch of places
(/ (get-internal-real-time)
1000f0))
(defvar *gpu-verts-arr* nil)
(defvar *gpu-index-arr* nil)
(defvar *vert-stream* nil)
;; --------------------------------------------------
;;(defvar *cube-stream* nil)
(defvar *cam-pos* (v! 0 0 0))
(defvar *blend* (make-blending-params))
(defvar *triggered* 0)
(defvar *triggered2* 0)
;; --------------------------------------------------
(defvar *samplers* (make-hash-table :test #'equal))
(defun load-tex (rel-path)
(or (gethash rel-path *samplers*)
(let* ((path (asdf:system-relative-pathname :somecepl rel-path))
(tex (load-image-to-texture path)))
(setf (gethash rel-path *samplers*)
(sample tex)))))
;; --------------------------------------------------
(defun-g rain-frag ((vert :vec2)
&uniform
(trigger :bool)
(resolution :vec2)
(time :float))
(let* ((time (* time .05))
(vert (+ vert (v! (- time) 0)))
(vert (* vert 10))
(pe (perlin-noise vert)))
(if trigger
(v! (v3! (+ .9 pe)) 0)
(v! (v3! pe) 0))
;; (v! (v3! (y (/ (s~ gl-frag-coord :xy) resolution))) 0)
))
(defun-g rain-vert ((pos :vec2))
(values (v! pos 0 1)
(* .5 (+ .5 pos))))
;; --------------------------------------------------
(defun-g vert ((vert :vec2) &uniform
(scale :float)
(pos :vec3)
(width :float)
(screen-height :float)
(screen-ratio :float))
(values (v! (/ (+ (s~ pos :xy)
(* scale vert))
(v! (* screen-ratio (/ 1f0 width))
screen-height))
0 1)
(+ (v2! .5) (* vert .5))))
(defun-g frag ((uv :vec2)
&uniform
(direction :bool)
(speed :float)
(rows :float)
(columns :float)
(time :float)
(trigger :bool)
(resolution :vec2)
(sam :sampler-2d)
(cam-pos :vec3))
;; 8 = width size
;; time ...mod does not matter...
;; .125 = 1/8
;; -1 ...flip vertically
;; /2 ... pick one row of the two
(let* (
(time (* speed time))
(mtime (if (= columns 1d0)
(mod time columns)
(floor (mod time columns))))
(vx (+ (* (* (if direction 1 -1) mtime)
(/ 1f0 columns))
(/ (x uv)
columns)))
(vy (/ (* -1 (y uv))
rows))
;;; (vx (* (cos time) vx))
;;; (vy (* (cos time) vy))
;;; wibble
(t-uv (v! vx vy))
(color (texture sam t-uv))
)
(if trigger
(* (+ (v! (v3! (expt (y (/ (s~ gl-frag-coord :xy) resolution)) 3)) 0) color) .8)
(* color .1))
))
;; --------------------------------------------------
(defpipeline-g mario ()
:vertex (vert :vec2)
:fragment (frag :vec2))
(defpipeline-g luigi ()
:vertex (rain-vert :vec2)
:fragment (rain-frag :vec2))
(defun init ()
(setf *screen-width* 1f0)
;; (setf (clear-color) (v! .46 .57 .69 1))
(setf (clear-color) (v! 0 0 0 1))
(setf *actors* nil)
(unless *actors*
(push
(make-instance
'actor
:name "scott"
:visual (load-tex "homura_running_by_konbe-d6ic8fv.png")
:columns 8f0
:scale .3f0
:speed 7f0
:pos (v! 0 -.6 0)
:rows 1f0) *actors*)
(push
(make-instance
'actor
:name "front"
:visual (load-tex "parallax-forest-front-trees.png")
:columns 1f0
:speed .5f0
:width 2f0
:rows 1f0) *actors*)
(push
(make-instance
'actor
:name "front"
:visual (load-tex "parallax-forest-middle-trees.png")
:columns 1f0
:speed .2f0
:width 2f0
:rows 1f0) *actors*))
(when *gpu-verts-arr*
(free *gpu-verts-arr*))
(when *gpu-index-arr*
(free *gpu-index-arr*))
(when *vert-stream*
(free *vert-stream*))
(setf *gpu-verts-arr*
(make-gpu-array
(list (v! -1.0 1.0)
(v! -1.0 -1.0)
(v! 1.0 -1.0)
(v! 1.0 1.0))
:element-type :vec2))
(setf *gpu-index-arr*
(make-gpu-array
(list 0 1 2
0 2 3)))
(setf *vert-stream*
(make-buffer-stream *gpu-verts-arr*
:index-array *gpu-index-arr*)))
(defun draw! ()
(step-host)
(clear)
(let ((res (surface-resolution (current-surface)))
(trigger (funcall *triggered* 'shoot)))
(setf (resolution (current-viewport))
res)
(when (= 1 (funcall *triggered2* 'shoot))
(push
(make-instance
'walking
:name "walkingthing"
:visual (load-tex "homy_by_konbe-d6jcix8.png")
:columns 6f0
:direction 1
:scale (ran :from .1 :below .4)
:speed (ran :from 6f0 :below 15f0)
:pos (v! (ran :from .2 :below 1) (ran :below -.1 :from -.6) 0)
:rows 1f0)
*actors*))
(map-g #'luigi *vert-stream*
:resolution res
:trigger trigger
:time (mynow))
(with-setf* ((depth-test-function) nil)
(with-blending *blend*
(loop :for x :in *actors* :do
(update x)
(with-slots (rows speed width columns pos scale visual direction) x
(map-g #'mario *vert-stream*
:time (mynow)
:rows rows
:direction direction
:speed speed
:columns columns
:scale scale
:screen-height *screen-height*
:width width
:screen-ratio (/ (x res) (y res))
:pos pos
:trigger trigger
:resolution res
:sam visual
;;:cam-pos *cam-pos*
))))
)
(swap)))
(def-simple-main-loop runplay (:on-start #'init)
(draw!))
| 7,368 | Common Lisp | .lisp | 229 | 23.637555 | 88 | 0.490702 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 1d342f3936d9600207c16579dc1d9915a8f37a1f9084009b34aaac5ebf7b7adb | 9,075 | [
-1
] |
9,076 | notalent.lisp | azimut_shiny/examples/notalent.lisp | (in-package :shiny)
(defvar *notes* nil)
(defclass circle-note ()
((pitch :initarg :pitch :initform nil)
(die-at :initarg :die-at :initform -1)
(life :initarg :life :initform 0f0)
(growth :initarg :growth :initform nil)
(pencil :initarg :pencil :initform 1)
(pos :initarg :pos :initform (v! 0 0))
(color :initarg :color :initform (v! 0 0 0))
(selfcolor :initarg :selfcolor :initform (v! 1 1 1))
(shape :initarg :shape :initform 0)
(fade :initarg :fade :initform 0f0)
(rotation :initarg :rotation :initform 0f0)))
(defun mynow ()
;; Just some number that increases over time that we use
;; in a bunch of places
(/ (get-internal-real-time)
1000f0))
;; --------------------------------------------------
(defun-g vert ((vert :vec2))
(values (v! vert 0 1)
(* (+ vert .5) .5)))
(defun-g frag ((uv :vec2) &uniform
(resolution :vec2) (time :float) (instance :float))
(v! .3 .3 .3 1))
(defpipeline-g pipe ()
:vertex (vert :vec2)
:fragment (frag :vec2))
(defmacro defcard (() &body body)
`(defun-g frag ((uv :vec2) &uniform
(resolution :vec2) (time :float)
(life :float)
(shape :int)
(pencil :int)
(mycolor :vec3)
(rotation :float)
(selfcolor :vec3)
(fade :float)
(pos :vec2) (pitch :int))
(let* ((st (/ (s~ gl-frag-coord :xy)
resolution))
(color (v! 0 0 0))
;; this helps keeping things inside
(st (+ .5 (* 1.1912 (- st .5)))))
;; this removes some artifacts on bridges AND
;; keeps the aspect ratio
(if (> (y resolution) (x resolution))
(progn
(multf (y st) (/ (y resolution) (x resolution)))
(decf (y st) (/ (- (* .5 (y resolution))
(* .5 (x resolution)))
(x resolution))))
(progn
(multf (x st) (/ (x resolution) (y resolution)))
(decf (x st) (/ (- (* .5 (x resolution))
(* .5 (y resolution)))
(y resolution)))))
,@body)))
;;--------------------------------------------------
(defparameter *blend*
(make-blending-params
;; :mode-rgb :func-add
;; :mode-alpha :func-add
:source-rgb :one
:destination-rgb :one
;; :source-alpha :one
;; :destination-alpha :one
))
(defun draw! ()
(let ((res (surface-resolution (current-surface)))
)
(setf (viewport-resolution (current-viewport))
res)
(as-frame
(loop :for x :in *notes* :do
;; reduce or increase life if growth is defined
(case (slot-value x 'growth)
(+ (incf (slot-value x 'life) .05))
(- (decf (slot-value x 'life) .05)))
;; ...
(when (> (slot-value x 'fade) 0)
(decf (slot-value x 'fade) .02))
;; kill when life implodes or explodes
(when (or (< (slot-value x 'life) 0)
(> (slot-value x 'life) 9))
(setf *notes* (remove x *notes*)))
;; kill when time expires
(when (> (get-universal-time) (slot-value x 'die-at))
(setf *notes* (remove x *notes*)))
(with-setf (depth-test-function) nil
(with-blending *blend*
(with-slots (color rotation fade pos
pencil pitch
life shape selfcolor)
x
(map-g #'pipe (get-quad-stream-v2)
:resolution res
:time (mynow)
:rotation rotation
:mycolor color
:pos pos
:fade fade
:pencil pencil
:selfcolor selfcolor
:pitch pitch
:shape shape
:life (float life)))))))))
(defun init ()
(setf *notes* nil)
(push (make-instance 'circle-note
:life 1f0
:pitch 60
:die-at (+ (get-universal-time) 2))
*notes*))
(def-simple-main-loop runplay (:on-start #'init)
(draw!))
;;--------------------------------------------------
(defcard ()
(let* (;;(color (v! .3 .1 .2))
(color (+ color (stroke (circle-sdf st)
(* .015 pitch)
.01)))
(color (+ color (* (v! .9 .2 .3) (g-fill (circle-sdf
st
)
.5)))))
(v! color)))
(defcard ()
(let* ((ost st)
(st (pixel-spirit-deck:rotate st (radians rotation)))
(ship (cond
((= shape 0) (circle-sdf (+ pos st)))
((= shape 3) (* 1.2 life (tri-sdf (+ (v! 0 -.1) st))))
((= shape 4) (rays-sdf (pixel-spirit-deck:rotate
st
(radians (* pitch (sin time))))
10))
(t (rect-sdf st (v2! (* pitch .01))))))
(vshape (if (= pencil 0)
(g-fill ship (* pitch life .002))
(stroke ship
(* pitch life .01)
.01)))
(newcolor (v3! vshape))
(newcolor (if (<= fade -1) newcolor (* newcolor fade)))
(newcolor (+ newcolor mycolor))
(newcolor (* newcolor selfcolor))
(newcolor (if (not (= rotation 0))
(if (= shape 1)
(+ newcolor (* .2 (y ost)))
newcolor)
(+ newcolor
(step (v3! (the-book-of-shaders:snoise
(* (* .09 pitch) (+ time st))))
(+ -.9 newcolor)))))
;; (newcolor (+ newcolor (v! (exp (* 100 (tan time) (y st) (x st)))
;; 0
;; 0)))
)
(v! newcolor 0)))
| 6,332 | Common Lisp | .lisp | 161 | 25.596273 | 76 | 0.421173 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | bdec563d316613a6b2616a0d6f01b58fa5137a83b513847cdf9109a1395bbabe | 9,076 | [
-1
] |
9,077 | somecepl.lisp | azimut_shiny/examples/somecepl.lisp | ;;;; somecepl.lisp
(in-package #:shiny)
;;; "somecepl" goes here. Hacks and glory await!
(defvar *gpu-verts-arr* nil)
(defvar *gpu-index-arr* nil)
(defvar *vert-stream* nil)
;(defvar *viewport* nil)
;vec2 random(vec2 st){
; st = vec2( dot(st, vec2(127.1,311.7)),
; dot(st, vec2(269.5,183.3)) );
; return -1.0 + 2.0 * fract(sin(st)*43758.5453123);
;}
(defun-g grandom ((st :vec2))
(let* ((s (v! (dot st (v! 127.1 311.7))
(dot st (v! 269.5 183.3)) )))
(- (* 2.0 (fract (* (sin s) 43758.5453123))) (v! 1.0 1.0) )))
;// Value Noise by Inigo Quilez - iq/2013
;// https://www.shadertoy.com/view/lsf3WH
;float noise(vec2 st) {
; vec2 i = floor(st);
; vec2 f = fract(st);
; vec2 u = f*f*(3.0-2.0*f);
; return mix( mix( dot( random(i + vec2(0.0,0.0) ), f - vec2(0.0,0.0) ),
; dot( random(i + vec2(1.0,0.0) ), f - vec2(1.0,0.0) ), u.x),
; mix( dot( random(i + vec2(0.0,1.0) ), f - vec2(0.0,1.0) ),
; dot( random(i + vec2(1.0,1.0) ), f - vec2(1.0,1.0) ), u.x), u.y);
;}
(defun-g gnoise ((st :vec2))
(let* ((i (floor st))
(f (fract st))
(u (* f (* f (- (v! 3.0 3.0) (* 2.0 f) )))))
(mix (mix (dot (grandom (+ i (v! 0.0 0.0)))
(- f (v! 0.0 0.0)))
(dot (grandom (+ i (v! 1.0 0.0)))
(- f (v! 1.0 0.0)))
(x u))
(mix (dot (grandom (+ i (v! 0.0 1.0)))
(- f (v! 0.0 1.0)))
(dot (grandom (+ i (v! 1.0 1.0)))
(- f (v! 1.0 1.0)))
(x u))
(y u))
))
(defun-g draw-verts-vert-stage ((vert :vec2))
(v! vert 0 1))
;; uniform vec2 resolution;
;; uniform float time;
;; uniform float val1;
;; uniform float val2;
;; uniform float val3;
;; uniform float subD;
;; uniform float mouseX;
;; uniform float mode;
;; vec2 st = gl_FragCoord.xy/resolution.xy;
;; float tt = -time*0.0005;
;; float val1s = val1*.5; //frequencie. 0.2
;; float val2s = val2*10.;//amplitude 5.0
;; float val3s = val3*5.;//contrast 2.5
;; float subDs = subD*10.; 100.0
;; st*=subDs;
;; float nV = (noise(vec2( st.s + sin(st.s*val1s*5.)*(val2s) , st.t + sin(st.t*val1s*5.)*(val2s) +tt)));
;; nV += .5;
;; nV = ((nV-.5)*val3s )+.5;
;; vec4 col = vec4(vec3(nV),1. );
;; gl_FragColor = col;
(defun-g draw-verts-frag-stage (&uniform (time :float)
(mouse :vec2)
(screen-res :vec2)
(mouse-buttons :vec2))
(let* ((u1 (* .4 0.5))
(u2 (* .2 10.0))
(u3 (* .6 5.0))
(u4 10.0)
(tt (* 1.0 time))
(st (* u4 (v! (/ (x gl-frag-coord) (x screen-res))
(/ (y gl-frag-coord) (y screen-res)) )))
(nv (+ .5 (gnoise (v! (+ (x st) (* u2 (sin (* 5.0 u1 (x st)))))
(+ (y st) (* u2 (sin (* 5.0 u1 (y st)))) tt)))))
(nvv (+ .5 (* u3 (- nv .5)))))
(v! nvv nvv nvv 1.0)
))
;; (defun-g draw-verts-frag-stage (&uniform (time :float)
;; (mouse :vec2)
;; (screen-res :vec2)
;; (mouse-buttons :vec2))
;; (v! (abs (sin time))
;; (/ (x mouse) (x screen-res))
;; (/ (x gl-frag-coord) (x screen-res) )
;; 0))
(defpipeline-g draw-verts-pipeline ()
:vertex (draw-verts-vert-stage :vec2)
:fragment (draw-verts-frag-stage))
(defun get-mouse-buttons ()
(v! (if (mouse-down-p mouse.left) 1f0 0f0)
(if (mouse-down-p mouse.right) 1f0 0f0)))
(defun get-mouse ()
(let ((pos (mouse-pos (mouse 0)))
(h (y (viewport-resolution (current-viewport)))))
(v! (x pos) (- h (y pos)))))
(defun now ()
(get-internal-real-time))
(defun draw! ()
;; (with-viewport *viewport*
(step-host)
(setf (resolution (current-viewport))
(surface-resolution (current-surface *cepl-context*)))
(clear)
(map-g #'draw-verts-pipeline *vert-stream*
:time (* (now) .0001 )
:mouse (get-mouse)
:screen-res (viewport-resolution (current-viewport))
:mouse-buttons (get-mouse-buttons))
(swap))
(defun init ()
; (when *viewport*
; (free *viewport*))
(when *gpu-verts-arr*
(free *gpu-verts-arr*))
(when *gpu-index-arr*
(free *gpu-index-arr*))
(when *vert-stream*
(free *vert-stream*))
; (setf *viewport*
; (make-viewport '(400 400)))
(setf *gpu-verts-arr*
(make-gpu-array
(list (v! -1.0 1.0)
(v! -1.0 -1.0)
(v! 1.0 -1.0)
(v! 1.0 1.0))
:element-type :vec2))
(setf *gpu-index-arr*
(make-gpu-array
(list 0 1 2
0 2 3)))
(setf *vert-stream*
(make-buffer-stream *gpu-verts-arr*
:index-array *gpu-index-arr*)))
(def-simple-main-loop play (:on-start #'init)
(draw!))
| 5,027 | Common Lisp | .lisp | 140 | 29.664286 | 104 | 0.480041 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | e3ab213affe98b6bbbf7308acc6c6a58ae5bb107ec3930aabb850910cd1955b3 | 9,077 | [
-1
] |
9,078 | sam-simple.lisp | azimut_shiny/examples/sam-simple.lisp | ;;;; somecepl.lisp
(in-package #:shiny)
;;; "somecepl" goes here. Hacks and glory await!
(defvar *ctex* nil)
(defvar *tex* nil)
(defvar *sam* nil)
(defvar *gpu-verts-arr* nil)
(defvar *gpu-index-arr* nil)
(defvar *vert-stream* nil)
(defvar *viewport* nil)
(setf *viewport* (make-viewport '(400 400)))
;; ------------------------------------------
(defun-g vert ((vert :vec2))
(v! vert 0 1))
;; ------------------------------------------
#|
void main() {
vec2 st = gl_FragCoord.xy/u_resolution.xy;
vec3 color = vec3(0.);
float total = 4.;
float col = floor(st.x*total);
color += float(floor(mod(u_time,total)) == col);
gl_FragColor = vec4(color,1.);
}
|#
;; http://thebookofshaders.com/edit.php?log=180220141500
(defun-g frag (&uniform
(resolution :vec2)
(time :float))
(let* ((st (/ (s~ gl-frag-coord :xy)
resolution))
(color (v3! 0))
(total 4.0)
(col (floor (* total (x st))))
(color (+ color
(v3!
(float
(eql
(floor (mod time total))
col))))))
(v! color 0)))
#|
http://thebookofshaders.com/edit.php?log=180220141210
void main() {
vec2 st = gl_FragCoord.xy/u_resolution.xy;
float dt = 2.;
float t = step(mod(u_time, dt),.2);
float t2 = step(mod(u_time-(1.*dt*.1), dt),.2);
float t3 = step(mod(u_time-(2.*dt*.1), dt),.2);
float t4 = step(mod(u_time-(3.*dt*.1), dt),.2);
float c =step(st.x,.25)*t;
c+= (step(st.x,.5)-step(st.x,.25))*t2;
c+= (step(st.x,.75)-step(st.x,.5))*t3;
c+= (step(st.x,1.)-step(st.x,.75))*t4;
gl_FragColor = vec4(vec3(c),1.);
}
|#
(defun-g frag (&uniform
(resolution :vec2)
(time :float))
(let* ((st (/ (s~ gl-frag-coord :xy)
resolution))
(dt 2.0)
(t1 (step (mod time dt) .2))
(t2 (step (mod (- time (* 1. dt .1)) dt) .2))
(t3 (step (mod (- time (* 2. dt .1)) dt) .2))
(t4 (step (mod (- time (* 3. dt .1)) dt) .2))
(c (* t1 (step (x st) .25)))
(c (+ c (* t2 (- (step (x st) .5) (step (x st) .25)))))
(c (+ c (* t3 (- (step (x st) .75) (step (x st) .5)))))
(c (+ c (* t4 (- (step (x st) 1.) (step (x st) .75))))))
(v! c c c 0)))
#|
void main() {
vec2 st = gl_FragCoord.xy/u_resolution.xy;
float dt = 2.;
float t = step(mod(u_time, dt),.2);
float t2 = step(mod(u_time-(1.*dt*.1), dt),.2);
float t3 = step(mod(u_time-(2.*dt*.1), dt),.2);
float t4 = step(mod(u_time-(3.*dt*.1), dt),.2);
float c1 =step(st.x,.25)*t;
float c2 = (step(st.x,.5)-step(st.x,.25))*t2;
float c3= (step(st.x,.75)-step(st.x,.5))*t3;
float c4= (step(st.x,1.)-step(st.x,.75))*t4;
float c = c1*sin(st.x*200.)
+ c2*sin(st.y*300.)
+ c3*sin((st.x+st.y)*200.)
+ c4*sin((st.x-st.y)*200.);
gl_FragColor = vec4(vec3(c),1.);
}
|#
(defun-g frag (&uniform
(resolution :vec2)
(time :float))
(let* ((st (/ (s~ gl-frag-coord :xy)
resolution))
(dt 3.)
(t1 (step (mod time dt) .2))
(t2 (step (mod (- time (* 1. dt .1)) dt) .2))
(t3 (step (mod (- time (* 2. dt .1)) dt) .2))
(t4 (step (mod (- time (* 3. dt .1)) dt) .2))
(c1 (* t1 (step (x st) .25)))
(c2 (* t2 (- (step (x st) .5) (step (x st) .25))))
(c3 (* t3 (- (step (x st) .75) (step (x st) .5))))
(c4 (* t4 (- (step (x st) 1.) (step (x st) .75))))
(c (+ (* c4 (sin (* 200. (x st))))
(* c3 (sin (* 300. (y st))))
(* c2 (sin (* 200. (+ (x st) (y st)))))
(* c1 (sin (* 200. (- (x st) (y st))))))))
(v! c c c 1)))
#|
void main() {
vec2 st = gl_FragCoord.xy/u_resolution.xy;
float dt = 1.;
float t = step(mod(u_time, dt),.25);
float t2 = step(mod(u_time-(1.*dt*.25), dt),.25);
float t3 = step(mod(u_time-(2.*dt*.25), dt),.25);
float t4 = step(mod(u_time-(3.*dt*.25), dt),.25);
vec2 cent = st*.5+.25;
float d = distance(st, cent);
float c1 = sin(d*100.)*t;
float c2 = sin(st.x*200.)*t2;
float c3 = sin(st.y*100.)*t3;
float c4= sin((st.x+st.y)*50.)*t4;
float c = c1
+ c2+c3+c4;
gl_FragColor = vec4(vec3(c),1.);
}
|#
(defun-g frag (&uniform
(time :float)
(resolution :vec2))
(let* ((st (/ (s~ gl-frag-coord :xy)
resolution))
(dt 1.)
(t1 (step (mod time dt) .25))
(t2 (step (mod (- time (* 1. dt .25)) dt) .25))
(t3 (step (mod (- time (* 2. dt .25)) dt) .25))
(t4 (step (mod (- time (* 3. dt .25)) dt) .25))
(cent (+ (v2! .25)
(* (v2! .5)
st)))
(d (distance st cent))
(c1 (* t1 (sin (* 100. d))))
(c2 (* t2 (sin (* 200. (x st)))))
(c3 (* t3 (sin (* 100. (y st)))))
(c4 (* t4 (sin (* 50. (+ (x st) (y st))))))
(c (+ c1 c2 c3 c4)))
(v! c c c 0)))
;; ------------------------------------------
;; formulanimations tutorial ::
;; the principles of painting with maths
;; https://www.youtube.com/watch?v=0ifChJ0nJfM
;; gradiant 1
(defun-g frag (&uniform (time :float) (resolution :vec2))
(let* ((st (/ (s~ gl-frag-coord :xy)
resolution))
(col (v! 1. .4 .1))
(col (* col (x st))))
(v! col 0)))
;; gradiant 2
(defun-g frag (&uniform (time :float) (resolution :vec2))
(let* ((st (/ (s~ gl-frag-coord :xy)
resolution))
(col (v! 1. .4 .1))
(col (* col (/ (x st)
(y st)))))
(v! col 0)))
;; gradiant 3
(defun-g frag (&uniform (time :float) (resolution :vec2))
(let* ((st (/ (s~ gl-frag-coord :xy)
resolution))
(col (v! 1. .4 .1))
(q (- st (v! .5 .5)))
(col (* col (length q))))
(v! col 0)))
;; shadertone vvv.glsl
(defun-g frag (&uniform (time :float) (resolution :vec2))
(let* ((uv (/ (s~ gl-frag-coord :xy)
resolution))
(A 300)
(B 300)
;; put A, B into 0,1 range
(a (+ .5 (/ (- A 300.) 50. 2.)))
(b (+ .5 (/ (- B 300.) 100. 2.)))
;; make a vertical step for A
(ac (smoothstep 0. 0.05 (- (x uv) a)))
;; make a horizontal step for B
(bc (smoothstep 0. 0.05 (- (y uv) b)))
(c (* (v3! ac) (v! 0. .5 1.)))
(c (+ c (* (v3! bc) (v! 1. .5 0)))))
(v! c 0)))
;; ------------------------------------------
(defun-g frag (&uniform (time :float)
(tt :sampler-2d)
(resolution :vec2))
(let* ((st (/ (s~ gl-frag-coord :xy)
(/ resolution .02)))
(ttt (texture tt st))
(col (v! 1. .4 .1))
(col (* col (x st))))
(v! (s~ ttt :xxx) 0)))
(defpipeline-g draw-verts-pipeline ()
:vertex (vert :vec2)
:fragment (frag))
;; ------------------------------------------
(defun draw! ()
(step-host)
(clear)
(with-viewport *viewport*
(map-g #'draw-verts-pipeline *vert-stream*
:resolution (viewport-resolution
(current-viewport))
:tt *sam*
:time (mynow)))
(swap))
(defun runinit ()
(when *gpu-verts-arr*
(free *gpu-verts-arr*))
(when *gpu-index-arr*
(free *gpu-index-arr*))
(when *vert-stream*
(free *vert-stream*))
(when *tex*
(free *tex*))
;; (setf *tex* (make-texture
;; (loop :for j :below 2 :collect
;; (loop :for i :below 512 :collect
;; (random 1.0)))
;; :element-type :float
;; :dimensions '(2 512)))
(setf *tex* (make-texture
(loop :for j :below 512 :collect
(loop :for i :below 512 :collect
(random 254)))
:element-type :uint8
:dimensions '(512 512)))
;; (setf *tex* (make-texture
;; (loop :for j :below 512 :collect
;; (loop :for i :below 2 :collect
;; (random 254)))
;; :element-type :uint8
;; :dimensions '(512 2)))
;; (setf *tex* (make-texture
;; (loop :for j :below 2 :collect
;; (loop :for i :below 512 :collect
;; (random 1.0)))
;; :element-type :r8
;; :dimensions '(2 512)))
(setf *sam* (cepl:sample *tex*))
(setf *gpu-verts-arr*
(make-gpu-array
(list (v! -1 1)
(v! -1 -1)
(v! 1 -1)
(v! 1 1))
:element-type :vec2))
(setf *gpu-index-arr*
(make-gpu-array
(list 0 1 2
0 2 3)))
(setf *vert-stream*
(make-buffer-stream *gpu-verts-arr*
:index-array *gpu-index-arr*)))
(def-simple-main-loop runplay (:on-start #'runinit)
(draw!))
| 9,075 | Common Lisp | .lisp | 266 | 26.669173 | 66 | 0.445193 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 8c499eb852c8c0311c5e44059d52d06f93b9437352bd82bffc12bfe410d494a6 | 9,078 | [
-1
] |
9,079 | incudine-guitar.lisp | azimut_shiny/examples/incudine-guitar.lisp | (in-package :shiny)
;; https://sourceforge.net/p/incudine/mailman/message/34320609/
;; https://ccrma.stanford.edu/realsimple/faust_strings/faust_strings.pdf
(define-vug diffgtz (x)
(if (plusp (- x (delay1 x))) 1.0d0 0.0d0))
(define-vug decay (n x)
(- x (if (plusp x) (/ n) 0.0d0)))
(define-vug release (n x)
(~ (+ x (decay n it))))
(define-vug trigger (n x)
(if (plusp (release n (diffgtz x))) 1.0d0 0.0d0))
(define-vug pickdir (in coef)
(with-samples ((g (- 1 coef)))
(pole (* g in) coef)))
(define-vug pickpos (in beta p)
(with ((ppdel (sample->fixnum (* beta p))))
(- (delay-s in 2048 ppdel) in)))
(define-vug symmetric-twozero (in h0 h1)
(with-samples ((del1 (delay1 in)))
(+ (* h0 del1) (* h1 (+ in (delay1 del1))))))
(define-vug damping-filter2 (in freq t60 b)
(with-samples ((k (/ (* freq t60)))
(rho (expt .001d0 k))
(h0 (* (+ 1 b) 0.5))
(h1 (* (- 1 b) 0.25)))
(* rho (symmetric-twozero in h0 h1))))
(define-vug level-filter (x l freq)
(with-samples ((l0 (expt (the non-negative-sample l) (incudine.util:sample 1/3)))
(lw (* pi freq *sample-duration*))
(lgain (/ lw (+ 1 lw)))
(lpole2 (/ (- 1 lw) (+ 1 lw)))
(s0 (* l l0 x))
(s1 (- 1 l)))
(+ s0 (* s1 (~ (+ (* x lgain) (* lpole2 it)))))))
(define-vug excitation (gain p)
(* (white-noise gain) (trigger p (incudine.util:sample (incudine.vug:mouse-button)))))
(define-vug filtered-excitation (gain freq pickangle beta l)
(with-samples ((p (/ *sample-rate* freq)))
(level-filter (pickpos (pickdir (excitation gain p) pickangle) beta p)
l freq)))
(define-vug stringloop (in freq t60 b)
(with-samples ((dt (/ freq)))
(~ (damping-filter2 (vdelay (+ in it) 0.05 dt :cubic) freq t60 b))))
(dsp! pluck-test (gain freq pickangle beta l t60 b)
(foreach-frame
(stereo (stringloop (filtered-excitation gain freq pickangle beta l)
freq t60 b))))
(set-rt-block-size 64)
(rt-start)
(pluck-test .7 440 .9 .13 .3 4 .5)
;; ***** Press the left button of the mouse to trigger a note *****
(free 0)
(rt-stop)
| 2,201 | Common Lisp | .lisp | 53 | 35.698113 | 88 | 0.580827 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 84cd97ec09ef1c080565bffd62226abf35193c3ab18be8dfa6de3cdf368d4595 | 9,079 | [
-1
] |
9,080 | 20180810.lisp | azimut_shiny/examples/20180810.lisp | (in-package :shiny)
;;; Code from "undo" video, along with compositions/ray.lisp
(defvar *growth* 0f0)
(defun-g circle-sdf ((st :vec2))
(* 4.0 (length (- st .5))))
(pixel-spirit-deck:poly-sdf)
(defun-g poly-sdf ((st :vec2) (V :float))
(let* ((st (- (* 2.0 st) 1.0))
(a (+ 3.1415 (atan (x st) (y st))))
(r (length st))
(v (/ 6.283185 (float V))))
(* r (cos (- (* v (floor (+ .5 (/ a v)))) a)))))
(defun-g frag ((uv :vec2)
&uniform
(trigger :int)
(vtrigger :int)
(growth :float)
(resolution :vec2)
(time :float))
(let* ((gate1 (= vtrigger 0))
(st uv)
(color (v3! 0 0 0))
(color (v3! 1 1 1))
(color (v3! (smoothstep (tan time) (cos time)
(poly-sdf st (ceil (* 4 (+ .5 (* .5 (sin time)))))))))
(time (* time (if (= trigger 0) .5 1f0)))
(st (if gate1
(+ (v! (* .5 (sin time))
(* .5 (cos time)))
st)
(+ (v! (* .5 (cos time))
(* .5 (sin time)))
st)))
(color (* color (v3! (circle-sdf st))))
(color (if gate1 (- color) (- color (v! .2 .7 1))))
(color (+ (* 1 growth) color))
)
(v! color 1)))
(defvar *trigger* (make-trigger))
(defvar *vtrigger* (make-trigger))
;;--------------------------------------------------
(defpipeline-g pipe (:points)
:fragment (frag :vec2))
(define-vug rms (in hp)
(:defaults 0 60)
(with-samples ((b (- 2 (cos (* hp *twopi-div-sr*))))
(c2 (- b (sqrt (the non-negative-sample (1- (* b b))))))
(c1 (- 1 c2))
(in2 (* in in))
(q +sample-zero+))
(lin->db (sqrt (the non-negative-sample (~ (+ (* c1 in2) (* c2 it))))))))
(dsp! rms-monitor (rms)
(:defaults 0)
(setf rms (rms (audio-out 0))))
(rms-monitor :id 99)
(defun get-db (&optional (id 99))
(let ((rms (control-value id 'rms)))
(when rms
(let ((output (lin->db rms)))
(cm:interp (- (realpart output))
-50 0f0 -10 1f0)))))
;;--------------------------------------------------
(defvar *bs*
(make-buffer-stream nil :primitive :points))
(defun draw! ()
(let ((res (surface-resolution (current-surface))))
(setf (viewport-resolution (current-viewport))
res)
(as-frame
(map-g #'pipe *bs*
:trigger (funcall *trigger* 'shoot)
:vtrigger (funcall *vtrigger* 'shoot)
:growth (coerce (get-db) 'single-float)
:resolution res
:time (/ (get-internal-real-time)
1000f0)))))
(def-simple-main-loop runplay ()
(draw!))
| 2,834 | Common Lisp | .lisp | 78 | 27.012821 | 87 | 0.445783 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | b3bc195e9216c779fe1b9b58690724bae7e2bbc02d45eba9a2d2447b9053dd25 | 9,080 | [
-1
] |
9,081 | clpatterns.lisp | azimut_shiny/examples/clpatterns.lisp | (in-package :cl-patterns)
(defparameter *clock* (make-clock (/ 110 60)))
(pdef :foo
(pbind :instrument 1
:channel (pseq '(0 1))
:midinote 90
:quant 4
:dur 1
:pfin 4
:pan (pseq '(0 1))
:amp .9))
(play :foo)
(stop :foo)
| 318 | Common Lisp | .lisp | 13 | 15.769231 | 46 | 0.456954 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 32e07e5920d5305031a08457036a240781c6e74a1bd29ddcd93d71b1d6f9107c | 9,081 | [
-1
] |
9,082 | 20180717.lisp | azimut_shiny/examples/20180717.lisp | (in-package :shiny)
(defparameter *step* (make-stepper (seconds .05) (seconds 1)))
(defparameter *trigger* (make-trigger))
(defvar *buf* (make-buffer 512))
(defvar *bs* nil)
(defvar *mar* nil)
(defvar *ubo* nil)
(defvar *scene-fbo* nil)
(defvar *scene-sample* nil)
(dsp! monitor-master ((buf buffer))
(buffer-write
buf
(counter 0 511 :loop-p t)
(audio-out 0)))
;; (monitor-master *buf* :id 100)
;;--------------------------------------------------
(defstruct-g (music :layout :std-140)
(samples (:double 512)))
(defun-g g-rand ((x :float))
(fract (* (sin x)
10000f0)))
(defun-g cyn ((x :float))
(+ .5 (* .5 (cos x))))
(defun-g syn ((x :float))
(+ .5 (* .5 (sin x))))
(defun-g g-random ((st :vec2))
(fract (* (sin (dot st
(v! 12.9898 ;; moves noise
78.233
)))
43758.543123
)))
(defun-g frag
((uv :vec2) &uniform (sound music :ubo) (time :float)
(rms :float))
(with-slots (samples) sound
(let* (;;(wide (+ 100 (* 100 (+ .5 (* .5 (sin time))))))
(wide 250)
(wave (float (aref samples (int (ceil (* wide (x uv)))))))
(wave (- 1 (smoothstep 0f0 .01 (abs (- wave (- (y uv) .5))))))
(wave (v3! wave))
;; (uv (v! (length (- (x uv) .5))
;; (y uv)))
;; !
;; (color (mix c1 c2 (+ (- rms) 1 (y uv))))
;; (color (+ color wave))
)
wave)))
(defpipeline-g pipe (:points)
:fragment (frag :vec2))
;;--------------------------------------------------
(defun-g frag-last ((uv :vec2) &uniform (waves :sampler-2d) (time :float))
(let ((color (texture waves (* (+ 2 (* 12 (cyn time))) uv))))
color))
(defun-g vert-last ((vert :vec2))
(values (v! vert 0 1)
(+ .5 (* .5 vert))))
(defpipeline-g lastpipe ()
(vert-last :vec2)
(frag-last :vec2))
;;--------------------------------------------------
(defun initialize ()
(when *scene-fbo*
(cepl:free *scene-fbo*))
(setf *scene-fbo* (make-fbo 0))
(setf *scene-sample* (cepl:sample (attachment-tex *scene-fbo* 0)))
(unless *bs*
(setf *bs* (make-buffer-stream nil :primitive :points))
(setf *mar* (make-c-array nil :dimensions 1 :element-type 'music))
(setf *ubo* (make-ubo *mar*))))
(defun draw! ()
(when (funcall *step*)
;; NOTE: ?
(with-gpu-array-as-c-array (m (ubo-data *ubo*) :access-type :write-only)
(incudine.external:foreign-copy-samples
(c-array-pointer m)
(buffer-data *buf*)
512)))
(let ((res (surface-resolution (current-surface))))
(setf (viewport-resolution (current-viewport))
res)
(with-fbo-bound (*scene-fbo*)
(clear-fbo *scene-fbo*)
(map-g #'pipe *bs*
:rms (float (funcall *trigger* 'bleed))
:time (* .001 (get-internal-real-time))
:sound *ubo*))
(as-frame
(clear)
(map-g #'lastpipe (get-quad-stream-v2)
:waves *scene-sample*
:time (* .001 (get-internal-real-time))))))
(def-simple-main-loop runplay (:on-start #'initialize)
(draw!))
| 3,187 | Common Lisp | .lisp | 94 | 27.808511 | 76 | 0.51043 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | a2013f12de777a211a9dc3ce9d4a2e76c182e897e325a8d90ac5bc2900650003 | 9,082 | [
-1
] |
9,083 | st1.lisp | azimut_shiny/examples/st1.lisp | ;;;; somecepl.lisp
(in-package #:shiny)
;;; "somecepl" goes here. Hacks and glory await!
(defvar *gpu-verts-arr* nil)
(defvar *gpu-index-arr* nil)
(defvar *vert-stream* nil)
(defun-g draw-verts-vert-stage ((vert :vec2))
(v! vert 0 1))
; https://www.shadertoy.com/view/XtGGRt
;; vec3 hash33(vec3 p)
;; {
;; p = fract(p * vec3(443.8975,397.2973, 491.1871));
;; p += dot(p.zxy, p.yxz+19.27);
;; return fract(vec3(p.x * p.y, p.z*p.x, p.y*p.z));
;; }
(defun-g hash33 ((p :vec3) (time :int))
(let* ((p (fract (* p (v! (* 0.00000000001 time)
"497.2973"
"491.1871"))))
(p (+ p (v3! (dot (s~ p :zxy)
(+ (v3! 19.27)
(s~ p :yxz) ))))))
(fract (v! (* (x p) (y p))
(* (z p) (x p))
(* (y p) (z p))))))
;; vec3 bg(in vec3 rd)
;; {
;; float sd = dot(normalize(vec3(-0.5, -0.6, 0.9)), rd)*0.5+0.5;
;; sd = pow(sd, 5.);
;; vec3 col = mix(vec3(0.05,0.1,0.2), vec3(0.1,0.05,0.2), sd);
;; return col*.63;
;; }
(defun-g bg ((rd :vec3))
(let* ((sd (+ .05
(* .05
(dot (normalize (v! -.5 -.6 .9)) rd))))
(sd (pow sd 5.0))
(col (mix (v! .05 .1 .2)
(v! .1 .05 .2)
sd)))
(* (v3! .63) col)))
;; vec3 stars(in vec3 p)
;; {
;; vec3 c = vec3(0.);
;; float res = iResolution.x*1.;
;; for (float i=0.;i<4.;i++)
;; {
;; vec3 q = fract(p*(.15*res))-0.5;
;; vec3 id = floor(p*(.15*res));
;; vec2 rn = hash33(id).xy;
;; float c2 = 1.-smoothstep(0.,.6,length(q));
;; c2 *= step(rn.x,.0005+i*i*0.001);
;; c += c2*(mix(vec3(1.0,0.49,0.1),vec3(0.75,0.9,1.),rn.y)*0.1+0.9);
;; p *= 1.3;
;; }
;; return c*c*.8;
;; }
(defun-g stars ((p :vec3) (resolution :vec2) (time :int))
(let* ((c (v3! 0.0))
(res (* 1. (x resolution))))
(for (i 0.) (< i 4) (++ i)
(let* ((q (- (fract (* p (* .15 res)))
(v3! 0.5)))
(rn (s~ (hash33 (floor (* p (* .15 res))) time) :xy))
(c2 (* (step (x rn) (+ .0005 (* i i .001)))
(- 1.0 (smoothstep 0.0 .6 (length q))))))
(setf c (+ c (* c2 (+ (v3! 0.9)
(* .1 (mix (v! 1.0 .49 .1)
(v! .75 .9 1.)
(y rn)))))))
(setf p (* p (v3! 1.3)))))
(* c c .8 )))
;; void mainImage( out vec4 fragColor, in vec2 fragCoord )
;; {
;; vec2 q = fragCoord.xy / iResolution.xy;
;; vec2 p = q - 0.5;
;; p.x*=iResolution.x/iResolution.y;
;; vec3 rd = normalize(vec3(p,1.3));
;; vec3 col = vec3(0.);
;; float fade = smoothstep(0.,0.01,abs(rd.y))*0.1+0.9;
;; col = bg(rd)*fade;
;; if (rd.y > 0.){
;; col += stars(rd);
;; }
;; fragColor = vec4(col, 1.);
;; }
(defun-g draw-verts-frag-stage (&uniform (resolution :vec2) (time :int))
(let* ((q (/ (s~ gl-frag-coord :xy)
(s~ resolution :xy)))
(p (- q (v2! 0.5)))
(p (v2! (* (x p) (/ (x resolution) (y resolution)))
(y p)))
(rd (normalize (v! p 1.3)))
(fade (+ 0.9
(* 0.1
(smoothstep 0.0 0.01 (abs (y rd))))))
(col (* fade (bg rd))))
;(cond ((> (y rd) 0.)
; (setf col (+ col (stars rd resolution)))))
(v! (+ col (stars rd resolution time)) 1.0)
))
(defun-g draw-verts-frag-stage (&uniform (resolution :vec2) (time :int))
(let* ((st (v! (/ (x gl-frag-coord) (x resolution))
(/ (y gl-frag-coord) (y resolution))))
(color (v! (step .5 (x st))
(step .5 (x st))
(step .5 (x st)))))
(v! 0.0 0.0 (* .1 (x (hash33 (v! .2 100. .5)))) 1.0)
))
(defpipeline-g draw-verts-pipeline ()
:vertex (draw-verts-vert-stage :vec2)
:fragment (draw-verts-frag-stage))
(defun now ()
(get-internal-real-time))
(defun draw! ()
(step-host)
(setf (resolution (current-viewport))
(surface-resolution (current-surface *cepl-context*)))
(clear)
(map-g #'draw-verts-pipeline *vert-stream*
:resolution (viewport-resolution (current-viewport))
:time (now))
(swap))
(defun init ()
(when *gpu-verts-arr*
(free *gpu-verts-arr*))
(when *gpu-index-arr*
(free *gpu-index-arr*))
(when *vert-stream*
(free *vert-stream*))
(setf *gpu-verts-arr*
(make-gpu-array
(list (v! -1.0 1.0)
(v! -1.0 -1.0)
(v! 1.0 -1.0)
(v! 1.0 1.0))
:element-type :vec2))
(setf *gpu-index-arr*
(make-gpu-array
(list 0 1 2
0 2 3)))
(setf *vert-stream*
(make-buffer-stream *gpu-verts-arr*
:index-array *gpu-index-arr*)))
(def-simple-main-loop play (:on-start #'init)
(draw!))
| 5,044 | Common Lisp | .lisp | 146 | 26.883562 | 76 | 0.441846 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 21c406481347a3d27c72bcb331a770a3f287bf58773f0819c252c227b538a047 | 9,083 | [
-1
] |
9,084 | incudine-guitar-standalone.lisp | azimut_shiny/examples/incudine-guitar-standalone.lisp | (in-package :shiny)
;; https://sourceforge.net/p/incudine/mailman/message/34320609/
;; https://ccrma.stanford.edu/realsimple/faust_strings/faust_strings.pdf
(define-vug diffgtz (x)
(if (plusp (- x (delay1 x)))
1.0d0
0.0d0))
(define-vug decay (n x)
(- x (if (plusp x)
(/ n)
0.0d0)))
(define-vug release (n x)
(~ (+ x (decay n it))))
(define-vug trigger (n x)
(if (plusp (release n (diffgtz x)))
1.0d0
0.0d0))
(define-vug pickdir (in coef)
(with-samples ((g (- 1 coef)))
(pole (* g in) coef)))
(define-vug pickpos (in beta p)
(with ((ppdel (sample->fixnum (* beta p))))
(- (delay-s in 2048 ppdel) in)))
(define-vug symmetric-twozero (in h0 h1)
(with-samples ((del1 (delay1 in)))
(+ (* h0 del1) (* h1 (+ in (delay1 del1))))))
(define-vug damping-filter2 (in freq t60 b)
(with-samples ((k (/ (* freq t60)))
(rho (expt .001d0 k))
(h0 (* (+ 1 b) 0.5))
(h1 (* (- 1 b) 0.25)))
(* rho (symmetric-twozero in h0 h1))))
(define-vug level-filter (x l freq)
(with-samples ((l0 (expt (the non-negative-sample l) (incudine.util:sample 1/3)))
(lw (* pi freq *sample-duration*))
(lgain (/ lw (+ 1 lw)))
(lpole2 (/ (- 1 lw) (+ 1 lw)))
(s0 (* l l0 x))
(s1 (- 1 l)))
(+ s0 (* s1 (~ (+ (* x lgain) (* lpole2 it)))))))
(defvar *env1* nil)
(setf *env1* (make-perc 0 .25))
;; (define-vug excitation (gain p)
;; (* (white-noise gain) (trigger p (incudine.util:sample (incudine.vug:mouse-button)))))
;; (define-vug excitation (gain p)
;; (* (white-noise gain)
;; (trigger p (incudine.util:sample 1.))))
(define-vug excitation (gain p)
(* (white-noise gain)
(cond ((eq (trigger p (incudine.util:sample 1.)) 1.) 1) (t (envelope *env1* 1 1. #'incudine:stop)))))
;; (define-vug excitation (gain p)
;; (* (white-noise gain)
;; (envelope *env1* 1 1. #'incudine:stop)))
;; ; (trigger p (incudine.util:sample (incudine.vug:mouse-button)))))
;;(defvar *env1* (make-envelope '(0 1 0) '(.2 .8)))
;; (setf *env1* (make-envelope '(0 1 1 0) '( .1 .3 .31) :curve :step))
;; (setf *env1* (make-envelope '(0 1 0) '(.39999 .3999999 )))
;; (setf *env1* (make-envelope '(0 1 0) '(.1 .5) :curve :step))
;; (setf *env1* (make-envelope '(0 1 0) '(.1 .11) :curve :step))
(define-vug filtered-excitation (gain freq pickangle beta l)
(with-samples ((p (/ *sample-rate* freq)))
(level-filter (pickpos (pickdir (excitation gain p) pickangle) beta p)
l freq)))
(define-vug stringloop (in freq t60 b)
(with-samples ((dt (/ freq)))
(~ (damping-filter2 (vdelay (+ in it) 0.05 dt :cubic) freq t60 b))))
(dsp! pluck-test (gain freq pickangle beta l t60 b)
(foreach-frame
(stereo
(stringloop
(filtered-excitation gain freq pickangle beta l)
freq t60 b))))
(set-rt-block-size 64)
(rt-start)
;; -----------------------
(defvar *myscale* nil)
(setf *myscale* '(0 2 3 5 7 8 10) )
(setf *myscale* '(0 1 3 5 6 8 10) )
(setf *myscale* (scale 0 'phrygian))
(pluck-test .5 440 .7 .1 .3 4 .5)
(defun right ()
;;(play-lsample-f (qcosr *myscale* 60 7 3/4) 1. .2)
;;(pluck-test .7 440 .7 .1 .3 4 .5)
(pluck-test .7
(midihz (qcosr *myscale* 60 7 3/4))
(cosr .7 .2 .3) .1 .3 4 .5)
(at (tempo-sync #[(cosr .9 .1 1/4) b]) #'right)
)
(defun left ()
;;(play-lsample-f (qcosr *myscale* 60 7 3/4) 1. .2)
;;(pluck-test .7 400 .7 .1 .3 4 .5)
(pluck-test .7
(midihz (qcosr *myscale* 40 7 3/4))
(cosr .7 .2 .3) .1 .3 4 .5)
(at (tempo-sync #[3 b]) #'left)
)
(right)
(left)
(flush-pending)
(incudine:free 0)
(rt-stop)
| 3,726 | Common Lisp | .lisp | 101 | 32.168317 | 106 | 0.562032 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 76dbe538d63a61d5d087624971896ef1e7c237e6e3e25933adf2ab0400f48c23 | 9,084 | [
-1
] |
9,085 | incudine1.lisp | azimut_shiny/examples/incudine1.lisp | ;;;; somecepl.lisp
(in-package #:shiny)
;;; "somecepl" goes here. Hacks and glory await!
(defvar *gpu-verts-arr* nil)
(defvar *gpu-index-arr* nil)
(defvar *vert-stream* nil)
;; From Music V family.
(define-vug rms (in hp)
(:defaults 0 30)
(with-samples ((b (- 2 (cos (* hp *twopi-div-sr*))))
(c2 (- b (sqrt (the non-negative-sample (1- (* b b))))))
(c1 (- 1 c2))
(in2 (* in in))
(q +sample-zero+))
(sqrt (the non-negative-sample (~ (+ (* c1 in2) (* c2 it)))))))
(dsp! rms-test (gain freq rms)
"Get the RMS amplitude by using a control parameter with side effect."
(:defaults -14 440 0)
(with-samples ((ma (* .5 (db->lin gain)))
(in (sine freq (+ ma (sine 4 ma 0)) 0)))
(setf rms (rms in))
(out in)))
(rt-start)
(rms-test -14 400 0 :id 123)
(set-control 123 'freq 320)
(lin->db (control-value 123 'rms))
(incudine:free 123)
(defun-g draw-verts-vert-stage ((vert :vec2))
(v! vert 0 1))
(defun-g draw-verts-frag-stage (&uniform
(resolution :vec2)
(time :float))
(let* ((st (v! (/ (x gl-frag-coord) (x resolution))
(/ (y gl-frag-coord) (y resolution))))
(stepn (abs (sin time)))
(color (v! (step stepn (x st))
(step stepn (x st))
(step stepn (x st)))))
(v! color 1.0)
))
(defpipeline-g draw-verts-pipeline ()
:vertex (draw-verts-vert-stage :vec2)
:fragment (draw-verts-frag-stage))
(defun getnow ()
(/ (float (get-internal-real-time)) 1000 ))
(defun draw! ()
(step-host)
(setf (resolution (current-viewport))
(surface-resolution (current-surface *cepl-context*)))
(clear)
(map-g #'draw-verts-pipeline *vert-stream*
:resolution (viewport-resolution (current-viewport))
:time (getnow))
(swap))
(defun init ()
(when *gpu-verts-arr*
(free *gpu-verts-arr*))
(when *gpu-index-arr*
(free *gpu-index-arr*))
(when *vert-stream*
(free *vert-stream*))
(setf *gpu-verts-arr*
(make-gpu-array
(list (v! -1.0 1.0)
(v! -1.0 -1.0)
(v! 1.0 -1.0)
(v! 1.0 1.0))
:element-type :vec2))
(setf *gpu-index-arr*
(make-gpu-array
(list 0 1 2
0 2 3)))
(setf *vert-stream*
(make-buffer-stream *gpu-verts-arr*
:index-array *gpu-index-arr*)))
(def-simple-main-loop play (:on-start #'init)
(draw!))
| 2,583 | Common Lisp | .lisp | 77 | 26.025974 | 74 | 0.533495 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 0fe38385bcb9baad83708e7be9ecf478f1ce70de91cff50a10b4a89f49ecdcdd | 9,085 | [
-1
] |
9,086 | simpleincudine3d2.lisp | azimut_shiny/examples/simpleincudine3d2.lisp | (in-package #:shiny)
;; ----------------------------------
;; ----------------------------------
;; From Music V family.
(define-vug rms (in hp)
(:defaults 0 60)
(with-samples ((b (- 2 (cos (* hp *twopi-div-sr*))))
(c2 (- b (sqrt (the non-negative-sample (1- (* b b))))))
(c1 (- 1 c2))
(in2 (* in in))
(q +sample-zero+))
(sqrt (the non-negative-sample (~ (+ (* c1 in2) (* c2 it)))))))
#|
(dsp! rms-master-out-test2 ()
(setf (bus 100)
(rms (audio-out 0))))
|#
(defvar *grms* nil)
(dsp! rms-master-out-test3 ()
(incudine.vug:with ((i 0)
(rms +sample-zero+))
(declare (incudine.util:sample rms))
;; Note: it is possible to optimize RMS here.
(setf rms (rms (audio-out 0)))
(when (= i 0)
;; or (nrt-funcall (lambda () (send-to-cepl rms)))
;; (lock-free-send-to-cepl rms))
(setf *grms* (coerce rms 'single-float)))
;; 256 samples are about 5ms if sr 48000
(setf i (logand (1+ i) 255))))
(dsp! rms-master-out-test3 ()
(with ((i 0)
(rms +sample-zero+))
(declare (sample rms))
;; Note: it is possible to optimize RMS here.
(setf rms (rms (audio-out 0)))
(when (= i 0)
;; or (nrt-funcall (lambda () (send-to-cepl rms)))
;; (setf *grms* (coerce rms 'single-float) ) )
;; 256 samples are about 5ms if sr 48000
(setf i (logand (1+ i) 255))))
#|
(defun rms-master ()
(coerce (incudine.util:barrier (:memory) (bus 100)) 'single-float))
|#
(rms-master-out-test2 :id 100 :tail 0)
(rms-master-out-test3 :id 100 :tail 0)
(incudine:free 100)
;;(rms-master)
;; ----------------------------------
;; "somecepl" goes here. Hacks and glory await!
;; ----------------------------------
(defvar *buf-stream* nil)
(defvar *gpu-arr* nil)
(defvar *light-pos* (v! 0 30 -5))
(defclass camera ()
((pos :initform (v! 0 0 0) :accessor pos)
(rot :initform (q:identity) :accessor rot)))
(defvar *camera* (make-instance 'camera))
(defclass thing ()
((pos :initform (v! 0 0 0) :accessor pos)
(rot :initform (q:identity) :accessor rot)))
(defvar *things* (loop :for i :below 40 :collect
(make-instance 'thing)))
(defun tt ()
(coerce (get-internal-run-time) 'single-float))
(defun-g vert-stage ((vert g-pnt) &uniform
;; (time :float)
;; (rms :float)
(model->world :mat4)
(world->view :mat4)
(view->clip :mat4))
(let* ((pos (pos vert))
(color (+ (pos vert) (v! .5 .5 .5)))
;; (id gl-instance-id)
;; (rms (* 150 rms))
;; (time (+ (/ time 50)
;; id
;; rms))
;; model space -> world space
(pos (v! pos 1))
(pos (* model->world pos))
;; world space -> view/camera/eye space
(pos (* world->view pos)))
;; view space -> clip space
(values (* view->clip pos) color)))
(defun-g frag-stage ((color :vec3)&uniform
(resolution :vec2)
(time :float)
(light-pos :vec3)
(rms :float))
(let* ((object-color (v! 1 1 0 0))
(ambient 0.4)
(diffuse 0.0)
(light-amount (+ ambient diffuse)))
(* object-color light-amount)
color))
(defun get-world->view-space (camera)
(m4:*
(m4:translation (v3:negate (pos camera)))
(q:to-mat4 (q:inverse (rot camera)))))
(defun get-model->world-space (thing)
(m4:*
(m4:translation (pos thing)))
(q:to-mat4 (rot thing)))
(defpipeline-g draw-verts-pipeline ()
:vertex (vert-stage g-pnt)
:fragment (frag-stage :vec3))
(defun draw! ()
(step-host)
(setf (resolution (current-viewport))
(surface-resolution (current-surface (cepl-context))))
;; (setf *cam-rot*
;; (q:from-axis-angle
;; (v! 0 0 1)
;; (radians (* 10 (sin (* .05 (tt)) ) ))))
(clear)
(loop :for thing :in *things* :do
(map-g #'draw-verts-pipeline *buf-stream*
:resolution (viewport-resolution (current-viewport))
;; :time (tt)
:light-pos *light-pos*
;; :rms (rms-master)
:model->world (get-model->world-space thing)
:world->view (get-world->view-space *camera*)
:view->clip (rtg-math.projection:perspective
(x (viewport-resolution (current-viewport)))
(y (viewport-resolution (current-viewport)))
0.4
200f0
60f0)))
(swap))
(defun runinit ()
(unless *buf-stream*
(destructuring-bind (vert index)
(nineveh.mesh.data.primitives:cube-gpu-arrays)
(setf *buf-stream*
(make-buffer-stream vert :index-array index)))))
(def-simple-main-loop runplay (:on-start #'runinit)
(draw!))
#|
(setf (depth-test-function (cepl-context)) nil)
(setf (depth-test-function (cepl-context)) #'<)
|#
| 5,077 | Common Lisp | .lisp | 144 | 28.111111 | 74 | 0.520676 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | c6e200242649fa1026de3034096e92739b0769035a16924a2ef060e2546e52fd | 9,086 | [
-1
] |
9,087 | simple-1.lisp | azimut_shiny/examples/simple-1.lisp | ;;;; somecepl.lisp
(in-package #:shiny)
;;; "somecepl" goes here. Hacks and glory await!
(defvar *tex* nil)
(defvar *ctex* nil)
(setf *ctex* (loop :for j :below 2 :collect
(loop :for i :below 512 :collect
(random 1.0))))
(setf *tex* (make-texture *ctex*
:element-type :float
:dimensions '(2 512)))
(defvar *sam* nil)
(setf *sam* (cepl:sample *tex*))
(defvar *gpu-verts-arr* nil)
(defvar *gpu-index-arr* nil)
(defvar *vert-stream* nil)
(defvar *viewport* nil)
(setf *viewport* (make-viewport '(400 400)))
;; ------------------------------------------
(defun-g vert ((vert :vec2))
(v! vert 0 1))
;; ------------------------------------------
#|
void main() {
vec2 st = gl_FragCoord.xy/u_resolution.xy;
vec3 color = vec3(0.);
float total = 4.;
float col = floor(st.x*total);
color += float(floor(mod(u_time,total)) == col);
gl_FragColor = vec4(color,1.);
}
|#
;; http://thebookofshaders.com/edit.php?log=180220141500
(defun-g frag (&uniform
(resolution :vec2)
(time :float))
(let* ((st (/ (s~ gl-frag-coord :xy)
resolution))
(color (v3! 0))
(total 4.0)
(col (floor (* total (x st))))
(color (+ color
(v3!
(float
(eql
(floor (mod time total))
col))))))
(v! color 0)))
#|
http://thebookofshaders.com/edit.php?log=180220141210
void main() {
vec2 st = gl_FragCoord.xy/u_resolution.xy;
float dt = 2.;
float t = step(mod(u_time, dt),.2);
float t2 = step(mod(u_time-(1.*dt*.1), dt),.2);
float t3 = step(mod(u_time-(2.*dt*.1), dt),.2);
float t4 = step(mod(u_time-(3.*dt*.1), dt),.2);
float c =step(st.x,.25)*t;
c+= (step(st.x,.5)-step(st.x,.25))*t2;
c+= (step(st.x,.75)-step(st.x,.5))*t3;
c+= (step(st.x,1.)-step(st.x,.75))*t4;
gl_FragColor = vec4(vec3(c),1.);
}
|#
(defun-g frag (&uniform
(resolution :vec2)
(time :float))
(let* ((st (/ (s~ gl-frag-coord :xy)
resolution))
(dt 2.0)
(t1 (step (mod time dt) .2))
(t2 (step (mod (- time (* 1. dt .1)) dt) .2))
(t3 (step (mod (- time (* 2. dt .1)) dt) .2))
(t4 (step (mod (- time (* 3. dt .1)) dt) .2))
(c (* t1 (step (x st) .25)))
(c (+ c (* t2 (- (step (x st) .5) (step (x st) .25)))))
(c (+ c (* t3 (- (step (x st) .75) (step (x st) .5)))))
(c (+ c (* t4 (- (step (x st) 1.) (step (x st) .75))))))
(v! c c c 0)))
#|
void main() {
vec2 st = gl_FragCoord.xy/u_resolution.xy;
float dt = 2.;
float t = step(mod(u_time, dt),.2);
float t2 = step(mod(u_time-(1.*dt*.1), dt),.2);
float t3 = step(mod(u_time-(2.*dt*.1), dt),.2);
float t4 = step(mod(u_time-(3.*dt*.1), dt),.2);
float c1 =step(st.x,.25)*t;
float c2 = (step(st.x,.5)-step(st.x,.25))*t2;
float c3= (step(st.x,.75)-step(st.x,.5))*t3;
float c4= (step(st.x,1.)-step(st.x,.75))*t4;
float c = c1*sin(st.x*200.)
+ c2*sin(st.y*300.)
+ c3*sin((st.x+st.y)*200.)
+ c4*sin((st.x-st.y)*200.);
gl_FragColor = vec4(vec3(c),1.);
}
|#
(defun-g frag (&uniform
(resolution :vec2)
(time :float))
(let* ((st (/ (s~ gl-frag-coord :xy)
resolution))
(dt 3.)
(t1 (step (mod time dt) .2))
(t2 (step (mod (- time (* 1. dt .1)) dt) .2))
(t3 (step (mod (- time (* 2. dt .1)) dt) .2))
(t4 (step (mod (- time (* 3. dt .1)) dt) .2))
(c1 (* t1 (step (x st) .25)))
(c2 (* t2 (- (step (x st) .5) (step (x st) .25))))
(c3 (* t3 (- (step (x st) .75) (step (x st) .5))))
(c4 (* t4 (- (step (x st) 1.) (step (x st) .75))))
(c (+ (* c4 (sin (* 200. (x st))))
(* c3 (sin (* 300. (y st))))
(* c2 (sin (* 200. (+ (x st) (y st)))))
(* c1 (sin (* 200. (- (x st) (y st))))))))
(v! c c c 1)))
#|
void main() {
vec2 st = gl_FragCoord.xy/u_resolution.xy;
float dt = 1.;
float t = step(mod(u_time, dt),.25);
float t2 = step(mod(u_time-(1.*dt*.25), dt),.25);
float t3 = step(mod(u_time-(2.*dt*.25), dt),.25);
float t4 = step(mod(u_time-(3.*dt*.25), dt),.25);
vec2 cent = st*.5+.25;
float d = distance(st, cent);
float c1 = sin(d*100.)*t;
float c2 = sin(st.x*200.)*t2;
float c3 = sin(st.y*100.)*t3;
float c4= sin((st.x+st.y)*50.)*t4;
float c = c1
+ c2+c3+c4;
gl_FragColor = vec4(vec3(c),1.);
}
|#
(defun-g frag (&uniform
(time :float)
(resolution :vec2))
(let* ((st (/ (s~ gl-frag-coord :xy)
resolution))
(dt 1.)
(t1 (step (mod time dt) .25))
(t2 (step (mod (- time (* 1. dt .25)) dt) .25))
(t3 (step (mod (- time (* 2. dt .25)) dt) .25))
(t4 (step (mod (- time (* 3. dt .25)) dt) .25))
(cent (+ (v2! .25)
(* (v2! .5)
st)))
(d (distance st cent))
(c1 (* t1 (sin (* 100. d))))
(c2 (* t2 (sin (* 200. (x st)))))
(c3 (* t3 (sin (* 100. (y st)))))
(c4 (* t4 (sin (* 50. (+ (x st) (y st))))))
(c (+ c1 c2 c3 c4)))
(v! c c c 0)))
;; ------------------------------------------
;; formulanimations tutorial ::
;; the principles of painting with maths
;; https://www.youtube.com/watch?v=0ifChJ0nJfM
;; gradiant 1
(defun-g frag (&uniform (time :float) (resolution :vec2))
(let* ((st (/ (s~ gl-frag-coord :xy)
resolution))
(col (v! 1. .4 .1))
(col (* col (x st))))
(v! col 0)))
;; gradiant 2
(defun-g frag (&uniform (time :float) (resolution :vec2))
(let* ((st (/ (s~ gl-frag-coord :xy)
resolution))
(col (v! 1. .4 .1))
(col (* col (/ (x st)
(y st)))))
(v! col 0)))
;; gradiant 3
(defun-g frag (&uniform (time :float) (resolution :vec2))
(let* ((st (/ (s~ gl-frag-coord :xy)
resolution))
(col (v! 1. .4 .1))
(q (- st (v! .5 .5)))
(col (* col (length q))))
(v! col 0)))
;; shadertone vvv.glsl
(defun-g frag (&uniform (time :float) (resolution :vec2))
(let* ((uv (/ (s~ gl-frag-coord :xy)
resolution))
(A 300)
(B 300)
;; put A, B into 0,1 range
(a (+ .5 (/ (- A 300.) 50. 2.)))
(b (+ .5 (/ (- B 300.) 100. 2.)))
;; make a vertical step for A
(ac (smoothstep 0. 0.05 (- (x uv) a)))
;; make a horizontal step for B
(bc (smoothstep 0. 0.05 (- (y uv) b)))
(c (* (v3! ac) (v! 0. .5 1.)))
(c (+ c (* (v3! bc) (v! 1. .5 0)))))
(v! c 0)))
;; ------------------------------------------
(defun-g frag (&uniform (time :float) (resolution :vec2))
(let* ((st (/ (s~ gl-frag-coord :xy)
resolution))
(col (v! 1. .4 .1))
(col (* col (x st))))
(v! col 0)))
(defpipeline-g draw-verts-pipeline ()
:vertex (vert :vec2)
:fragment (frag))
;; ------------------------------------------
(defun draw! ()
(step-host)
(clear)
(with-viewport *viewport*
(map-g #'draw-verts-pipeline *vert-stream*
:resolution (viewport-resolution (current-viewport))
:time (mynow)))
(swap))
(defun runinit ()
(when *gpu-verts-arr*
(free *gpu-verts-arr*))
(when *gpu-index-arr*
(free *gpu-index-arr*))
(when *vert-stream*
(free *vert-stream*))
(setf *gpu-verts-arr*
(make-gpu-array
(list (v! -1 1)
(v! -1 -1)
(v! 1 -1)
(v! 1 1))
:element-type :vec2))
(setf *gpu-index-arr*
(make-gpu-array
(list 0 1 2
0 2 3)))
(setf *vert-stream*
(make-buffer-stream *gpu-verts-arr*
:index-array *gpu-index-arr*)))
(def-simple-main-loop runplay (:on-start #'runinit)
(draw!))
| 8,114 | Common Lisp | .lisp | 241 | 26.240664 | 66 | 0.454929 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 53f439d2e79bbc87c28d89edcebdabe8c07eaebef5a499fecca2941e86d0996d | 9,087 | [
-1
] |
9,088 | graphing.lisp | azimut_shiny/examples/graphing.lisp | ;;;; somecepl.lisp
(in-package #:shiny)
;;; "somecepl" goes here. Hacks and glory await!
(defvar *gpu-verts-arr* nil)
(defvar *gpu-index-arr* nil)
(defvar *vert-stream* nil)
(defun-g vert-stage ((pos :vec2))
(values (v! pos 0 1)
(* 0.5 (+ pos (v2! 1.0)))))
(defun-g hash33 ((p :vec3) (time :int))
(let* ((p (fract (* p (v! (* 0.00000000001 time)
"7.2973"
"1.1871"))))
(p (+ p (v3! (dot (s~ p :zxy)
(+ (v3! 19.27)
(s~ p :yxz) ))))))
(fract (v! (* (x p) (y p))
(* (z p) (x p))
(* (y p) (z p))))))
(defun-g stars ((p :vec3) (resolution :vec2) (time :int))
(let* ((c (v3! 0.0))
(res (* 1. (x resolution))))
(for (i 0.) (< i 4) (++ i)
(let* ((q (- (fract (* p (* .15 res)))
(v3! 0.5)))
(rn (s~ (hash33 (floor (* p (* .15 res))) time) :xy))
(c2 (* (step (x rn) (+ .0005 (* i i .001)))
(- 1.0 (smoothstep 0.0 .6 (length q))))))
(setf c (+ c (* c2 (+ (v3! 0.9)
(* .1 (mix (v! 1.0 .49 .1)
(v! .75 .9 1.)
(y rn)))))))
(setf p (* p (v3! 1.3)))))
(* c c .8 )))
(defun-g frag-stage ((uv :vec2) &uniform (resolution :vec2))
(let* ((st (v! (/ (x gl-frag-coord) (x resolution))
(/ (y gl-frag-coord) (y resolution))))
(color (v! (step .5 (x st))
(step .5 (x st))
(step .5 (x st)))))
;; (graph (lambda ((x :float)) (sin x))
;; uv
;; (v! -5 5 -2 2))
;; (graph (lambda ((x :float)) (x (hash33 (v! x x x) 1)))
;; uv
;; (v! -.01 .01 -1 1))
;; (graph (lambda ((x :float)) (y (stars (v! 1. x 1.)
;; (v! 320. 240.)
;; 1)))
;; uv
;; (v! -3 3 -1 1))
(plot .5
uv
(v! -3 3 -1 1))
))
(defpipeline-g draw-verts-pipeline ()
:vertex (vert-stage :vec2)
:fragment (frag-stage :vec2))
(defun now ()
(get-internal-real-time))
(defun draw! ()
(step-host)
(setf (resolution (current-viewport))
(surface-resolution (current-surface *cepl-context*)))
(clear)
(map-g #'draw-verts-pipeline *vert-stream*
:resolution (viewport-resolution (current-viewport)))
(swap))
(defun init ()
(when *gpu-verts-arr*
(free *gpu-verts-arr*))
(when *gpu-index-arr*
(free *gpu-index-arr*))
(when *vert-stream*
(free *vert-stream*))
(setf *gpu-verts-arr*
(make-gpu-array
(list (v! -1.0 1.0)
(v! -1.0 -1.0)
(v! 1.0 -1.0)
(v! 1.0 1.0))
:element-type :vec2))
(setf *gpu-index-arr*
(make-gpu-array
(list 0 1 2
0 2 3)))
(setf *vert-stream*
(make-buffer-stream *gpu-verts-arr*
:index-array *gpu-index-arr*)))
(def-simple-main-loop play (:on-start #'init)
(draw!))
| 3,246 | Common Lisp | .lisp | 91 | 25.758242 | 69 | 0.4066 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 4a82cff08673b8b81275e01f7f782818d9f11af94a37fe3ebcad24241b68a3f0 | 9,088 | [
-1
] |
9,089 | 20180813.lisp | azimut_shiny/examples/20180813.lisp | (in-package :shiny)
(defparameter *step* (make-stepper (seconds .05) (seconds 1)))
(defvar *car*
(make-c-array nil :dimensions 512 :element-type :float))
(defvar *bs* nil)
(defvar *tex* nil)
(defvar *sam* nil)
(defun-g frag
((uv :vec2) &uniform
(time :float) (texture :sampler-1d))
(let* ((tx (* 512 (x uv)))
;; (wave (texel-fetch texture ))
(something (texture texture tx))
(other (- 1f0 (smoothstep (v4! 0f0) (v4! .03) (abs (- something (+ -.5 (y uv)))))))
)
other))
(defpipeline-g pipe (:points)
:fragment (frag :vec2))
(defun draw! ()
(let ((res (surface-resolution (current-surface))))
(setf (viewport-resolution (current-viewport))
res)
(when (funcall *step*)
;; Test to upload random data to the c array
(loop :for i :upto 100
:do (setf (cepl:aref-c *c-arr* (+ (random 400) i)) (random 1f0)))
(setf *tex* (make-texture *c-arr*))
(setf *s-tex* (cepl:sample *tex*)))
(as-frame
(map-g #'pipe *bs*
:texture *s-tex*
:time (/ (get-internal-real-time)
1000f0)))))
(defun initialize ()
(unless *bs*
(setf *bs* (make-buffer-stream nil :primitive :points))
(setf *tex* (make-texture *car*))
(setf *sam* (cepl:sample *tex*))))
(def-simple-main-loop runplay (:on-start #'initialize)
(draw!))
| 1,381 | Common Lisp | .lisp | 40 | 28.775 | 92 | 0.578395 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 6bba890dcc0d1090cd67224c98c6ab0e38ba9144adc5567607f173e22a989007 | 9,089 | [
-1
] |
9,090 | plot.lisp | azimut_shiny/examples/plot.lisp | ;;;; somecepl.lisp
(in-package #:shiny)
;;; "somecepl" goes here. Hacks and glory await!
(defvar *gpu-verts-arr* nil)
(defvar *gpu-index-arr* nil)
(defvar *vert-stream* nil)
(defun-g draw-verts-vert-stage ((vert :vec2))
(v! vert 0 1))
(defun-g draw-verts-frag-stage (&uniform
(resolution :vec2) (time :float))
(let* ((st (v! (/ (x gl-frag-coord) (x resolution))
(/ (y gl-frag-coord) (y resolution))))
(color (v! .5 .5 .5)))
(v! color 1.0)
))
(defpipeline-g draw-verts-pipeline ()
:vertex (draw-verts-vert-stage :vec2)
:fragment (draw-verts-frag-stage))
(defun draw! ()
(step-host)
(setf (resolution (current-viewport))
(surface-resolution (current-surface (cepl-context))))
(clear)
(map-g #'draw-verts-pipeline *vert-stream*
:resolution (viewport-resolution (current-viewport))
:time (* .1 (get-internal-real-time)))
(swap))
(defun runinit ()
(when *gpu-verts-arr*
(free *gpu-verts-arr*))
(when *gpu-index-arr*
(free *gpu-index-arr*))
(when *vert-stream*
(free *vert-stream*))
(setf *gpu-verts-arr*
(make-gpu-array
(list (v! -1.0 1.0)
(v! -1.0 -1.0)
(v! 1.0 -1.0)
(v! 1.0 1.0))
:element-type :vec2))
(setf *gpu-index-arr*
(make-gpu-array
(list 0 1 2
0 2 3)))
(setf *vert-stream*
(make-buffer-stream *gpu-verts-arr*
:index-array *gpu-index-arr*)))
(def-simple-main-loop runplay (:on-start #'runinit)
(draw!))
| 1,618 | Common Lisp | .lisp | 50 | 25.34 | 65 | 0.558349 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | d6f0eb5b7fd28d5a4054eff394657aecd4acc5b5c902bb3fc4cc5f9cfbc34b41 | 9,090 | [
-1
] |
9,091 | simple.lisp | azimut_shiny/examples/simple.lisp | ;;;; somecepl.lisp
(in-package #:shiny)
;;; "somecepl" goes here. Hacks and glory await!
(defvar *gpu-verts-arr* nil)
(defvar *gpu-index-arr* nil)
(defvar *vert-stream* nil)
(defun-g draw-verts-vert-stage ((vert :vec2))
(v! vert 0 1))
(defun-g draw-verts-frag-stage (&uniform (resolution :vec2) (time :float))
(let* ((st (v! (/ (x gl-frag-coord) (x resolution))
(/ (y gl-frag-coord) (y resolution))))
(color (v! (step .5 (x st))
(step .5 (x st))
(step .5 (x st)))))
(v! (s~ color :xy) (sin time) 1.0)
))
(defpipeline-g draw-verts-pipeline ()
:vertex (draw-verts-vert-stage :vec2)
:fragment (draw-verts-frag-stage))
(defun draw! ()
(step-host)
;; (setf (resolution (current-viewport))
;; (surface-resolution (current-surface *cepl-context*)))
(clear)
(map-g #'draw-verts-pipeline *vert-stream*
:resolution (viewport-resolution (current-viewport))
:time (mynow))
(swap))
(defun runinit ()
(when *gpu-verts-arr*
(free *gpu-verts-arr*))
(when *gpu-index-arr*
(free *gpu-index-arr*))
(when *vert-stream*
(free *vert-stream*))
(setf *gpu-verts-arr*
(make-gpu-array
(list (v! -1.0 1.0)
(v! -1.0 -1.0)
(v! 1.0 -1.0)
(v! 1.0 1.0))
:element-type :vec2))
(setf *gpu-index-arr*
(make-gpu-array
(list 0 1 2
0 2 3)))
(setf *vert-stream*
(make-buffer-stream *gpu-verts-arr*
:index-array *gpu-index-arr*)))
(def-simple-main-loop runplay (:on-start #'runinit)
(draw!))
| 1,668 | Common Lisp | .lisp | 51 | 25.882353 | 74 | 0.55125 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 4a9d7fab7495fcb2f6d1b7d17a63a498893705ad34db3a9d3627ed1fd8c9a7f0 | 9,091 | [
-1
] |
9,092 | simpleincudine3d.lisp | azimut_shiny/examples/simpleincudine3d.lisp | ;;;; somecepl.lisp
(in-package #:shiny)
;; ----------------------------------
;; ----------------------------------
;; From Music V family.
(define-vug rms (in hp)
(:defaults 0 60)
(with-samples ((b (- 2 (cos (* hp *twopi-div-sr*))))
(c2 (- b (sqrt (the non-negative-sample (1- (* b b))))))
(c1 (- 1 c2))
(in2 (* in in))
(q +sample-zero+))
(sqrt (the non-negative-sample (~ (+ (* c1 in2) (* c2 it)))))))
#|
(dsp! rms-master-out-test2 ()
(setf (bus 100)
(rms (audio-out 0))))
|#
(defvar *grms* nil)
(dsp! rms-master-out-test3 ()
(incudine.vug:with ((i 0)
(rms +sample-zero+))
(declare (incudine.util:sample rms))
;; Note: it is possible to optimize RMS here.
(setf rms (rms (audio-out 0)))
(when (= i 0)
;; or (nrt-funcall (lambda () (send-to-cepl rms)))
;; (lock-free-send-to-cepl rms))
(setf *grms* (coerce rms 'single-float)))
;; 256 samples are about 5ms if sr 48000
(setf i (logand (1+ i) 255))))
(dsp! rms-master-out-test3 ()
(with ((i 0)
(rms +sample-zero+))
(declare (sample rms))
;; Note: it is possible to optimize RMS here.
(setf rms (rms (audio-out 0)))
(when (= i 0)
;; or (nrt-funcall (lambda () (send-to-cepl rms)))
(setf *grms* (coerce rms 'single-float) ) )
;; 256 samples are about 5ms if sr 48000
(setf i (logand (1+ i) 255))))
#|
(defun rms-master ()
(coerce (incudine.util:barrier (:memory) (bus 100)) 'single-float))
|#
(rms-master-out-test2 :id 100 :tail 0)
(rms-master-out-test3 :id 100 :tail 0)
(incudine:free 100)
;;(rms-master)
;; ----------------------------------
;; ----------------------------------
(defvar env2 (make-perc .001 .4))
(dsp! env-test-3 (freq amp pos (env envelope) gate)
(foreach-channel
(cout (pan2 (* (envelope env gate 1 #'stop)
(sine freq amp 0))
pos))))
(defun seq-test (rep freq amp pos)
(when (plusp rep)
(dsp-seq (env-test-3 freq amp pos env2 1)
(env-test-3 (* freq 7/4) amp pos env2 1)
(env-test-3 (* freq 2) amp pos env2 1)
(seq-test (1- rep) freq amp pos))))
(defun phr1 (time)
(at time #'seq-test 8 200 .3 .5)
(at (+ time #[2 b]) #'seq-test 6 400 .3 .4)
(at (+ time #[4 b]) #'seq-test 4 600 .3 .6))
(setf (bpm *tempo*) 120)
(phr1 (now))
;; ----------------------------------
;; "somecepl" goes here. Hacks and glory await!
;; ----------------------------------
(defvar *buf-stream* nil)
(defvar *gpu-arr* nil)
(defvar *cam-pos* (v! 0 0 0))
(defvar *cam-rot* (q:identity))
(defun tt ()
(coerce (get-internal-run-time) 'single-float))
(defun-g vert-stage ((vert g-pnt) &uniform
(time :float)
(rms :float)
(cam-pos :vec3)
(cam-rot :mat3)
(perspective :mat4))
(let* ((pos (pos vert))
(id gl-instance-id)
;;(id ( id))
(rms (* 200 rms))
(time (+ (/ time 50) id rms))
(color (+ (v3! (sin rms) ) (pos vert)))
(pos (+ pos (v! (cos (* 2 time)) (sin time) (+ -7 (sin time)) )))
(pos (+ pos cam-pos))
(pos (* cam-rot pos)))
(values
(* perspective (v! pos 1))
(:smooth color) )))
(defun-g frag-stage ((color :vec3) &uniform (resolution :vec2)
(time :float)
(rms :float))
(v! color 0)
)
(defpipeline-g draw-verts-pipeline ()
:vertex (vert-stage g-pnt)
:fragment (frag-stage :vec3))
(defun draw! ()
(step-host)
(setf (resolution (current-viewport))
(surface-resolution (current-surface (cepl-context))))
; (setf *cam-rot* (q:from-axis-angle (v! 0 0 1) (radians (* 10 (sin (* .05 (tt)) ) ))))
(clear)
(with-instances 40
(map-g #'draw-verts-pipeline *buf-stream*
:resolution (viewport-resolution (current-viewport))
:time (tt)
:rms (rms-master)
:cam-pos *cam-pos*
:cam-rot (q:to-mat3 (q:inverse *cam-rot*))
:perspective (rtg-math.projection:perspective
(x (viewport-resolution (current-viewport)))
(y (viewport-resolution (current-viewport)))
0.5
30f0
60f0)))
(swap))
(defun runinit ()
(unless *buf-stream*
(destructuring-bind (vert index)
(nineveh.mesh.data.primitives:cube-gpu-arrays)
(setf *buf-stream*
(make-buffer-stream vert :index-array index)))))
(def-simple-main-loop runplay (:on-start #'runinit)
(draw!))
#|
(setf (depth-test-function (cepl-context)) nil)
(setf (depth-test-function (cepl-context)) #'<)
|#
| 4,843 | Common Lisp | .lisp | 137 | 28.10219 | 89 | 0.509728 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 61d39cd2d3f5fd1f16ba55f6cdaed65642a903ea82d9e16a31cad7d7da375146 | 9,092 | [
-1
] |
9,093 | noise.lisp | azimut_shiny/examples/noise.lisp | ;;;; somecepl.lisp
(in-package #:shiny)
;;; "somecepl" goes here. Hacks and glory await!
(defvar *gpu-verts-arr* nil)
(defvar *gpu-index-arr* nil)
(defvar *vert-stream* nil)
(defun-g draw-verts-vert-stage ((vert :vec2))
(v! vert 0 1))
(defun-g draw-verts-frag-stage (&uniform (resolution :vec2))
(let* ((st (v! (/ (x gl-frag-coord) (x resolution))
(/ (y gl-frag-coord) (y resolution))))
(color (v! (step .5 (x st))
(step .5 (x st))
(step .5 (x st)))))
(perlin-noise (* (v3! 18.) (v! st 1.0)) )
))
(defpipeline-g draw-verts-pipeline ()
:vertex (draw-verts-vert-stage :vec2)
:fragment (draw-verts-frag-stage))
(defun draw! ()
(step-host)
(setf (resolution (current-viewport))
(surface-resolution (current-surface *cepl-context*)))
(clear)
(map-g #'draw-verts-pipeline *vert-stream*
:resolution (viewport-resolution (current-viewport)))
(swap))
(defun init ()
(when *gpu-verts-arr*
(free *gpu-verts-arr*))
(when *gpu-index-arr*
(free *gpu-index-arr*))
(when *vert-stream*
(free *vert-stream*))
(setf *gpu-verts-arr*
(make-gpu-array
(list (v! -1.0 1.0)
(v! -1.0 -1.0)
(v! 1.0 -1.0)
(v! 1.0 1.0))
:element-type :vec2))
(setf *gpu-index-arr*
(make-gpu-array
(list 0 1 2
0 2 3)))
(setf *vert-stream*
(make-buffer-stream *gpu-verts-arr*
:index-array *gpu-index-arr*)))
(def-simple-main-loop play (:on-start #'init)
(draw!))
| 1,624 | Common Lisp | .lisp | 50 | 25.52 | 63 | 0.550064 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 89c0961c71190f8941dffbb18f5db5d57a03d820fd79b759fc0540186d223f18 | 9,093 | [
-1
] |
9,094 | incudineret.lisp | azimut_shiny/examples/incudineret.lisp | (in-package :shiny)
;; From Music V family.
(define-vug rms (in hp)
(:defaults 0 60)
(with-samples ((b (- 2 (cos (* hp *twopi-div-sr*))))
(c2 (- b (sqrt (the non-negative-sample (1- (* b b))))))
(c1 (- 1 c2))
(in2 (* in in))
(q +sample-zero+))
(sqrt (the non-negative-sample (~ (+ (* c1 in2) (* c2 it)))))))
(dsp! rms-test (gain freq rms)
"Get the RMS amplitude by using a control parameter with side effect."
(:defaults -14 440 0)
(with-samples ((ma (* .5 (db->lin gain)))
(in (sine freq (+ ma (sine 4 ma 0)) 0)))
(setf rms (rms in))
(out in)))
(rt-start)
(rms-test :id 123)
(lin->db (control-value 123 'rms))
(incudine:free 123)
;;;
;;;
;;;
(dsp! rms-master-out-test (rms)
(:defaults 0)
(setf rms (rms (audio-out 0))))
(defun rms-value (id)
(lin->db (control-value id 'rms)))
(rms-test -20 440 :id 1)
(rms-test -20 555 :id 2)
(rms-test -20 666 :id 3)
;; The last DSP to get the RMS amp of the mix.
(rms-master-out-test :id 100 :tail 0)
;; Mix
(rms-value 100)
;; Get all the values from rt-thread
(rt-eval (:return-value-p t) (mapcar #'rms-value '(1 2 3 100)))
(incudine:free 0)
;;;
;;; Alternative 1: a bus for master out
;;;
#|
(dsp! rms-master-out-test2 ()
(setf (bus 100) (audio-out 0)))
(defun rms-master ()
(lin->db (incudine.util:barrier (:memory) (bus 100))))
|#
(dsp! rms-master-out-test2 ()
(setf (bus 100)
(rms (audio-out 0))))
(defun rms-master ()
(incudine.util:barrier (:memory) (bus 100)))
(rms-test -20 440 :id 1)
(rms-test -20 555 :id 2)
(rms-test -20 666 :id 3)
(rms-test -20 100 :id 4)
(rms-master-out-test2 :id 100 :tail 0)
(rms-master)
(incudine:free 100)
(incudine:free 0)
;;;
;;; Alternative 2: lock-free call from DSP
;;;
(dsp! rms-master-out-test3 ()
(with ((i 0)
(rms +sample-zero+))
(declare (sample rms))
;; Note: it is possible to optimize RMS here.
(setf rms (rms (audio-out 0)))
(when (= i 0)
;; or (nrt-funcall (lambda () (send-to-cepl rms)))
(lock-free-send-to-cepl rms))
;; 256 samples are about 5ms if sr 48000
(setf i (logand (1+ i) 255))))
;;; Copy buffer data
(dsp! copy-buffer-data-test ((buf buffer))
[...]
(with-follow (buf)
;; warning: no size check [buffer-to-copy size is >= buf size otherwise...]
(incudine.external:foreign-copy-samples
(buffer-data buf)
;; copy from BUFFER-DATA, ABUFFER-DATA, foreign data, etc..
(buffer-data buffer-to-copy)
(buffer-size buf)))
[...])
;; to eval in rt-thread
(defun update-my-buffer (node buffer)
;; trigger the copy
(set-control node :buf buffer)
(lock-free-send-to-cepl show-buffer-data buffer))
(defvar *my-buffer* (make-buffer 1024))
(rt-eval () (update-my-buffer some-node *my-buffer*))
;; -----------
;; From 2nd getting started
;; Too noisy?
;; Too cpu (?) expensive when converting to list with buffer->list
(define-vug buffer-record ((buf buffer) in)
(incudine.vug:buffer-write buf (incudine.vug:counter 0 (buffer-size buf) :loop-p t) in))
(dsp! buffer-record-test ((buf buffer))
(when (zerop incudine.vug:current-channel)
(buffer-record buf (audio-in 0))))
(defvar btest (make-buffer 44100))
(buffer-record-test btest :id 1)
;; -----------
(defvar env2 (make-perc .001 .4))
(dsp! env-test-3 (freq amp pos (env envelope) gate)
(foreach-channel
(cout (pan2 (* (envelope env gate 1 #'stop)
(sine freq amp 0))
pos))))
(defun seq-test (rep freq amp pos)
(when (plusp rep)
(dsp-seq (env-test-3 freq amp pos env2 1)
(env-test-3 (* freq 7/4) amp pos env2 1)
(env-test-3 (* freq 2) amp pos env2 1)
(seq-test (1- rep) freq amp pos))))
(defun phr1 (time)
(at time #'seq-test 8 200 .3 .5)
(at (+ time #[2 b]) #'seq-test 6 400 .3 .4)
(at (+ time #[4 b]) #'seq-test 4 600 .3 .6))
(setf (bpm *tempo*) 120)
(phr1 (now))
| 3,965 | Common Lisp | .lisp | 123 | 28.284553 | 90 | 0.607209 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 0631dcce8d066e9791a5dde245df15fb88e633dae43e97a1ed8f491d842fe7a5 | 9,094 | [
-1
] |
9,095 | cv.lisp | azimut_shiny/examples/cv.lisp | (in-package :shiny)
(defvar *hsv* nil)
(defvar *rgb* nil)
(defvar *h* nil)
(defvar *w* nil)
(defvar *p* nil)
(defvar *fh* nil)
(defparameter *vevents* '())
(defclass to-sec ()
((sec :initarg :sec :initform 0f0)))
(defclass to-hsv ()
((secs :initarg :secs :initform 0f0)))
;; This needs (callback) from scheduler/cl-collider
(defgeneric update (obj capture fps seconds)
(:method ((obj to-sec) capture fps seconds)
(with-slots (sec) obj
(cv:set-capture-property capture
cv:+cap-prop-pos-frame+
(* fps (min sec seconds)))))
(:method ((obj to-hsv) capture fps seconds)
(with-slots (secs) obj
(setf *hsv* 1)
(callback (+ (now) secs) #'(lambda () (setq *hsv* nil))))))
;; made a separate function instead of directly on the loop to be able to recompile on the fly. Using an infinite recursive function doesn't work either as a SBCL stack get's eventually overflow on these type of funtions.
(defun render (frame filename mat)
(let ((mysize (cv:size 100 100)))
(if (= (cv:wait-key 30) 27)
'done
(cv:with-ipl-images
((img mysize cv:+ipl-depth-8u+ 3)
(cimg mysize cv:+ipl-depth-8u+ 1))
;;(cv:copy frame img)
(cv:resize frame img)
(cv:repeat img frame)
;;(cv:flip img img 1)
;;(cv:cvt-color img cimg cv:+bgr-2-gray+)
;; (cv:cvt-color img img cv:+bgr-2-rgb+)
;; (cv:cvt-color img img cv:+bgr-2-hsv+)
;; (and (= 0 (mod (get-universal-time) 10))
;; (cv:flip img img 1))
;; (2d-rotate mat 20 50 0f0 .7)
;; (cv:warp-affine img img mat)
(cv:show-image filename frame)))))
(defun show-video (filename)
"Show the video in FILENAME in a window."
(cv:with-named-window
(filename (+ +window-freeratio+ +window-gui-normal+))
(with-captured-file (capture filename)
(let ((mat (cv:create-mat 2 3 cv:+32fc1+)))
(loop
(let ((frame (cv:query-frame capture)))
;; livecoding
(update-swank)
;; check if we got a valid frame
(if (not (cffi:null-pointer-p frame))
(when (eq 'done (render frame filename mat))
(return))
;; repeat video ad-infinitum
(skip-to capture 0))))))))
| 2,376 | Common Lisp | .lisp | 59 | 32.322034 | 221 | 0.572912 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 14b804eb64288b3cb9e076d14a27aa80bf143e452bf87789d24b8450d404728c | 9,095 | [
-1
] |
9,096 | 20180303.lisp | azimut_shiny/examples/20180303.lisp | (in-package :shiny)
(defun mynow ()
;; Just some number that increases over time that we use
;; in a bunch of places
(/ (get-internal-real-time)
1000f0))
(defvar *gpu-verts-arr* nil)
(defvar *gpu-index-arr* nil)
(defvar *vert-stream* nil)
;; --------------------------------------------------
;;(defvar *cube-stream* nil)
(defvar *cam-pos* (v! 0 0 0))
(defvar *scott-tex* nil)
;; --------------------------------------------------
(defvar *samplers* (make-hash-table :test #'equal))
(defun load-tex (rel-path)
(or (gethash rel-path *samplers*)
(let* ((path (asdf:system-relative-pathname :somecepl rel-path))
(tex (load-image-to-texture path)))
(setf (gethash rel-path *samplers*)
(sample tex)))))
;; --------------------------------------------------
(defun-g vert ((vert :vec2))
(values (v! vert 0 1)
(+ (v2! .5) (* vert .5))))
(defun-g frag ((uv :vec2)
&uniform
(time :float)
(resolution :vec2)
(sam :sampler-2d)
(cam-pos :vec3))
;; 8 = width size
;; time ...mod does not matter...
;; .125 = 1/8
;; -1 ...flip vertically
;; /2 ... pick one row of the two
(let* ((frames 8)
(rows 2)
(time (* 15 time))
(mtime (floor (mod time frames)))
(vx (+ (* (* -1 mtime)
.125)
(/ (x uv)
frames)))
(vy (/ (* -1 (y uv))
rows))
;; (vx (* (cos time) vx))
;; (vy (* (cos time) vy))
;;; wibble
(color (texture sam
(v! vx
vy))))
color))
;; --------------------------------------------------
(defpipeline-g mario ()
:vertex (vert :vec2)
:fragment (frag :vec2))
(defun init ()
(unless *scott-tex*
(setf *scott-tex*
(load-tex "scottpilgrim_multiple.png")))
(when *gpu-verts-arr*
(free *gpu-verts-arr*))
(when *gpu-index-arr*
(free *gpu-index-arr*))
(when *vert-stream*
(free *vert-stream*))
(setf *gpu-verts-arr*
(make-gpu-array
(list (v! -1.0 1.0)
(v! -1.0 -1.0)
(v! 1.0 -1.0)
(v! 1.0 1.0))
:element-type :vec2))
(setf *gpu-index-arr*
(make-gpu-array
(list 0 1 2
0 2 3)))
(setf *vert-stream*
(make-buffer-stream *gpu-verts-arr*
:index-array *gpu-index-arr*)))
(defun draw! ()
(step-host)
(clear)
(setf (resolution (current-viewport))
(surface-resolution (current-surface)))
(map-g #'mario *vert-stream*
:time (mynow)
:resolution (surface-resolution (current-surface))
:sam *scott-tex*
:cam-pos *cam-pos*)
(swap))
(def-simple-main-loop runplay (:on-start #'init)
(draw!))
| 2,869 | Common Lisp | .lisp | 94 | 23.180851 | 70 | 0.469225 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 0c8e5534107998784d45fffb70832e05390159df7fa2c47538a9a8b9ca550f41 | 9,096 | [
-1
] |
9,097 | 20180304.lisp | azimut_shiny/examples/20180304.lisp | (in-package :shiny)
(defclass actor ()
((pos :initform (v! 0 0 0) :initarg :pos)
(rot :initform 0f0 :initarg :rot)
(scale :initform 1f0 :initarg :scale)
(visual :initarg :visual)))
(defvar *actors* nil)
(defun mynow ()
;; Just some number that increases over time that we use
;; in a bunch of places
(/ (get-internal-real-time)
1000f0))
(defvar *gpu-verts-arr* nil)
(defvar *gpu-index-arr* nil)
(defvar *vert-stream* nil)
;; --------------------------------------------------
;;(defvar *cube-stream* nil)
(defvar *cam-pos* (v! 0 0 0))
(defvar *blend* (make-blending-params))
;; --------------------------------------------------
(defvar *samplers* (make-hash-table :test #'equal))
(defun load-tex (rel-path)
(or (gethash rel-path *samplers*)
(let* ((path (asdf:system-relative-pathname :somecepl rel-path))
(tex (load-image-to-texture path)))
(setf (gethash rel-path *samplers*)
(sample tex)))))
;; --------------------------------------------------
(defun-g vert ((vert :vec2))
(values (v! (x vert) (y vert) 0 1)
(+ (v2! .5) (* vert .5))))
(defun-g frag ((uv :vec2)
&uniform
(scale :float)
(time :float)
(resolution :vec2)
(sam :sampler-2d)
(cam-pos :vec3))
;; 8 = width size
;; time ...mod does not matter...
;; .125 = 1/8
;; -1 ...flip vertically
;; /2 ... pick one row of the two
(let* (
(frames 8)
(rows 2)
(time (* 15 time))
(mtime (floor (mod time frames)))
(vx (+ (* (* -1 mtime)
.125)
(/ (x uv)
frames)))
(vy (/ (* -1 (y uv))
rows))
;; (vx (* (cos time) vx))
;; (vy (* (cos time) vy))
;;; wibble
(t-uv (v! vx vy))
(color (texture sam t-uv))
)
color))
;; --------------------------------------------------
(defpipeline-g mario ()
:vertex (vert :vec2)
:fragment (frag :vec2))
(defun init ()
(unless *actors*
(setf *actors*
(make-array 0 :element-type 'actor
:adjustable t
:fill-pointer 0))
(vector-push-extend (make-instance 'actor :visual (load-tex "scottpilgrim_multiple.png")) *actors*))
(when *gpu-verts-arr*
(free *gpu-verts-arr*))
(when *gpu-index-arr*
(free *gpu-index-arr*))
(when *vert-stream*
(free *vert-stream*))
(setf *gpu-verts-arr*
(make-gpu-array
(list (v! -1.0 1.0)
(v! -1.0 -1.0)
(v! 1.0 -1.0)
(v! 1.0 1.0))
:element-type :vec2))
(setf *gpu-index-arr*
(make-gpu-array
(list 0 1 2
0 2 3)))
(setf *vert-stream*
(make-buffer-stream *gpu-verts-arr*
:index-array *gpu-index-arr*)))
(defun draw! ()
(step-host)
(clear)
(setf (resolution (current-viewport))
(surface-resolution (current-surface)))
(with-setf* ((depth-test-function) nil)
(with-blending *blend*
(loop :for x :across *actors* :do
(map-g #'mario *vert-stream*
:time (mynow)
:resolution (surface-resolution (current-surface))
:sam (slot-value x 'visual)
:scale (slot-value x 'scale)
:cam-pos *cam-pos*))))
(swap))
(def-simple-main-loop runplay (:on-start #'init)
(draw!))
| 3,484 | Common Lisp | .lisp | 109 | 24.449541 | 104 | 0.488088 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | feb59ffb1dfa72e0619bc77644c6f79a451b18bd5a366c7ca8a873a7834a9d96 | 9,097 | [
-1
] |
9,098 | simplest.lisp | azimut_shiny/examples/simplest.lisp | (in-package :shiny)
(defun-g vert ((vert :vec2))
(v! vert 0 1))
(defun-g frag ()
(v! 1 0 0 0))
(defpipeline-g mario ()
:vertex (vert :vec2)
:fragment (frag))
(defun reset ())
(defun game-step ()
(clear)
(map-g #'mario (get-quad-stream-v2))
(swap))
(def-simple-main-loop runplay (:on-start #'reset)
(game-step))
| 335 | Common Lisp | .lisp | 15 | 19.866667 | 49 | 0.627389 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 944b62e63c1970ab5163df3d4084724849564c66808754cefb40d4265e73f7e2 | 9,098 | [
-1
] |
9,099 | cv-cepl.lisp | azimut_shiny/examples/cv-cepl.lisp | (in-package :shiny)
(defvar *bs* NIL)
(defvar *capture* (cv:create-file-capture "/home/sendai/testfield/hila.mp4"))
(defvar *frame* (cv:query-frame *capture*))
(defvar *data* (cv:ipl-data *frame*))
(defvar *props* (get-props *capture*))
(defparameter *c-arr* (make-c-array-from-pointer '(426 240) :char *data*))
(defun-g frag ((uv :vec2))
(v! 1 0 0 1))
(defpipeline-g pipe (:points)
:fragment (frag :vec2))
(defun initialize ()
(unless *bs*
(setf *bs* (make-buffer-stream NIL :primitive :points))))
(defun draw! ()
(let ((res (surface-resolution (current-surface))))
(setf (viewport-resolution (current-viewport)) res)
(as-frame
(map-g #'pipe *bs*))))
(def-simple-main-loop runplay (:on-start #'initialize)
(draw!))
| 752 | Common Lisp | .lisp | 21 | 33.095238 | 77 | 0.669433 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | be1687775b21b3896fb55a7b9f8d178ebc199e2a14d787440e929d3a48fb3a6b | 9,099 | [
-1
] |
9,100 | incudinepiano.lisp | azimut_shiny/examples/incudinepiano.lisp | (in-package :shiny)
;(sort (loop for x in (directory (pathname "/home/sendai/Downloads/samples/pianosample/SalamanderGrandPianoV2_44.1khz16bit/44.1khz16bit/*v10*.wav")) collect (note-name-to-midi-number (uiop:unix-namestring x))) #'<)
(defvar *pianosamples* nil)
(defvar env1 (make-envelope '(0 1 0) '(.2 .8)))
(defvar env2 (make-perc .01 .4))
(setf (bpm *tempo*) 120)
;(bplay (aref *pianosamples* 57) 1 0 nil :id 1)
;(loop for i from 1 to 10 do (sleep 1) (a (aref *pianosamples* (nth (random 3) '(54 57 60))) :id 1))
;; ---------------------------
(defun loadpianosamples ()
(unless *pianosamples*
(setf *pianosamples* (make-array 122 :initial-element nil)))
(loop :for x :in
(directory (pathname "~/Downloads/samples/pianosample/SalamanderGrandPianoV2_44.1khz16bit/44.1khz16bit/*v10*.wav"))
:collect
(let* ((filename (uiop:unix-namestring x))
(note (note-name-to-midi-number filename)))
(setf (aref *pianosamples* note) (buffer-load filename)))))
(loadpianosamples)
;; ---------------------------
(dsp! bplay ((buf buffer) rate start-pos (loop-p boolean))
(foreach-channel
(cout (buffer-play buf rate start-pos loop-p #'stop))))
(dsp! a ((buf buffer) atk rel amp)
(:defaults 0 .01 .4 1.)
(foreach-channel
(cout (* amp
(envelope (make-local-perc atk rel) 1 1 #'stop)
(cos (* pi (- (phasor .9 0) 0.5d0)))
(buffer-play buf 1 0 nil #'stop)))))
;; ---------------------------
(defun seq-test-inf (index)
(dsp-seq (a (aref *pianosamples* index))
(a (aref *pianosamples* (+ 3 index)))
(a (aref *pianosamples* (+ 12 index)))
(seq-test-inf index)))
; trying "markov chains" from extempore demo
(defun seq-test (root)
(let* ((newroot (random-list (cdr (assoc root '((60 57 54)
(57 60 54)
(54 42 60)
(42 60 57)))))))
(dsp-seq (a (aref *pianosamples* root) .01 .4 :id 1)
(a (aref *pianosamples* (- root 12)) .01 .4 :id 2)
(a (aref *pianosamples* (+ 12 root)) .01 .4 1.5 :id 3)
(seq-test newroot))))
(defun seq-test (rep index)
(when (plusp rep)
(dsp-seq (bplay (aref *pianosamples* index) 1 0 nil)
(bplay (aref *pianosamples* (+ (* 3 5) index)) 1 0 nil)
(bplay (aref *pianosamples* (- (* 3 5) index)) 1 0 nil)
(seq-test (1- rep) index))))
(defun seq-test (rep index)
(let* ((root index)
(newroot (- index 3))))
(when (plusp rep)
(dsp-seq (bplay (aref *pianosamples* index) 1 0 nil)
(bplay (aref *pianosamples* (+ (* 3 5) index)) 1 0 nil)
(bplay (aref *pianosamples* (- (* 3 5) index)) 1 0 nil)
(seq-test (1- rep) index))))
(defun phr1 (time)
(at time #'seq-test 8 200 .3 .5)
(at (+ time #[2 b]) #'seq-test 6 400 .3 .4)
(at (+ time #[4 b]) #'seq-test 4 600 .3 .6))
(defun phr1 (time)
(at time #'seq-test 8 30)
(at (+ time #[2 b]) #'seq-test 6 45)
;(at (+ time #[4 b]) #'seq-test 4 45)
)
(defun phr1-inf (time)
(at time #'seq-test-inf 30)
(at (+ time #[2 b]) #'seq-test-inf 45)
;(at (+ time #[4 b]) #'seq-test 4 45)
)
;; ---------------------------
;; trying "markov chains" from extempore demo
(defun seq-test (root)
(let* ((newroot (random-list (cdr (assoc root '((60 57 54)
(57 60 54)
(54 42 60)
(42 60 57)))))))
(dsp-seq (a (aref *pianosamples* root) .01 .4 :id 1)
(a (aref *pianosamples* (- root 12)) .01 .4 :id 2)
(a (aref *pianosamples* (+ 12 root)) .01 .4 1.5 :id 3)
(seq-test newroot))))
;; ---------------------------
;; Feeding a beat
(defun beatme (root)
(a (aref *pianosamples* root) :id 1)
(at (+ (now) #[2 b]) #'beatme 60))
;; Feeding a list of beats / fmsynth.xtm
;; (beatme '(60 63 63 66))
;; (beatme '(60 63 63 66 72 66 84 78 66 69))
(defun beatme (rootl)
(a (aref *pianosamples* (car rootl)) :id 1)
(at (+ (now) #[1/2 b]) #'beatme (rotate rootl 1)))
;; Feeding beats with varying amp
(defun beatme (rootl)
(a (aref *pianosamples* (car rootl)) .01 .4 (cosr 1.5 .2 1) :id 1)
(at (+ (now) #[1/2 b]) #'beatme (rotate rootl 1)))
| 4,419 | Common Lisp | .lisp | 100 | 36.51 | 214 | 0.530384 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | e9bfb019155687ce8b8b8940188d1d4b44bb40c23bb16a9a3a2dab9d8581dbb2 | 9,100 | [
-1
] |
9,101 | 20180718.lisp | azimut_shiny/examples/20180718.lisp | (in-package :shiny)
(defparameter *step* (make-stepper (seconds .05) (seconds 1)))
(defparameter *trigger* (make-trigger))
(defvar *buf* (make-buffer 512))
(defvar *light* (v! .2 .2 .2))
(defvar *mar* nil)
(defvar *ubo* nil)
(dsp! monitor-master ((buf buffer))
(buffer-write
buf
(counter 0 511 :loop-p t)
(audio-out 0)))
;; (monitor-master *buf* :id 100)
;;--------------------------------------------------
(defstruct-g (music :layout :std-140)
(samples (:double 512)))
(defun-g g-rand ((x :float))
(fract (* (sin x)
10000f0)))
(defun-g cyn ((x :float))
(+ .5 (* .5 (cos x))))
(defun-g syn ((x :float))
(+ .5 (* .5 (sin x))))
(defun-g g-random ((st :vec2))
(fract (* (sin (dot st
(v! 12.9898 ;; moves noise
78.233
)))
43758.543123
)))
(defun-g frag
((uv :vec2) &uniform (sound music :ubo) (time :float)
(rms :float))
(with-slots (samples) sound
(let* (;;(wide (+ 100 (* 100 (+ .5 (* .5 (sin time))))))
(wide 250)
(wave (float (aref samples (int (ceil (* wide (x uv)))))))
(wave (- 1 (smoothstep 0f0 .01 (abs (- wave (- (y uv) .5))))))
(wave (v3! wave))
;; (uv (v! (length (- (x uv) .5))
;; (y uv)))
;; !
;; (color (mix c1 c2 (+ (- rms) 1 (y uv))))
;; (color (+ color wave))
)
wave)))
(defclass actor ()
((pos :initarg :pos :initform (v! 0 0 0))
(rot :initarg :rot :initform (v! 0 0 0))
(buf :initarg :buf :initform (box))))
(defvar *actors* nil)
(defun-g vert
((vert g-pnt) &uniform
(time :float) (sound music :ubo) (model-world :mat4))
(let* ((pos (pos vert))
(pos (* (v! pos 1) model-world)))
(values pos
(v! (+ .5 (* .5 (s~ pos :xy)))))))
(bbuffer-load "/home/sendai/music/Furi.wav")
(bbplay "Furi.wav" :id 100 :loop-p t)
(incudine:free (node 100))
(defpipeline-g pipe ()
:vertex (vert g-pnt)
:fragment (frag :vec2))
(defun initialize ()
(setf (clear-color) (v! 1 1 1 1))
(setf *actors* nil)
(push (make-instance 'actor
:buf (box .5)
:pos (v! .2 .2 .2))
*actors*)
(unless *ubo*
(setf *mar* (make-c-array nil :dimensions 1 :element-type 'music))
(setf *ubo* (make-ubo *mar*))))
(defgeneric update (actor))
(defmethod update ((actor actor))
(with-slots (pos rot) actor
(setf pos (v! 0 0 .2))
(setf rot (v! 0 (sin (get-universal-time)) 0))))
(defun draw! ()
(when (funcall *step*)
;; NOTE: ?
(with-gpu-array-as-c-array (m (ubo-data *ubo*) :access-type :write-only)
(incudine.external:foreign-copy-samples
(c-array-pointer m)
(buffer-data *buf*)
512)))
(let ((res (surface-resolution (current-surface))))
(setf (viewport-resolution (current-viewport))
res)
(as-frame
(loop :for a :in *actors*
:do
;; (update a)
(with-slots (pos rot buf) a
(map-g #'pipe buf
;; :rms (float (funcall *trigger* 'bleed))
:time (* .001 (get-internal-real-time))
:sound *ubo*
:model-world (m4:* (m4:translation pos)
(q:to-mat4 rot))
))))))
(def-simple-main-loop runplay (:on-start #'initialize)
(draw!))
| 3,465 | Common Lisp | .lisp | 104 | 26.288462 | 76 | 0.502249 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | d83651b46765e90bb8c61d0ef2640c3c343fbb622f1d9ebaa82bb7f815742624 | 9,101 | [
-1
] |
9,102 | camera.lisp | azimut_shiny/examples/flower/camera.lisp | (in-package :shiny)
(defclass camera ()
((pos :initarg :pos :accessor pos)
(rot :initarg :rot :accessor rot)
(near :initarg :near :accessor near)
(far :initarg :far :accessor far)
(frame-size :initarg :frame-size
:accessor frame-size)
(buf :initarg :buf))
(:default-initargs
:pos (v! 0 0 0)
:rot (q:identity)
:near .1
:far 400f0
:frame-size nil
:buf (box)))
(defclass orth (camera) ())
(defclass pers (camera)
((fov :initarg :fov :accessor fov))
(:default-initargs
:fov 60f0))
(defparameter *camera* (make-instance 'pers))
(defparameter *camera1* (make-instance 'orth))
(defparameter *camera-cubemap*
(make-instance 'pers :fov 90f0))
(defparameter *currentcamera* *camera*)
(defun world->view (camera)
(m4:* (m4:translation (v3:negate (pos camera)))
(q:to-mat4 (q:inverse (rot camera)))))
(defgeneric projection (camera)
(:method ((camera pers))
(let ((fs (or (frame-size camera)
(viewport-resolution (current-viewport)))))
(rtg-math.projection:perspective-v2
fs
(near camera)
(far camera)
(fov camera))))
(:method ((camera orth))
(let ((fs (or (frame-size camera)
(viewport-resolution (current-viewport)))))
(rtg-math.projection:orthographic
(x fs)
(y fs)
(near camera)
(far camera)))))
(defmethod update ((camera orth))
(setf (pos camera) (v! 0 0 0))
(setf (frame-size camera) (v2! 30))
;; (setf (rot camera) (v! 0 0 0))
(setf (rot camera)
;; TOP
(q:from-axis-angle (v! 1 0 0)
(radians -90))
;; FRONT
;; (q:from-axis-angle (v! 1 0 0)
;; (radians -45))
))
(defmethod update ((camera pers))
(let ((time (mynow)))
(with-slots (pos rot) camera
;;(setf rot (q:identity))
;;(setf pos (v! 0 0 0))
(setf rot (q:*
(q:from-axis-angle (v! 1 0 0)
(radians -10))
;;(q:identity)
(q:from-axis-angle (v! 1 0 1)
(radians (* 10
(sin (* .1 time)))))
))
;; (setf rot (q:from-axis-angle
;; (v! 0 1 0)
;; (radians (* 90 0))))
;; (setf pos (v! (+ 0 (* 0 (cos (* .5 time))))
;; (+ 0 (* .1 (sin (* .5 time))))
;; (+ 0 (* 1 (cos (* .5 time))))))
;;(setf rot (q:look-at (v! 0 1 0) pos (v! 0 -1 0)))
)))
| 2,595 | Common Lisp | .lisp | 79 | 25.063291 | 68 | 0.5 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 3fbd2ac306126199713ad3627d380f36dc1fea50c1a37358b16dc96c9b84711e | 9,102 | [
-1
] |
9,103 | main.lisp | azimut_shiny/examples/flower/main.lisp | (in-package :shiny)
(defvar *fbo* nil)
(defvar *sam* nil)
(defvar *samd* nil)
(defvar *bs* nil)
;; Cubemap with clouds
(defvar *t-cubemap* nil)
(defvar *s-cubemap* nil)
;; Cubemap for the luminance
(defparameter *saved* nil)
(defvar *t-cubemap-live* nil)
(defvar *s-cubemap-live* nil)
;; Cubemap to store the mix between the clouds and own floor geometry
;; ???
;; Prefilter cubemap - for specular
(defparameter *prefilter* nil)
(defvar *t-cubemap-prefilter* nil)
(defvar *s-cubemap-prefilter* nil)
(defparameter *brdf* nil)
(defvar *f-brdf* nil)
(defvar *t-brdf* nil)
(defvar *s-brdf* nil)
(defparameter *dimensions* '(512 512))
(defun free-cubes ()
;;(setf *saved* NIL)
(when *t-cubemap-prefilter*
(free *t-cubemap-prefilter*)
(setf *t-cubemap-prefilter* NIL)
;; (setf *prefilter* NIL)
)
(when *t-cubemap*
(free *t-cubemap*)
(setf *t-cubemap* NIL))
(when *t-cubemap-live*
(free *t-cubemap-live*)
(setf *t-cubemap-live* NIL)
;; (setf *saved* NIL)
)
)
(defun initialize ()
(unless *t-cubemap*
(setf *t-cubemap*
(make-cubemap-tex
"static/ThickCloudsWater/left.png"
"static/ThickCloudsWater/right.png"
"static/ThickCloudsWater/up.png"
"static/ThickCloudsWater/down.png"
"static/ThickCloudsWater/front.png"
"static/ThickCloudsWater/back.png"))
(setf *s-cubemap*
(cepl:sample *t-cubemap*
:wrap :clamp-to-edge
:magnify-filter :linear)))
;;--------------------------------------------------
;; IBL - Diffuse ambient
(unless *t-cubemap-live*
(setf *t-cubemap-live*
(make-texture
nil
:element-type :rgb16f
:dimensions '(32 32)
:cubes t))
(setf *s-cubemap-live*
(cepl:sample *t-cubemap-live*
:minify-filter :linear
:magnify-filter :linear
:wrap :clamp-to-edge)))
;;--------------------------------------------------
;; IBL - Specular ambient
;; 1) prefilter
(unless *t-cubemap-prefilter*
(setf *t-cubemap-prefilter*
(make-texture
nil
:element-type :rgb16f
:dimensions '(128 128)
:mipmap 5
:cubes t))
(setf *s-cubemap-prefilter*
(cepl:sample *t-cubemap-prefilter*
:magnify-filter :linear
:wrap :clamp-to-edge)))
;; 2) BRDF
(unless *f-brdf*
(setf *f-brdf*
(make-fbo
(list 0 :element-type :rg16f :dimensions '(512 512))))
(setf *t-brdf* (attachment-tex *f-brdf* 0))
(setf *s-brdf*
(cepl:sample *t-brdf*
:wrap :clamp-to-edge
:magnify-filter :linear
:minify-filter :linear)))
;;--------------------------------------------------
;; Buffer stream for single stage pipelines
(unless *bs*
(setf *bs* (make-buffer-stream nil :primitive :points)))
;;--------------------------------------------------
;; HDR fbo(s)
(when *fbo* (free *fbo*))
(setf *fbo*
(make-fbo
(list 0 :element-type :rgb16f :dimensions *dimensions*)
(list :d :dimensions *dimensions*)))
(setf *sam* (cepl:sample (attachment-tex *fbo* 0)
:wrap :clamp-to-edge))
(setf *samd* (cepl:sample (attachment-tex *fbo* :d)
:wrap :clamp-to-edge))
;;--------------------------------------------------
(setf (clear-color) (v! 0 0 0 1))
;;--------------------------------------------------
(setf *actors* nil)
(make-pbr (v! 0 -2 -10))
(make-cubemap)
;;(make-light-cubemap)
(make-pbr-simple (v! 0 0 -10))
NIL)
(defun draw! ()
(let* ((res (surface-resolution (current-surface)))
;;(time (mynow))
)
(setf (resolution (current-viewport)) res)
;;(setf (resolution (current-viewport)) (v! *dimensions*))
(update *currentcamera*)
(update-all-the-things *actors*)
(unless *prefilter*
(setf *prefilter* T)
(render-to-prefilter-cubemap *camera-cubemap*
*t-cubemap*
*s-cubemap*
*t-cubemap-prefilter*))
(unless *brdf*
(setf *brdf* T)
(setf (resolution (current-viewport)) (v! 512 512))
(map-g-into *f-brdf* #'brdf-pipe *bs*))
(unless *saved*
(render-to-light-cubemap *camera-cubemap*
*t-cubemap*
*s-cubemap*
*t-cubemap-live*)
(setf *saved* T))
(with-fbo-bound (*fbo*)
(clear-fbo *fbo*)
(loop :for actor :in *actors* :do
(draw actor *currentcamera*)))
(as-frame
(with-setf* ((depth-mask) nil
(cull-face) nil
(clear-color) (v! 0 0 0 1))
(map-g #'generic-2d-pipe *bs*
:sam *sam*
:samd *samd*)))))
(def-simple-main-loop runplay (:on-start #'initialize)
(draw!))
| 5,150 | Common Lisp | .lisp | 154 | 24.88961 | 69 | 0.510793 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 28d9f82fc3535aee7e60f40a01a93edadafb3e6b07147d3ccd3926439cd09c96 | 9,103 | [
-1
] |
9,104 | draw.lisp | azimut_shiny/examples/flower/draw.lisp | (in-package :shiny)
(defparameter *pointlight-pos* (v! 0 0 0))
(defun render-all-the-things (actor camera)
(update actor)
(draw actor camera))
(defgeneric draw (actor camera))
(defmethod draw (actor camera))
(defmethod draw ((actor box) camera)
(with-slots (buf scale) actor
(map-g #'generic-pipe buf
:scale scale
:color (v! .001 .001 .001)
:model-world (model->world actor)
:world-view (world->view camera)
:view-clip (projection camera))))
(defmethod draw ((actor pbr) camera)
(with-slots (buf albedo normal height roughness scale ao) actor
(map-g #'pbr-pipe buf
:uv-repeat 8f0
:uv-speed .1f0
:scale scale
:albedo albedo
:ao-map ao
:normal-map normal
:height-map height
:rough-map roughness
:time (mynow)
:color-mult 1f0
:cam-pos (pos camera)
:light-pos *light-pos*
:brdf-lut *s-brdf*
:prefilter-map *s-cubemap-prefilter*
:model-world (model->world actor)
:world-view (world->view camera)
:view-clip (projection camera)
:irradiance-map *s-cubemap-live*)))
(defmethod draw ((actor pbr-simple) camera)
(with-slots (buf scale color) actor
(map-g #'pbr-simple-pipe buf
:scale *scale*
:color *color*
:time (mynow)
:color-mult 1f0
:cam-pos (pos camera)
:brdf-lut *s-brdf*
:prefilter-map *s-cubemap-prefilter*
:irradiance-map *s-cubemap-live*
:light-pos *light-pos*
:model-world (model->world actor)
:world-view (world->view camera)
:view-clip (projection camera))))
(defmethod draw ((actor cubemap) camera)
(with-slots (buf) actor
(with-setf* ((cull-face) :front
(depth-test-function) #'<=)
(map-g #'cubemap-pipe buf
:tex *s-cubemap*
:mod-clip
(m4:* (projection camera)
(world->view camera))))))
(defmethod draw ((actor light-cubemap) camera)
(with-slots (buf) actor
(with-setf* ((cull-face) :front
(depth-test-function) #'<=)
(map-g #'cubemap-pipe buf
:tex *s-cubemap*
;;:tex *s-cubemap-live*
;;:tex *s-cubemap-prefilter*
:mod-clip
(m4:* (projection camera)
(world->view camera))))))
| 2,510 | Common Lisp | .lisp | 71 | 25.535211 | 65 | 0.550391 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | c7496b9c3a759edb402568bbc30d1b35d3bf821f51fe04ff0f01974f278841ee | 9,104 | [
-1
] |
9,105 | actors.lisp | azimut_shiny/examples/flower/actors.lisp | (in-package :shiny)
(defvar *actors* nil)
(defparameter *light-pos* (v! -60 100 -50)
;;(v! 0 10 -40)
)
(defparameter *light-color* (v! .9 .9 .9))
(defparameter *exposure* .5f0)
(defun update-all-the-things (l)
(declare (list l))
(loop :for actor :in l :do
(update actor)))
(defun model->world (actor)
(with-slots (pos rot) actor
(m4:* (m4:translation pos)
(q:to-mat4 rot))))
(defun delete-actor-name (actor-name)
(declare (symbol actor-name))
(setf *actors*
(delete-if
(lambda (x) (eq actor-name (slot-value x 'name)))
*actors*))
NIL)
(defun delete-actor-class (class-name)
(declare (string class-name))
(setf *actors*
(delete-if
(lambda (x) (string= class-name (class-name (class-of x))))
*actors*))
NIL)
(defmethod sync (x) (+ .5 (* .5 (sin x))))
(defmethod cync (x) (+ .5 (* .5 (cos x))))
;;--------------------------------------------------
(defclass actor ()
((name :initarg :name :initform (gensym))
(pos :initarg :pos :initform (v! 0 0 0) :accessor pos)
(rot :initarg :rot :initform (q:identity) :accessor rot)
(buf :initarg :buf :initform (box))
(color :initarg :color :initform (v! 1 0 0))
(scale :initarg :scale :initform 1f0)))
(defclass cubemap (actor) ())
(defun make-cubemap ()
(let ((obj (make-instance 'cubemap)))
(push obj *actors*)
obj))
(defclass light-cubemap (actor) ())
(defun make-light-cubemap ()
(let ((obj (make-instance 'light-cubemap)))
(push obj *actors*)
obj))
(defclass pbr-simple (actor) ())
(defclass pbr (actor)
((albedo :initarg :albedo)
(ao :initarg :ao)
(height :initarg :height)
(normal :initarg :normal)
(roughness :initarg :roughness))
(:default-initargs
:albedo (get-tex "static/16.Plasterwall02-1k/plasterwall02_albedo.jpg" nil t :rgb8)
:ao (get-tex "static/16.Plasterwall02-1k/plasterwall02_ao.jpg" nil t :r8)
:height (get-tex "static/16.Plasterwall02-1k/plasterwall02_height.jpg" nil t :r8)
:normal (get-tex "static/16.Plasterwall02-1k/plasterwall02_normal.jpg" nil t :rgb8)
:roughness (get-tex "static/16.Plasterwall02-1k/plasterwall02_roughness.jpg" nil t :r8)))
(defclass box (actor)
((buf :initform (box 2 2 2))))
(defun make-pbr (&optional (pos (v! 0 0 0)) (rot (q:identity)))
(let ((obj
(make-instance
'pbr
:buf (lattice 100 100 2 2 t)
:pos pos
:rot rot)))
(push obj *actors*)
obj))
(defun make-pbr-simple (&optional (pos (v! 0 0 0)))
(let ((obj
(make-instance
'pbr-simple
:buf (sphere)
:pos pos)))
(push obj *actors*)
obj))
(defun make-box (&optional (pos (v! 0 0 0)) (scale 1f0))
(let ((obj (make-instance 'box
:pos pos
:scale scale
:buf (box) ;;(box 3 10 1)
)))
(appendf *actors* (list obj))
obj))
(defgeneric update (actor))
(defmethod update (actor))
(defmethod update ((actor pbr)))
(defmethod update ((actor pbr-simple))
(with-slots (pos rot color) actor
(setf color (v! .01 .01 .01))
;; (setf rot (q:from-axis-angle
;; (v! 1 .2 .8)
;; (radians (mod (* 10 (mynow)) 360))))
;; (setf pos (v! 0 0 (+ -10 (- (* 5 (sin (mynow)))))))
))
(defmethod update ((actor box)))
| 3,406 | Common Lisp | .lisp | 101 | 28.326733 | 92 | 0.580037 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | c7005c0dceca4ac15ba2a91bb5a7bc4d324d6da9a836234c03f07343a7d2dd91 | 9,105 | [
-1
] |
9,106 | cubemap.lisp | azimut_shiny/examples/flower/cubemap.lisp | (in-package #:shiny)
;; Reference: Cubemap generation mostly from
;; https://learnopengl.com/PBR/IBL/Diffuse-irradiance
(defparameter *saved* nil)
(defvar *cubemap-sides* '("left" "right" "bottom" "front" "top" "back"))
(defvar *cubemap-rotations*
(list
(list (v! 0 -1 0) (v! 0 0 0) (v! 1 0 0))
(list (v! 0 -1 0) (v! 0 0 0) (v! -1 0 0))
(list (v! 0 0 -1) (v! 0 0 0) (v! 0 -1 0))
(list (v! 0 0 1) (v! 0 0 0) (v! 0 1 0))
(list (v! 0 -1 0) (v! 0 0 0) (v! 0 0 1))
(list (v! 0 -1 0) (v! 0 0 0) (v! 0 0 -1))))
;;--------------------------------------------------
;; GI - IBL - Specular prefilter cubemap
;; https://learnopengl.com/PBR/IBL/Specular-IBL
(defgeneric render-to-prefilter-cubemap (camera
src-cubemap
src-cubemap-sample
dst-cubemap))
(defmethod render-to-prefilter-cubemap ((camera pers)
src-cubemap
src-cubemap-sample
dst-cubemap)
(let ((dst-dimensions (dimensions dst-cubemap))
(src-dimensions (dimensions src-cubemap)))
(assert (= 5 (texture-mipmap-levels dst-cubemap)))
(assert (texture-cubes-p dst-cubemap))
(assert (texture-cubes-p src-cubemap))
(assert (eq :RGB16F (texture-element-type dst-cubemap)))
(assert (= (car dst-dimensions) (cadr dst-dimensions)))
(setf (fov camera) 90f0)
(dotimes (mip 5)
(let* ((mip-width (floor (* 128 (expt .5 mip))))
(mip-height mip-width)
(dimensions (list mip-width mip-height))
(roughness (coerce (/ mip (- 5 1)) 'single-float)))
(setf (resolution (current-viewport)) (v! dimensions))
(with-free*
((fbo
(make-fbo
(list 0 :dimensions dimensions :element-type :rgb16f)
(list :d :dimensions dimensions))))
(loop
:for side :in *cubemap-sides*
:for rotation :in *cubemap-rotations*
:for face :from 0
:finally (setf *saved* T)
:do
;; Rotate camera
(destructuring-bind (up from to) rotation
(setf (rot camera) (q:look-at up from to)))
;; Switch FBO texture for one of the cubemap
(setf (attachment fbo 0)
(texref dst-cubemap :cube-face face :mipmap-level mip))
(with-setf* ((cull-face) :front
(depth-test-function) #'<=)
(with-fbo-bound (fbo)
(clear-fbo fbo)
(map-g #'prefilter-pipe (box)
:roughness roughness
:environment-map src-cubemap-sample
:mod-clip (m4:* (projection camera)
(world->view camera)))))))))))
;;--------------------------------------------------
(defgeneric render-to-light-cubemap (camera
src-cubemap
src-cubemap-sample
dst-cubemap))
(defmethod render-to-light-cubemap ((camera pers)
src-cubemap
src-cubemap-sample
dst-cubemap)
(let ((dst-dimensions (dimensions dst-cubemap))
(src-dimensions (dimensions src-cubemap)))
;; (assert (eq :RGB16F (element-type (texref src-cubemap :cube-face 0)))
;; (src-cubemap)
;; "Provided src-cubemap must be HDR/RGB16F")
(assert (eq :RGB16F (element-type (texref dst-cubemap :cube-face 0)))
(dst-cubemap)
"Provided dst-cubemap must be HDR/RGB16F")
(assert (= (car src-dimensions) (cadr src-dimensions))
(src-dimensions)
"src DIMENSIONS should have an aspect ratio of 1:1")
(assert (= (car dst-dimensions) (cadr dst-dimensions))
(dst-dimensions)
"dst DIMENSIONS should have an aspect ratio of 1:1")
(setf (resolution (current-viewport)) (v! dst-dimensions))
(setf (fov camera) 90f0)
(with-free*
((fbo
(make-fbo
(list 0 :dimensions dst-dimensions :element-type :rgb16f)
(list :d :dimensions dst-dimensions))))
(loop
:for side :in *cubemap-sides*
:for rotation :in *cubemap-rotations*
:for i :from 0
:finally (setf *saved* T)
:do
;; Rotate camera
(destructuring-bind (up from to) rotation
(setf (rot camera) (q:look-at up from to)))
;; Switch FBO texture for one of the cubemap
(setf (attachment fbo 0)
(texref dst-cubemap :cube-face i))
(with-setf* ((cull-face) :front
(depth-test-function) #'<=)
(with-fbo-bound (fbo)
(clear-fbo fbo)
(map-g #'cube-down-pipe (box)
:tex src-cubemap-sample
:mod-clip (m4:* (projection camera)
(world->view camera)))))))))
;;--------------------------------------------------
(defgeneric render-to-cubemap (camera dimensions cubemap))
(defmethod render-to-cubemap ((camera pers) dimensions cubemap)
"Fills the provided CUBEMAP texture with proper images"
(assert (eq :RGB16F (element-type (texref cubemap :cube-face 0)))
(cubemap)
"Provided cubemap must be HDR/RGB16F")
(assert (and (list dimensions) (= 2 (length dimensions)))
(dimensions)
"DIMENSIONS should be a list of 2 numbers")
(assert (= (car dimensions) (cadr dimensions))
(dimensions)
"DIMENSIONS should have an aspect ratio of 1:1")
(setf (resolution (current-viewport)) (v! dimensions))
(setf (fov camera) 90f0)
(with-free*
((external-fbo
(make-fbo
(list 0 :dimensions dimensions :element-type :rgb16f)
(list :d :dimensions dimensions)))
(external-sample (cepl:sample (attachment-tex external-fbo 0)))
(bs (make-buffer-stream nil :primitive :points))
(fbo
(make-fbo
(list 0 :dimensions dimensions :element-type :rgb16f)))
(pipeline
(pipeline-g (:points)
:fragment
(lambda-g ((uv :vec2) &uniform (sam :sampler-2d))
(let* ((color (s~ (texture sam uv) :xyz))
;;(color (v! (x color) .1 (z color)))
)
(v! (pow color
(vec3 (/ 1f0 2.2)))
1))))))
(loop
:for side :in *cubemap-sides*
:for rotation :in *cubemap-rotations*
:for i :from 0
:finally (setf *saved* T)
:do
;; Rotate camera
(destructuring-bind (up from to) rotation
(setf (rot camera)
(q:look-at up from to)))
;; Normal draw - preferably a 16bit fbo to avoid dithering
(with-fbo-bound (external-fbo)
(clear-fbo external-fbo)
(loop :for actor :in *actors* :do
(draw actor camera)))
;; Switch FBO texture for one of the cubemap
(setf (attachment fbo 0) (texref cubemap :cube-face i))
;; Final draw to LDR (? the colors
(with-fbo-bound (fbo)
(clear-fbo fbo)
(map-g pipeline bs
:sam external-sample)))))
;;--------------------------------------------------
(defgeneric save-to-cubemap (camera dimensions))
(defmethod save-to-cubemap ((camera pers) dimensions)
"Save the current scene in *ACTORS* into 6 bmp images
Sadly the images are saved in a 8bit LDR image"
(assert (and (list dimensions) (= 2 (length dimensions)))
(dimensions)
"DIMENSIONS should be a list of 2 numbers")
(assert (= (car dimensions) (cadr dimensions))
(dimensions)
"DIMENSIONS should have an aspect ratio of 1:1")
(setf (resolution (current-viewport)) (v! dimensions))
(setf (fov camera) 90f0)
(with-free*
((external-fbo
(make-fbo
(list 0 :dimensions dimensions :element-type :rgb16f)
(list :d :dimensions dimensions)))
(external-sample (cepl:sample (attachment-tex external-fbo 0)))
(bs (make-buffer-stream nil :primitive :points))
(fbo (make-fbo (list 0 :dimensions dimensions)))
(pipeline
(pipeline-g (:points)
:fragment
(lambda-g ((uv :vec2) &uniform (sam :sampler-2d))
(v! (pow (s~ (texture sam uv) :xyz)
(vec3 (/ 1f0 2.2)))
1)))))
(loop
:for side :in *cubemap-sides*
:for rotation :in *cubemap-rotations*
:finally (setf *saved* T)
:do
;; Rotate camera
(destructuring-bind (up from to) rotation
(setf (rot camera)
(q:look-at up from to)))
;; Normal draw - preferably a 16bit fbo to avoid dithering
(with-fbo-bound (external-fbo)
(clear-fbo external-fbo)
(loop :for actor :in *actors* :do
(draw actor camera)))
;; Final draw to LDR (? the colors
(with-fbo-bound (fbo)
(clear-fbo fbo)
(map-g pipeline bs
:sam external-sample))
;; Read from our created fbo texture
(dirt:save-as-image
(attachment-tex fbo 0)
(asdf:system-relative-pathname
:shiny
(concatenate 'string "static/cubemap_" side ".dds"))))))
| 9,668 | Common Lisp | .lisp | 224 | 31.366071 | 76 | 0.522987 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | e5afe7edafd0b5fc5a0a2ce5dfed067bc877dc9d84700d9dbde4923fc6198851 | 9,106 | [
-1
] |
9,107 | render.lisp | azimut_shiny/examples/flower/render.lisp | (in-package :shiny)
(defparameter *exposure* 1f0)
(defvar *scale* 1f0)
(defvar *color* (v! .3 .3 .3))
(defvar *rough* 1f0)
(defvar *pointlight-pos* (v! 0 0 0))
;;--------------------------------------------------
;; 3D - g-pnt with tangent info in tb-data AND textures
(defun-g vert-with-tbdata
((vert g-pnt) (tb tb-data)
&uniform
(model-world :mat4)
(world-view :mat4)
(view-clip :mat4)
(scale :float)
;; Parallax vars
(light-pos :vec3)
(cam-pos :vec3))
(let* ((pos (* scale (pos vert)))
(norm (norm vert))
(uv (treat-uvs (tex vert)))
(norm (* (m4:to-mat3 model-world) norm))
(world-pos (* model-world (v! pos 1)))
(view-pos (* world-view world-pos))
(clip-pos (* view-clip view-pos))
(t0 (normalize
(s~ (* model-world (v! (tb-data-tangent tb) 0))
:xyz)))
(n0 (normalize
(s~ (* model-world (v! norm 0))
:xyz)))
(t0 (normalize (- t0 (* (dot t0 n0) n0))))
(b0 (cross n0 t0))
(tbn (mat3 t0 b0 n0)))
(values clip-pos
uv
norm
(s~ world-pos :xyz)
tbn
(* tbn light-pos)
(* tbn cam-pos)
(* tbn (s~ view-pos :xyz)))))
(defun-g frag-tex-tbn ((uv :vec2)
(frag-norm :vec3)
(frag-pos :vec3)
(tbn :mat3)
(tan-light-pos :vec3)
(tan-cam-pos :vec3)
(tan-frag-pos :vec3)
&uniform
(cam-pos :vec3)
(albedo :sampler-2d)
(normap :sampler-2d)
(height-map :sampler-2d))
(let* ((light-pos *pointlight-pos*)
;; Parallax
(tan-cam-dir (- tan-cam-pos tan-frag-pos))
(newuv (parallax-mapping uv tan-cam-dir height-map .1))
;; ---------
(light-color (v! 1 1 1))
(light-strength 1f0)
;;--------------------
(vec-to-light (- light-pos frag-pos))
(dir-to-light (normalize vec-to-light))
;;--------------------
(color (expt (s~ (texture albedo newuv) :xyz)
(vec3 2.2)))
(normal (norm-from-map normap newuv))
(normal (normalize (* tbn normal))))
(values
;; (v! final-color 1)
;; (v! 1 1 1 1)
;;frag-pos
(normalize frag-norm))))
(defpipeline-g generic-tex-pipe ()
:vertex (vert-with-tbdata g-pnt tb-data)
:fragment (frag-tex-tbn :vec2 :vec3 :vec3 :mat3
;; Parallax
:vec3 :vec3 :vec3))
;;--------------------------------------------------
;; 3D - g-pnt mesh without tangents
(defun-g vert
((vert g-pnt) &uniform
(model-world :mat4) (world-view :mat4) (view-clip :mat4)
(scale :float))
(let* ((pos (* scale (pos vert)))
(norm (norm vert))
(tex (tex vert))
(world-norm (* (m4:to-mat3 model-world) norm))
(world-pos (* model-world (v! pos 1)))
(view-pos (* world-view world-pos))
(clip-pos (* view-clip view-pos)))
(values clip-pos
tex
world-norm
(s~ world-pos :xyz))))
;; http://wiki.ogre3d.org/tiki-index.php?page=-Point+Light+Attenuation
(defun-g frag ((uv :vec2)
(frag-norm :vec3)
(frag-pos :vec3)
&uniform
(time :float)
(color :vec3)
(cam-pos :vec3))
(let* (
;;--------------------
(final-color color)
(final-color
(dir-light-apply final-color
(v! 20 20 20)
(v! 0 1000 1000)
frag-pos
frag-norm))
(final-color
(point-light-apply final-color
(v! 10 10 10)
*light-pos*
frag-pos
frag-norm
1f0
0.014 0.07)))
(values (v! final-color 1)
(v! 0 1 0 1))))
;;--------------------------------------------------
;; 2D - Post Processing
(defun-g vert-2d ((vert :vec2))
(let* ((uv (+ .5 (* .5 vert))))
(values (v! vert 0 1)
uv)))
(defun-g frag-2d ((uv :vec2) &uniform (sam :sampler-2d) (samd :sampler-2d))
(let* ((color (defered-fog (v! .5 .6 .7) uv sam samd))
;; (color
;; (s~ (nineveh.anti-aliasing:fxaa3 uv sam (v2! (/ 1 320f0))) :xyz))
(ldr (nineveh.tonemapping:tone-map-reinhard color *exposure*))
(luma (rgb->luma-bt601 ldr))
)
;;(v! (pow ldr (vec3 2.2)) 1)
(v! ldr luma)
;;(v! (- 1 (x color)) 0 0 1)
;;(v! color 1)
;;(v! ldr 1)
))
(defpipeline-g generic-2d-pipe (:points)
:fragment (frag-2d :vec2))
;;--------------------------------------------------
;; 3D - g-pnt mesh with light shading
(defpipeline-g generic-pipe ()
:vertex (vert g-pnt)
:fragment (frag :vec2 :vec3 :vec3))
;;--------------------------------------------------
(defun-g frag-tex ((uv :vec2)
(frag-norm :vec3)
(frag-pos :vec3)
&uniform
(cam-pos :vec3)
(albedo :sampler-2d))
(let* ((light-pos *pointlight-pos*)
;; ---------
(light-color (v! 1 1 1))
(light-strength 1f0)
;;--------------------
(vec-to-light (- light-pos frag-pos))
(dir-to-light (normalize vec-to-light))
;;--------------------
(color (expt (s~ (texture albedo (* 20 uv)) :xyz)
(vec3 2.2)))
;;--------------------
;;(normal (normalize frag-norm))
;;(nfm (norm-from-map normap uv))
(color (apply-fog color
(v! .5 .6 .7)
(length (- frag-pos cam-pos))
cam-pos
(normalize (- frag-pos cam-pos)))))
(v! color 1)))
(defpipeline-g tex-pipe ()
:vertex (vert g-pnt)
:fragment (frag-tex :vec2 :vec3 :vec3))
;;--------------------------------------------------
(defparameter *parallax-scale* .07)
(defun-g pbr-frag ((uv :vec2)
(frag-norm :vec3)
(frag-pos :vec3)
(tbn :mat3)
(tan-light-pos :vec3)
(tan-cam-pos :vec3)
(tan-frag-pos :vec3)
&uniform
(light-pos :vec3)
(time :float)
(color-mult :float)
(cam-pos :vec3)
(ao-map :sampler-2d)
(rough-map :sampler-2d)
(albedo :sampler-2d)
(height-map :sampler-2d)
(normal-map :sampler-2d)
(uv-repeat :float)
(uv-speed :float)
(irradiance-map :sampler-cube)
(prefilter-map :sampler-cube)
(brdf-lut :sampler-2d) )
(let* (;; First change UV, then parallax!
;;(uv (treat-uvs uv))
(uv (+ (* uv uv-repeat)
(v! 0 (* uv-speed time))
))
(uv (parallax-mapping-offset
uv
(normalize (- tan-cam-pos tan-frag-pos))
height-map
*parallax-scale*))
(roughness (x (texture rough-map uv)))
(ao (x (texture ao-map uv)))
(color (* color-mult (expt (s~ (texture albedo uv) :xyz)
(vec3 2.2))))
;; Normal Mapping
(normal (normalize (norm-from-map normal-map uv)))
(normal (normalize (* tbn normal)))
;;----------------------------------------
;; PBR
;; metallic
(metallic .1)
(f0 (vec3 .04))
;;(f0 color)
(f0 (mix f0 color metallic))
;; pbr - reflectance equation
(lo (vec3 0f0))
(n normal)
(v (normalize (- cam-pos frag-pos)))
;; lights START
(lo (+ lo (pbr-direct-lum *light-pos*
frag-pos
v
n
roughness
f0
metallic
color)))
;; (lo (+ lo (pbr-point-lum (v! (* 5 (sin time))
;; 0
;; (* 5 (cos time)))
;; frag-pos
;; v
;; n
;; roughness
;; f0
;; metallic
;; color)))
;; ---------- END
;;(ambient (* color ao (vec3 .03)))
;; (ambient (pbr-ambient-map-r irradiance-map
;; color
;; ao n v f0
;; roughness))
(r (reflect (- v) n))
(f (fresnel-schlick-roughness (max (dot n v) 0)
f0
roughness))
(ks f)
(kd (* (- 1 ks) (- 1 metallic)))
(irradiance (s~ (texture irradiance-map n) :xyz))
(diffuse (* irradiance color))
(prefiltered-color (s~ (texture-lod prefilter-map
r
(* roughness 4f0))
:xyz))
(env-brdf (texture brdf-lut (v! (max (dot n v) 0) (* roughness 4f0))))
(specular (* prefiltered-color (+ (* f (x env-brdf)) (y env-brdf))))
(ambient (* (+ specular (* kd diffuse)) ao))
(final-color (+ ambient lo))
;; Fog
;; (final-color
;; (fog-exp2-apply final-color
;; ;;(v! .3 .2 .1)
;; (v! .2 .3 .4)
;; frag-pos
;; cam-pos .02))
)
(v! final-color 1)))
(defpipeline-g pbr-pipe ()
:vertex (vert-with-tbdata g-pnt tb-data)
:fragment (pbr-frag :vec2 :vec3 :vec3
:mat3 :vec3 :vec3 :vec3))
;;--------------------------------------------------
(defun-g pbr-simple-frag ((uv :vec2)
(frag-norm :vec3)
(frag-pos :vec3)
&uniform
(light-pos :vec3)
(time :float)
(color-mult :float)
(color :vec3)
(cam-pos :vec3)
(irradiance-map :sampler-cube)
(prefilter-map :sampler-cube)
(brdf-lut :sampler-2d))
(let* (;; First change UV, then parallax!
(uv (treat-uvs uv))
(normal (normalize frag-norm))
(roughness *rough*)
(ao 1f0)
(color color)
;;----------------------------------------
;; PBR
;; metallic
(metallic .1)
;;(f0 (vec3 .04))
(f0 color)
(f0 (mix f0 color metallic))
;; pbr - reflectance equation
(n normal)
(v (normalize (- cam-pos frag-pos)))
(lo (vec3 0f0))
;; lights START
(lo (+ lo (pbr-direct-lum light-pos
frag-pos
v
n
roughness
f0
metallic
color)))
;; ---------- END
;;vec3 R = reflect(-V, N);
;; vec3 F = FresnelSchlickRoughness(max(dot(N, V), 0.0), F0, roughness);
;; vec3 kS = F;
;; vec3 kD = 1.0 - kS;
;; kD *= 1.0 - metallic;
;; vec3 irradiance = texture(irradianceMap, N).rgb;
;; vec3 diffuse = irradiance * albedo;
;; const float MAX_REFLECTION_LOD = 4.0;
;; vec3 prefilteredColor = textureLod(prefilterMap, R, roughness * MAX_REFLECTION_LOD).rgb;
;; vec2 envBRDF = texture(brdfLUT, vec2(max(dot(N, V), 0.0), roughness)).rg;
;; vec3 specular = prefilteredColor * (F * envBRDF.x + envBRDF.y);
;; vec3 ambient = (kD * diffuse + specular) * ao;
(r (reflect (- v) n))
(f (fresnel-schlick-roughness (max (dot n v) 0)
f0
roughness))
(ks f)
(kd (* (- 1 ks) (- 1 metallic)))
(irradiance (s~ (texture irradiance-map n) :xyz))
(diffuse (* irradiance color))
(prefiltered-color (s~ (texture-lod prefilter-map
r
(* roughness 4f0))
:xyz))
(env-brdf (texture brdf-lut (v! (max (dot n v) 0) (* roughness 4f0))))
(specular (* prefiltered-color (+ (* f (x env-brdf)) (y env-brdf))))
(ambient (* (+ specular (* kd diffuse)) ao))
;; (ambient (pbr-ambient-map-r irradiance-map
;; color
;; ao n v f0
;; roughness))
;;(ambient (* color ao (vec3 .3)))
(final-color (+ ambient lo))
;; Fog
;; (final-color
;; (fog-exp2-apply final-color
;; (v! 0 0 0)
;; frag-pos
;; cam-pos .03))
)
(v! final-color 1)))
(defun-g fresnel-schlick-roughness ((cos-theta :float)
(f0 :vec3)
(roughness :float))
(+ f0
(* (- (max (vec3 (- 1 roughness))
f0)
f0)
(pow (- 1 cos-theta) 5f0))))
(defun-g pbr-ambient-map ((irradiance-map :sampler-cube)
(albedo :vec3)
(ao :float)
(n :vec3)
(v :vec3)
(f0 :vec3))
(let* ((ks (fresnel-schlick (max (dot n v) 0) f0))
(kd (- 1 ks))
(irradiance (s~ (texture irradiance-map n) :xyz))
(diffuse (* irradiance albedo)))
(* diffuse kd ao)))
(defun-g pbr-ambient-map-r ((irradiance-map :sampler-cube)
(albedo :vec3)
(ao :float)
(n :vec3)
(v :vec3)
(f0 :vec3)
(roughness :float))
(let* ((ks (fresnel-schlick-roughness (max (dot n v) 0)
f0
roughness))
(kd (- 1 ks))
(irradiance (s~ (texture irradiance-map n) :xyz))
(diffuse (* irradiance albedo)))
(* diffuse kd ao)))
(defpipeline-g pbr-simple-pipe ()
:vertex (vert g-pnt)
:fragment (pbr-simple-frag :vec2 :vec3 :vec3))
;;--------------------------------------------------
;; Cubemap
;; Rendering order does not matter
;; Use it with a 1x1x1 box AND
;; depth-test-function #'<=
(defun-g cubemap-vert ((g-pnt g-pnt)
&uniform
(mod-clip :mat4))
(let* ((pos3 (pos g-pnt))
(pos4 (v! pos3 1))
(cpos4 (* mod-clip pos4)))
(values (s~ cpos4 :xyww)
pos3)))
(defun-g cubemap-frag ((tc :vec3)
&uniform
(tex :sampler-cube))
(v! (expt (s~ (texture tex tc) :xyz)
(vec3 2.2))
1f0))
(defpipeline-g cubemap-pipe ()
(cubemap-vert g-pnt)
(cubemap-frag :vec3))
;;----------------------------------------
;; GI - IBL - Diffuse ambient
(defun-g cube-down-frag ((frag-pos :vec3)
&uniform
(tex :sampler-cube))
(let* ((normal (normalize frag-pos))
(irradiance (v! 0 0 0))
(up (v! 0 1 0))
(right (cross up normal))
(up (cross normal right))
(sample-delta .025)
(nr-samples 0f0))
(for
(phi 0f0) (< phi (* 2 +pi+)) (setf phi (+ phi sample-delta))
(for
(theta 0f0) (< theta (* .5 +pi+)) (setf theta (+ theta sample-delta))
(let* (;; spherical to cartesian (in tangent space)
(tangent-sample (v! (* (sin theta) (cos phi))
(* (sin theta) (sin phi))
(cos theta)))
;; Tangent space to world
(sample-vec (+ (* right (x tangent-sample))
(* up (y tangent-sample))
(* normal (z tangent-sample)))))
(incf irradiance (* (s~ (texture tex sample-vec) :xyz)
(cos theta)
(sin theta)))
(incf nr-samples 1f0))))
(setf irradiance (* +pi+ irradiance (/ 1 nr-samples)))
(v! irradiance 1)))
(defpipeline-g cube-down-pipe ()
:vertex (cubemap-vert g-pnt)
:fragment (cube-down-frag :vec3))
;;--------------------------------------------------
;; This gives us a sample vector somewhat oriented around the expected
;; microsurface's halfway vector based on some input roughness and the
;; low-discrepancy sequence value Xi. Note that Epic Games uses the
;; squared roughness for better visual results as based on Disney's
;; original PBR research.
(defun-g importance-sample-ggx ((xi :vec2)
(n :vec3)
(roughness :float))
(let* ((a (* roughness roughness))
(phi (* 2 +pi+ (x xi)))
(cos-theta (sqrt (/ (- 1 (y xi))
(+ 1 (* (1- (* a a)) (y xi))))))
(sin-theta (sqrt (- 1 (* cos-theta cos-theta))))
;; from spherical coordinates to cartesian coordinates
(h (v! (* (cos phi) sin-theta)
(* (sin phi) sin-theta)
cos-theta))
;; from tangent-space vector to world-space sample vector
(up (if (< (abs (z n)) .999)
(v! 0 0 1)
(v! 1 0 0)))
(tangent (normalize (cross up n)))
(bitangent (cross n tangent))
(sample-vec (+ (* (x h) tangent)
(* (y h) bitangent)
(* (z h) n))))
(normalize sample-vec)))
(defun-g prefilter-frag ((frag-pos :vec3)
&uniform
(environment-map :sampler-cube)
(roughness :float))
(let* ((n (normalize frag-pos))
;; make the simplyfying assumption that V equals R equals the normal
(r n)
(v r)
(total-weight 0f0)
(prefiltered-color (vec3 0f0)))
(dotimes (i 1024)
(let* ((xi (hammersley-nth-2d 1024 i))
(h (importance-sample-ggx xi n roughness))
(l (normalize (- (* 2 h (dot v h)) v)))
(n-dot-l (max (dot n l) 0f0)))
(when (> n-dot-l 0)
(let* ((d (distribution-ggx n h roughness))
(n-dot-h (max (dot n h) 0))
(h-dot-v (max (dot h v) 0))
(pdf (+ .0001 (/ (* d n-dot-h)
(* 4 h-dot-v))))
(resolution 512)
(sa-texel (/ (* 4 +pi+)
(* 6 resolution resolution)))
(sa-sample (/ (+ .0001 (* pdf 1024))))
(mip-level (if (= 0 roughness)
0f0
(* .5 (log2 (/ sa-sample sa-texel))))))
(incf prefiltered-color
(* (s~ (texture-lod environment-map l mip-level) :xyz)
n-dot-l))
(incf total-weight n-dot-l)))))
(divf prefiltered-color (vec3 total-weight))
(v! prefiltered-color 1)))
(defpipeline-g prefilter-pipe ()
:vertex (cubemap-vert g-pnt)
:fragment (prefilter-frag :vec3))
| 20,608 | Common Lisp | .lisp | 521 | 25.973129 | 104 | 0.406452 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 7d8f0d617339b179e71544bc25bba709101c51f79732c107ac4752cfc4fd3322 | 9,107 | [
-1
] |
9,108 | camera.lisp | azimut_shiny/examples/light-etude/camera.lisp | (in-package :shiny)
(defclass camera ()
((pos :initarg :pos :initform (v! 0 0 0) :accessor rot)
(rot :initarg :rot :initform (q:identity) :accessor pos)
(near :initarg :near :initform .1 :accessor near)
(far :initarg :far :initform 400f0 :accessor far)
(frame-size
:initarg :frame-size :initform nil :accessor frame-size)
(buf :initform (box))))
(defclass orth (camera)
((tex :initform (get-tex "static/LetterO.jpg"))))
(defclass pers (camera)
((fov :initform 60f0 :accessor fov)
(tex :initform (get-tex "static/LetterP.jpg"))))
(defparameter *camera* (make-instance 'pers))
(defparameter *camera1* (make-instance 'orth))
(defparameter *currentcamera* *camera*)
(defun world->view (camera)
(m4:* (m4:translation (v3:negate (pos camera)))
(q:to-mat4 (q:inverse (rot camera)))))
(defgeneric projection (camera)
(:method ((camera pers))
(let ((fs (or (frame-size camera)
(viewport-resolution (current-viewport)))))
(rtg-math.projection:perspective
(x fs)
(y fs)
(near camera)
(far camera)
(fov camera))))
(:method ((camera orth))
(let ((fs (or (frame-size camera)
(viewport-resolution (current-viewport)))))
(rtg-math.projection:orthographic
(x fs)
(y fs)
(near camera)
(far camera)))))
(defmethod update ((camera orth))
(setf (pos camera) (v! 0 0 0))
(setf (frame-size camera) (v2! 5))
;; (setf (rot camera) (v! 0 0 0))
(setf (rot camera)
;; TOP
(q:from-axis-angle (v! 1 0 0)
(radians -90))
;; FRONT
; (q:identity)
;; (q:from-axis-angle (v! 1 0 0)
;; (radians -45))
))
(defparameter *crotate* nil)
(defparameter *head* nil)
(defparameter *wave* 1f0)
(defparameter *cam-vector* (v! 1 0 0))
(defmethod update ((camera pers))
;;(setf (pos camera) (v! 0 2 9))
;;(setf (far camera) 100f0)
(setf (pos camera) (v! 0 0 3))
;;n(setf (rot camera) (q:from-axis-angle *cam-vector* (radians 90)))
(setf (rot camera)
(q:from-axis-angle *cam-vector*
;;(radians 90)
(radians (mod (* 20 (mynow)) 360))
;;(radians (+ 130 (mod (* 20 (mynow)) 90)))
)
)
)
| 2,356 | Common Lisp | .lisp | 68 | 27.926471 | 70 | 0.567852 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | f660f065d94197e75cf8325ac071b61017fb977b94b96d3c742027c235bb91d6 | 9,108 | [
-1
] |
9,109 | main.lisp | azimut_shiny/examples/light-etude/main.lisp | (in-package :shiny)
(defvar *dimensions-fbo* nil)
(defvar *fbo* nil)
(defvar *sam* nil)
;; Assimp
(defvar *mesh* nil)
(defvar *mesh-light* nil)
(defvar *ass* nil)
(defvar *ass-light* nil)
(defvar *blend* nil)
(defvar *bs* nil)
;; Merge
(defvar *sam-depth* nil)
(defvar *fbo-secondary* nil)
(defvar *sam-secondary* nil)
(defvar *fbo-terciary* nil)
(defvar *sam-terciary* nil)
;; SSAO
(defvar *sam-pos* nil)
(defvar *sam-nor* nil)
(defvar *sam-alb* nil)
(defvar *fbo-ao* nil)
(defvar *sam-ao* nil)
(defvar *noise-tex* nil)
(defvar *noise-sam* nil)
(defvar *fbo-ao-blur* nil)
(defvar *sam-ao-blur* nil)
(defvar *ubo-kernel* nil)
;; Blur
(defvar *sam1* nil)
(defvar *half-fbo* nil)
(defvar *fourth-fbo* nil)
(defvar *eighth-fbo* nil)
(defvar *sixteen-fbo* nil)
(defvar *sam-half-fbo* nil)
(defvar *sam-fourth-fbo* nil)
(defvar *sam-eighth-fbo* nil)
(defvar *sam-sixteen-fbo* nil)
(defun generate-rotation-kernel ()
(loop :repeat 4 :collect
(loop :repeat 4 :collect
(v! (1- (* 2 (random 1f0)))
(1- (* 2 (random 1f0)))
0f0))))
(defun generate-sample-kernel ()
(loop :for i :below 64 :collect
(let* ((sample (v! (1- (* 2 (random 1f0)))
(1- (* 2 (random 1f0)))
(random 1f0)))
(sample (v3:normalize sample))
(sample (v3:*s sample (random 1f0)))
(scale (/ i 64f0))
(scale (lerp .1 1f0 (* scale scale))))
(v3:*s sample scale))))
(defun initialize ()
;;(unless *mesh*)
(setf *mesh*
(elt
(slot-value
(ai:import-into-lisp
"/home/sendai/untitled.3ds"
:processing-flags '(:ai-process-triangulate
:ai-process-calc-tangent-space))
'ai:meshes)
0))
(setf *mesh-light*
(elt
(slot-value
(ai:import-into-lisp
"/home/sendai/untitled-light.3ds"
:processing-flags '(:ai-process-triangulate
:ai-process-calc-tangent-space))
'ai:meshes)
0))
(when *ass* (cepl:free (slot-value *ass* 'buf)))
(when *ass-light* (cepl:free (slot-value *ass-light* 'buf)))
(setf *ass*
(make-instance 'assimp-thing-with-maps
:rot (q:from-axis-angle (v! 1 0 0)
(radians -90))
:buf (assimp-mesh-to-stream *mesh*)))
(setf *ass-light*
(make-instance 'assimp-bloom
:rot (q:from-axis-angle (v! 1 0 0)
(radians -90))
:buf (assimp-mesh-to-stream *mesh-light*)))
;;--------------------------------------------------
;; Buffer stream for single stage pipelines
(unless *bs* (setf *bs* (make-buffer-stream nil :primitive :points)))
;;--------------------------------------------------
;; HDR fbo(s)
(when *fbo*
(free *fbo*)
;; (free *fbo-secondary*)
;; (free *fbo-terciary*)
;; (free *fbo-ao*)
)
;; (setf *fbo* (make-fbo (list 0 :element-type :rgba16f)
;; ;; BLOOM LIGHT
;; (list 1 :element-type :rgba16f)
;; ;; SSAO
;; (list 2 :element-type :rgb16f) ;; pos
;; (list 3 :element-type :rgb16f) ;; nor
;; :d))
(setf *fbo* (make-fbo ;;(list 0 :element-type :rgb16f) ;; pos
(list 0 :element-type :rgb16f) ;; nor
:d))
(setf *dimensions-fbo* (dimensions (attachment-tex *fbo* 0)))
;; (setf *sam* (cepl:sample (attachment-tex *fbo* 0) :wrap :clamp-to-edge))
;; (setf *sam1* (cepl:sample (attachment-tex *fbo* 1) :wrap :clamp-to-edge))
;;--------------------------------------------------
;; SSAO - Normal and position textures
(setf *sam-depth* (cepl:sample (attachment-tex *fbo* :d)
:minify-filter :nearest
:magnify-filter :nearest
:wrap :clamp-to-edge))
;; (setf *sam-pos* (cepl:sample (attachment-tex *fbo* 0)
;; :minify-filter :nearest
;; :magnify-filter :nearest
;; :wrap :clamp-to-edge))
(setf *sam-nor* (cepl:sample (attachment-tex *fbo* 0)
:minify-filter :nearest
:magnify-filter :nearest))
;; SSAO - Random kernel rotations - generate noise texture
(unless *noise-tex*
(setf *noise-tex* (make-texture (generate-rotation-kernel)
:element-type :rgb32f))
(setf *noise-sam* (cepl:sample *noise-tex*
:minify-filter :nearest
:magnify-filter :nearest)))
;; SSAO - samples
(unless *ubo-kernel*
(setf *ubo-kernel* (make-ubo (list (generate-sample-kernel))
'random-kernel)))
;; (unless *g-kernel*
;; (setf *g-kernel* (make-gpu-array (generate-sample-kernel)
;; :dimensions 64
;; :element-type :vec3)))
;; SSAO - ?
;; (setf *fbo-ao* (make-fbo (list 0 :element-type :r16)))
;; (setf *sam-ao* (cepl:sample (attachment-tex *fbo-ao* 0)
;; :minify-filter :nearest
;; :magnify-filter :nearest
;; :wrap :clamp-to-edge))
;; (setf *fbo-ao-blur* (make-fbo (list 0 :element-type :r8)))
;; (setf *sam-ao-blur* (cepl:sample (attachment-tex *fbo-ao-blur* 0)
;; :minify-filter :nearest
;; :magnify-filter :nearest
;; :wrap :clamp-to-edge))
;;--------------------------------------------------
;; Sec FBO
;; (setf *fbo-secondary* (make-fbo (list 0 :element-type :rgba16f)))
;; (setf *sam-secondary*
;; (cepl:sample (attachment-tex *fbo-secondary* 0)
;; :wrap :clamp-to-edge))
;; Ter FBO
;; (setf *fbo-terciary* (make-fbo (list 0 :element-type :rgba16f)))
;; (setf *sam-terciary*
;; (cepl:sample (attachment-tex *fbo-terciary* 0)
;; :wrap :clamp-to-edge))
;;--------------------------------------------------
;; BLUR
;; Used for the upsampling part of the blur
(unless *blend*
(setf *blend* (make-blending-params :source-rgb :one
:destination-rgb :one)))
(when *half-fbo*
(free *half-fbo*)
(free *fourth-fbo*)
(free *eighth-fbo*)
(free *sixteen-fbo*))
;; (flet ((f (d) (mapcar (lambda (x) (round (/ x d)))
;; *dimensions-fbo*)))
;; (setf *half-fbo*
;; (make-fbo (list 0 :element-type :rgba16f :dimensions (f 2))))
;; (setf *fourth-fbo*
;; (make-fbo (list 0 :element-type :rgba16f :dimensions (f 4))))
;; (setf *eighth-fbo*
;; (make-fbo (list 0 :element-type :rgba16f :dimensions (f 8))))
;; (setf *sixteen-fbo*
;; (make-fbo (list 0 :element-type :rgba16f :dimensions (f 16))))
;; (setf *sam-half-fbo* (cepl:sample (attachment-tex *half-fbo* 0)
;; :wrap :clamp-to-edge))
;; (setf *sam-fourth-fbo* (cepl:sample (attachment-tex *fourth-fbo* 0)
;; :wrap :clamp-to-edge))
;; (setf *sam-eighth-fbo* (cepl:sample (attachment-tex *eighth-fbo* 0)
;; :wrap :clamp-to-edge))
;; (setf *sam-sixteen-fbo* (cepl:sample (attachment-tex *sixteen-fbo* 0)
;; :wrap :clamp-to-edge)))
;;--------------------------------------------------
(setf (clear-color) (v! 0 0 0 1))
;;(setf (clear-color) (v! 0 0 0 1))
(setf *actors* nil)
;;;(make-box)
(make-cement)
(make-celestial-sphere)
;;(push *ass* *actors*)
;;(push *ass-light* *actors*)
;;(make-sphere)
;;(make-piso)
NIL)
(defun draw! ()
(let ((res (surface-resolution (current-surface))))
(setf (resolution (current-viewport)) res)
(update *currentcamera*)
(update-all-the-things *actors*)
(with-fbo-bound (*fbo*)
(clear-fbo *fbo*)
(loop :for actor :in *actors* :do
(draw actor *currentcamera*)))
;; Really poor implementation of the awesome and more effective bloom from:
;; https://catlikecoding.com/unity/tutorials/advanced-rendering/bloom/
;; (let ((width (car *dimensions-fbo*))
;; (height (car (last *dimensions-fbo*))))
;; (with-setf* ((depth-mask) nil
;; (cull-face) nil
;; (clear-color) (v! 0 0 0 1)
;; (depth-test-function) #'always)
;;;;--------------------------------------------------
;; (with-fbo-bound (*half-fbo*)
;; (clear-fbo *half-fbo*)
;; (map-g #'bloom-pipe *bs*
;; :sam *sam1*
;; :x (/ 1f0 width)
;; :y (/ 1f0 height)
;; :delta 1f0))
;; (with-fbo-bound (*fourth-fbo*)
;; (clear-fbo *fourth-fbo*)
;; (map-g #'bloom-pipe *bs*
;; :sam *sam-half-fbo*
;; :x (/ 1f0 (round (* .5 width)))
;; :y (/ 1f0 (round (* .5 height)))))
;; (with-fbo-bound (*eighth-fbo*)
;; (clear-fbo *eighth-fbo*)
;; (map-g #'bloom-pipe *bs*
;; :sam *sam-fourth-fbo*
;; :x (/ 1f0 (round (* .5 (* .5 width))))
;; :y (/ 1f0 (round (* .5 (* .5 height))))))
;; (with-fbo-bound (*sixteen-fbo*)
;; (clear-fbo *sixteen-fbo*)
;; (map-g #'bloom-pipe *bs*
;; :sam *sam-eighth-fbo*
;; :x (/ 1f0 (round (* .5 (* .5 (* .5 width)))))
;; :y (/ 1f0 (round (* .5 (* .5 (* .5 height)))))))
;;;;--------------------------------------------------
;; ;; END downscale BEGIN upscale
;; (with-blending *blend*
;; (with-fbo-bound (*eighth-fbo*)
;; (clear-fbo *eighth-fbo*)
;; (map-g #'bloom-pipe *bs*
;; :sam *sam-sixteen-fbo*
;; :x (/ 1f0 (round (* .5 (* .5 (* .5 width)))))
;; :y (/ 1f0 (round (* .5 (* .5 (* .5 height)))))
;; :delta .5)))
;; (with-blending *blend*
;; (with-fbo-bound (*fourth-fbo*)
;; (clear-fbo *fourth-fbo*)
;; (map-g #'bloom-pipe *bs*
;; :sam *sam-eighth-fbo*
;; :x (/ 1f0 (round (* .5 (* .5 width))))
;; :y (/ 1f0 (round (* .5 (* .5 height)))))))
;; (with-blending *blend*
;; (with-fbo-bound (*half-fbo*)
;; (clear-fbo *half-fbo*)
;; (map-g #'bloom-pipe *bs*
;; :sam *sam-fourth-fbo*
;; :x (/ 1f0 (round (* .5 width)))
;; :y (/ 1f0 (round (* .5 height))))))
;; (with-blending *blend*
;; (with-fbo-bound (*fbo-secondary*)
;; (clear-fbo *fbo-secondary*)
;; (map-g #'bloom-pipe *bs*
;; :sam *sam-half-fbo*
;; :x (/ 1f0 width)
;; :y (/ 1f0 height))))
;;--------------------------------------------------
;; ;; END upscale BEGIN merge
;; (with-fbo-bound (*fbo-terciary*)
;; (clear-fbo *fbo-terciary*)
;; (map-g #'dobloom-pipe *bs*
;; :sam *sam*
;; :light-sam *sam-secondary*
;; :delta .5
;; :x (/ 1f0 width)
;; :y (/ 1f0 height)))))
(as-frame
(with-setf* ((depth-mask) nil
(cull-face) nil
(clear-color) (v! 0 0 0 1)
(depth-test-function) #'always)
(map-g #'ssao-pipe *bs*
;; :g-position *sam-pos*
:g-normal *sam-nor*
:g-depth *sam-depth*
:kernel *kernel*
:kernel-effect *kernel-effect*
:radius *radius*
;; :world-view (world->view *currentcamera*)
:tex-noise *noise-sam*
:random-kernel *ubo-kernel*
:res (v! *dimensions-fbo*)
:view-clip (projection *currentcamera*))))
;; (as-frame
;; (map-g #'generic-2d-pipe *bs*
;; ;;:sam *sam-terciary*
;; ;;:sam *sam*
;; :sam *sam-nor*
;; ))
))
(def-simple-main-loop runplay
(:on-start #'initialize)
(draw!))
| 12,766 | Common Lisp | .lisp | 312 | 34.099359 | 79 | 0.457173 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 2827a8f632412e4f1926072e164502f43eee092f5af119e9aa056b063d7ad2c9 | 9,109 | [
-1
] |
9,110 | draw.lisp | azimut_shiny/examples/light-etude/draw.lisp | (in-package :shiny)
(defparameter *dirlight-pos* (v! 1000 1000 1000))
(defparameter *dirlight-mul* .5)
(defparameter *pointlight-pos* (v! 0 2 0))
(defun render-all-the-things (actor camera)
(update actor)
(draw actor camera))
(defgeneric draw (actor camera))
(defmethod draw (actor camera))
;; (defmethod draw ((actor camera) camera)
;; (with-slots (buf tex) actor
;; (map-g #'generic-tex-pipe buf
;; :time (mynow)
;; :scale 1f0
;; :tex tex
;; ;; :color (v! .1 .1 .8)
;; :model-world (model->world actor)
;; :world-view (world->view camera)
;; :view-clip (projection camera))))
;; (defmethod draw ((actor piso) camera)
;; (with-slots (buf scale) actor
;; (map-g #'generic-pipe buf
;; :scale 1f0
;; :color (v! .9 .9 .9)
;; :model-world (model->world actor)
;; :world-view (world->view camera)
;; :view-clip (projection camera))))
(defmethod draw ((actor cement) camera)
(with-slots
(buf scale albedo normal height)
actor
;; (map-g #'assimp-norm-pipeline buf
;; :normal-map normal
;; :scale scale
;; :model-world (model->world actor)
;; :world-view (world->view camera)
;; :view-clip (projection camera))
(map-g #'generic-pipe ;;#'generic-tex-pipe
buf
:scale scale
:color (v! 0 0 0)
;; :albedo albedo
;; :normap normal
;; :light-pos *pointlight-pos*
:cam-pos (pos camera)
;; :height-map height
:model-world (model->world actor)
:world-view (world->view camera)
:view-clip (projection camera))))
;; (defmethod draw ((actor box) camera)
;; (with-slots (buf scale) actor
;; (map-g #'generic-pipe buf
;; :time 1f0 ;;(mynow)
;; :scale scale
;; :color (v! .9 .9 .9)
;; :model-world (model->world actor)
;; :world-view (world->view camera)
;; :view-clip (projection camera))))
;; (defmethod draw ((actor sphere) camera)
;; (with-slots (buf scale) actor
;; (map-g #'generic-pipe buf
;; :time (mynow)
;; :scale scale
;; :color (v! 1 1 1)
;; :model-world (model->world actor)
;; :world-view (world->view camera)
;; :view-clip (projection camera))))
;;--------------------------------------------------
;; (defmethod draw ((actor assimp-thing) camera)
;; (with-slots (buf scale) actor
;; (map-g #'generic-pipe buf
;; :scale 1f0
;; :color (v! .2 .2 .2)
;; :model-world (model->world actor)
;; :world-view (world->view camera)
;; :view-clip (projection camera))))
(defmethod draw ((actor assimp-thing-with-maps) camera)
(with-slots (buf scale albedo normal height) actor
(map-g #'assimp-pipe buf
:scale 1f0
:albedo albedo
:normap normal
:height-map height
:model-world (model->world actor)
:world-view (world->view camera)
:view-clip (projection camera))))
(defmethod draw ((actor assimp-bloom) camera)
(with-slots (buf scale) actor
(map-g #'light-pipe buf
:color (v3:*s (v! 1f0 .7 .3) 230f0)
:model-world (model->world actor)
:world-view (world->view camera)
:view-clip (projection camera))))
(defmethod draw ((actor celestial-sphere) camera)
(with-slots (buf scale) actor
(with-setf (cull-face) :front
(map-g #'light-pipe buf
;;:color (v! .5 .2 .5)
:scale 1f0
:model-world (model->world actor)
:world-view (world->view camera)
:view-clip (projection camera)))))
| 3,830 | Common Lisp | .lisp | 102 | 33.137255 | 55 | 0.543203 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | caa171e9ef9be320358a743ac2bc70319ab27fa70e89eb9e66fb41b562f999d1 | 9,110 | [
-1
] |
9,111 | actors.lisp | azimut_shiny/examples/light-etude/actors.lisp | (in-package :shiny)
(defvar *actors* nil)
(defun update-all-the-things (l)
(declare (list l))
(loop :for actor :in l :do
(update actor)))
(defun model->world (actor)
(with-slots (pos rot) actor
(m4:* (m4:translation pos)
(q:to-mat4 rot))))
(defun delete-actor-name (actor-name)
(declare (keyword actor-name))
(setf *actors*
(delete-if
(lambda (x) (eq actor-name (slot-value x 'name)))
*actors*))
NIL)
(defun delete-actor-class (class-name)
(declare (string class-name))
(setf *actors*
(delete-if
(lambda (x) (string= class-name (class-name (class-of x))))
*actors*))
NIL)
(defmethod sync (x) (+ .5 (* .5 (sin x))))
(defmethod cync (x) (+ .5 (* .5 (cos x))))
(defclass actor ()
((name :initarg :name :initform (gensym))
(pos :initarg :pos :initform (v! 0 0 0) :accessor pos)
(rot :initarg :rot :initform (v! 0 0 0) :accessor rot)
(buf :initarg :buf :initform (box))
(scale :initarg :scale :initform 1f0)))
(defclass assimp-thing (actor) ())
(defclass assimp-thing-with-maps (actor)
((albedo
:initform (get-tex "static/32.Rock01-1k/rock01_albedo.jpg"))
(normal
:initform (get-tex "static/32.Rock01-1k/rock01_normal.jpg"))
(height
:initform (get-tex "static/32.Rock01-1k/rock01_height.jpg"))))
(defclass assimp-bloom (actor) ())
(defclass celestial-sphere (actor)
((buf :initform (box 5 5 5))))
(defclass piso (actor)
((buf :initform (box 15 .1 15))))
(defclass box (actor)
((buf :initform (box 2 2 2))))
(defclass sphere (actor)
((buf :initform (sphere 1))))
(defclass cement (actor)
((buf :initform (box 1 1 1 t))
(albedo
:initform (get-tex "static/16.Plasterwall02-1k/plasterwall02_albedo.jpg"))
(normal
:initform (get-tex "static/16.Plasterwall02-1k/plasterwall02_normal.jpg"))
(height
:initform (get-tex "static/16.Plasterwall02-1k/plasterwall02_height.jpg"))))
(defun make-celestial-sphere ()
(let ((obj (make-instance 'celestial-sphere)))
(push obj *actors*)
obj))
(defun make-box ()
(let ((obj (make-instance 'box)))
(push obj *actors*)
obj))
(defun make-cement ()
(let ((obj (make-instance 'cement :pos (v! 0 -1 0))))
(push obj *actors*)
obj))
(defun make-sphere ()
(let ((obj (make-instance 'sphere)))
(push obj *actors*)
obj))
(defun make-piso ()
(let ((obj (make-instance 'piso)))
(push obj *actors*)
obj))
(defgeneric update (actor))
(defmethod update (actor))
(defmethod update ((actor box))
(setf (pos actor) (v! 0 -1 0))
(setf (rot actor) (q:identity))
;; (setf (slot-value actor 'scale) .5)
;; (setf (rot actor)
;; (q:from-axis-angle
;; (v! 1 1 1)
;; (radians (* 360 (sync (* .2 (mynow)))))))
)
(defmethod update ((actor assimp-thing))
(setf (pos actor) (v! 0 0 0)))
(defmethod update ((actor assimp-thing-with-maps))
(setf (pos actor) (v! 0 0 0)))
(defmethod update ((actor cement))
;; (setf (pos actor) (v! 0 -.4 0))
)
(defmethod update ((actor assimp-bloom))
(setf (pos actor) (v! 0 0 0)))
| 3,086 | Common Lisp | .lisp | 97 | 28.298969 | 80 | 0.627477 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | b4abc1fc4e2455281e6622bcecd0a46c1567ce8698c0eea76ba9888af15b8e51 | 9,111 | [
-1
] |
9,112 | render.lisp | azimut_shiny/examples/light-etude/render.lisp | (in-package :shiny)
(defparameter *exposure* 1f0)
(defun-g treat-uvs ((uv :vec2))
(v! (x uv) (- 1.0 (y uv))))
;;--------------------------------------------------
;; (defun-g assimp-norm-geom ((normals (:vec3 3)))
;; (declare (output-primitive :kind :line-strip :max-vertices 6))
;; (labels ((gen-line ((index :int))
;; (let* ((magnitude 2)
;; (p0 (gl-position (aref gl-in index)))
;; (p1 (+ p0 (* (v! (aref normals index) 0) magnitude))))
;; (setf gl-position p0)
;; (emit-vertex)
;; (setf gl-position p1)
;; (emit-vertex)
;; (end-primitive)
;; (values))))
;; (gen-line 0)
;; (gen-line 1)
;; (gen-line 2)
;; (values)))
;; (defun-g assimp-norm-vert ((vert g-pnt) (tb tb-data)
;; &uniform
;; (model-world :mat4)
;; (world-view :mat4)
;; (view-clip :mat4)
;; (scale :float)
;; (normal-map :sampler-2d))
;; (with-slots (tangent bitangent) tb
;; (with-slots (position texture) vert
;; (let* ((model-pos (v! (* position scale) 1))
;; (world-pos (* model-world model-pos))
;; (view-pos (* world-view world-pos))
;; (clip-pos (* view-clip view-pos))
;; (t0 (normalize
;; (s~ (* model-world
;; (v! tangent 0))
;; :xyz)))
;; ;; (b0 (normalize
;; ;; (s~ (* model-world
;; ;; (v! bitangent 0))
;; ;; :xyz)))
;; (n0 (normalize
;; (s~ (* model-world
;; (v! (norm vert) 0))
;; :xyz)))
;; (t0 (normalize (- t0 (* (dot t0 n0) n0))))
;; (b0 (cross n0 t0))
;; (tbn (mat3 t0 b0 n0))
;; (world-norm (* (m4:to-mat3 model-world) (norm vert)))
;; (norm-from-map (norm-from-map normal-map texture))
;; (new-world-normal (* tbn norm-from-map))
;; (view-norm (* (mat4 (m4:to-mat3 world-view))
;; (v! new-world-normal 0)))
;; (clip-norm (* view-clip view-norm)))
;; (values clip-pos
;; (s~ clip-norm :xyz))))))
;; (defun-g assimp-norm-frag ()
;; (v! 1 1 0 1))
;; (defpipeline-g assimp-norm-pipeline ()
;; :vertex (assimp-norm-vert g-pnt tb-data)
;; :geometry (assimp-norm-geom (:vec3 3))
;; :fragment (assimp-norm-frag))
;; 3D - assimp-mesh with textures
(defstruct-g (random-kernel :layout :std-140)
(random-v3 (:vec3 64)))
(defun-g assimp-vert
((assimp assimp-mesh)
&uniform
(model-world :mat4)
(world-view :mat4)
(view-clip :mat4)
(scale :float)
;; Parallax vars
(light-pos :vec3)
(cam-pos :vec3))
(with-slots (pos normal uv tangent bitangent) assimp
(let* ((pos (* scale pos))
(uv (treat-uvs uv))
(norm (* (m4:to-mat3 model-world) normal))
(world-pos (* model-world (v! pos 1)))
(view-pos (* world-view world-pos))
(clip-pos (* view-clip view-pos))
(tbn (mat3 tangent bitangent norm)))
(values clip-pos
uv
norm
(s~ world-pos :xyz)
tbn
(* tbn light-pos)
(* tbn cam-pos)
(* tbn (s~ world-pos :xyz))))))
(defpipeline-g assimp-pipe ()
:vertex (assimp-vert assimp-mesh)
:fragment (frag-tex :vec2 :vec3 :vec3 :mat3
;; Parallax
:vec3 :vec3 :vec3))
;;--------------------------------------------------
;; 3D - g-pnt with tangent info in tb-data AND textures
(defun-g vert-with-tbdata
((vert g-pnt) (tb tb-data)
&uniform
(model-world :mat4)
(world-view :mat4)
(view-clip :mat4)
(scale :float)
;; Parallax vars
(light-pos :vec3)
(cam-pos :vec3))
(let* ((pos (* scale (pos vert)))
(norm (norm vert))
(uv (treat-uvs (tex vert)))
(norm (* (m4:to-mat3 model-world) norm))
(world-pos (* model-world (v! pos 1)))
(view-pos (* world-view world-pos))
(clip-pos (* view-clip view-pos))
(t0 (normalize
(s~ (* model-world
(v! (tb-data-tangent tb) 0))
:xyz)))
(n0 (normalize
(s~ (* model-world
(v! norm 0))
:xyz)))
(t0 (normalize (- t0 (* (dot t0 n0) n0))))
(b0 (cross n0 t0))
(tbn (mat3 t0 b0 n0)))
(values clip-pos
uv
norm
(s~ world-pos :xyz)
tbn
(* tbn light-pos)
(* tbn cam-pos)
(* tbn (s~ world-pos :xyz)))))
(defun-g frag-tex ((uv :vec2)
(frag-norm :vec3)
(frag-pos :vec3)
(tbn :mat3)
(tan-light-pos :vec3)
(tan-cam-pos :vec3)
(tan-frag-pos :vec3)
&uniform
(cam-pos :vec3)
(albedo :sampler-2d)
(normap :sampler-2d)
(height-map :sampler-2d))
(let* ((light-pos *pointlight-pos*)
;; Parallax
(tan-cam-dir (- tan-cam-pos tan-frag-pos))
(newuv (parallax-mapping uv tan-cam-dir height-map .1))
;; ---------
(light-color (v! 1 1 1))
(light-strength 1f0)
;;--------------------
(vec-to-light (- light-pos frag-pos))
(dir-to-light (normalize vec-to-light))
;;--------------------
(color (expt (s~ (texture albedo newuv) :xyz)
(vec3 2.2)))
;;(normal (normalize frag-norm))
(nfm (norm-from-map normap newuv))
(normal (* tbn nfm))
;; (direc-light-strength
;; (* *dirlight-mul*
;; light-color
;; (saturate
;; (dot normal
;; (normalize (- *dirlight-pos* frag-pos))))))
;; (point-light-strength
;; (* light-color
;; light-strength
;; ;; saturate?
;; (saturate (dot normal dir-to-light))
;; ;; attenuation - constant, linear, cuadratic
;; (/ 1f0 (+ 1f0
;; (* .014 (length vec-to-light))
;; (* .07 (pow (length vec-to-light)
;; 2))))))
;; (final-color
;; (+ (* color point-light-strength)
;; (* color direc-light-strength)))
)
(values
;; (v! final-color 1)
;; (v! 1 1 1 1)
;;frag-pos
(normalize frag-norm))))
(defpipeline-g generic-tex-pipe ()
:vertex (vert-with-tbdata g-pnt tb-data)
:fragment (frag-tex :vec2 :vec3 :vec3 :mat3
;; Parallax
:vec3 :vec3 :vec3))
;;--------------------------------------------------
;; 3D - g-pnt mesh without tangents
(defun-g vert
((vert g-pnt) &uniform
(model-world :mat4) (world-view :mat4) (view-clip :mat4)
(scale :float))
(let* ((pos (* scale (pos vert)))
(norm (norm vert))
(tex (tex vert))
(world-norm (* (m4:to-mat3 model-world) norm))
(world-pos (* model-world (v! pos 1)))
(view-pos (* world-view world-pos))
(clip-pos (* view-clip view-pos)))
(values clip-pos
tex
world-norm
(s~ world-pos :xyz))))
;; http://wiki.ogre3d.org/tiki-index.php?page=-Point+Light+Attenuation
(defun-g frag
((uv :vec2) (frag-norm :vec3) (frag-pos :vec3) &uniform
(time :float) (color :vec3) (cam-pos :vec3))
(let* ((light-pos *pointlight-pos*)
(light-color (v! 1 .7 .4))
(light-strength 1f0)
;;--------------------
(vec-to-light (- light-pos frag-pos))
(dir-to-light (normalize vec-to-light))
;;--------------------
(direc-light-strength
(* *dirlight-mul*
light-color
(saturate
(dot frag-norm
(normalize (- *dirlight-pos* frag-pos))))))
(point-light-strength
(* light-color
light-strength
;; saturate?
(saturate (dot frag-norm dir-to-light))
;; attenuation - constant, linear, cuadratic
(/ 1f0 (+ 1f0
(* .014 (length vec-to-light))
(* .07 (pow (length vec-to-light)
2))))))
(final-color (+ (* color point-light-strength)
(* color direc-light-strength))))
(values
;;(v! final-color 1)
;;(v! 0 0 0 1)
;;frag-pos
;;frag-pos
(normalize frag-norm))))
;;--------------------------------------------------
;; 2D - Post Processing
(defun-g vert-2d ((vert :vec2))
(let* ((uv (+ .5 (* .5 vert))))
(values (v! vert 0 1)
uv)))
(defun-g frag-2d ((uv :vec2) &uniform (sam :sampler-2d))
(let* ((color (s~ (texture sam uv) :xyz))
;; (color
;; (s~ (nineveh.anti-aliasing:fxaa3 uv sam (v2! (/ 1 320f0))) :xyz))
(ldr (nineveh.tonemapping:tone-map-reinhard color *exposure*))
;;(luma (rgb->luma-bt601 ldr))
)
(v! (pow ldr (vec3 2.2)) 1)
;;(v! ldr luma)
;;(v! color 1)
))
(defpipeline-g generic-2d-pipe (:points)
:fragment (frag-2d :vec2))
;;--------------------------------------------------
;; 3D - g-pnt mesh with light shading
(defpipeline-g generic-pipe ()
:vertex (vert g-pnt)
:fragment (frag :vec2 :vec3 :vec3))
;;--------------------------------------------------
;; 3D - Lamp solid color
(defun-g light-frag
((uv :vec2) (frag-norm :vec3) (frag-pos :vec3)
&uniform (color :vec3))
(values ;;frag-pos
(normalize frag-norm)
;;(v! color 1)
;;(v! color 1)
))
(defpipeline-g light-pipe ()
:vertex (vert g-pnt)
:fragment (light-frag :vec2 :vec3 :vec3))
;;--------------------------------------------------
;; 2D - Blur
(defun-g sample-box
((uv :vec2) (delta :float) (sam :sampler-2d) (x :float) (y :float))
(let* ((o (* (v! x y x y) (v! (- delta) (- delta) delta delta)))
(s (+ (texture sam (+ uv (s~ o :xy)))
(texture sam (+ uv (s~ o :zy)))
(texture sam (+ uv (s~ o :xw)))
(texture sam (+ uv (s~ o :zw))))))
(* s .125)))
(defun-g some-frag
((uv :vec2) &uniform
(sam :sampler-2d) (x :float) (y :float) (delta :float))
(let ((color (sample-box uv delta sam x y)))
color))
(defpipeline-g bloom-pipe (:points)
:fragment (some-frag :vec2))
;;----------------------------------------
;; 2D - Bloom
(defun-g other-frag ((uv :vec2) &uniform
(light-sam :sampler-2d) (sam :sampler-2d)
(x :float) (y :float) (delta :float))
(let* ((c (texture light-sam uv))
(c (v! (+ (s~ (sample-box uv delta sam x y) :xyz)
(s~ c :xyz))
(w c))))
c))
(defpipeline-g dobloom-pipe (:points)
:fragment (other-frag :vec2))
;;----------------------------------------
(defun-g get-view-pos ((uv :vec2) (g-depth :sampler-2d)
(world-view :mat4))
(let* ((x (1- (* 2f0 (x uv))))
(y (1- (* 2f0 (y uv))))
(z (1- (* 2f0 (x (texture g-depth uv)))))
(pos-proj (v! x y z 1))
(pos-view (* (inverse world-view) pos-proj))
(pos-view (/ pos-view (w pos-view))))
pos-view))
;; THIS ONE WORKS!
;; I had to change to send the view-clip matrix
;; instead of the world-view matrix to the helper func above
;; https://github.com/McNopper/OpenGL/blob/master/Example28/shader/ssao.frag.glsl
(defparameter *kernel* 10)
(defparameter *radius* .1)
(defparameter *kernel-effect* 1f0)
(defun-g ssao-frag ((uv :vec2)
&uniform
(kernel :int)
(radius :float)
(kernel-effect :float)
(g-normal :sampler-2d)
(g-depth :sampler-2d)
(tex-noise :sampler-2d)
(random-kernel random-kernel :ubo)
(res :vec2)
(view-clip :mat4))
(let* ((pos-view (get-view-pos uv g-depth view-clip))
(normal-view
(normalize
(1- (* 2 (s~ (texture g-normal uv) :xyz)))))
(random-vector
(normalize
(1- (* 2 (s~ (texture tex-noise (* (/ res 4) uv)) :xyz)))))
(tangent-view
(normalize
(- random-vector (* (dot random-vector normal-view)
normal-view))))
(bitangent-view (cross normal-view tangent-view))
(kernel-matrix (mat3 tangent-view bitangent-view normal-view))
(oclussion 0f0))
(with-slots (random-v3) random-kernel
(dotimes (i kernel)
(let* ((sample-vector-view
(* kernel-matrix (aref random-v3 (int i))))
(sample-point-view
(+ pos-view (* radius (v! sample-vector-view 0))))
(sample-point-ndc
(* view-clip sample-point-view))
(sample-point-ndc (/ sample-point-ndc
(w sample-point-ndc)))
(sample-point-tex-coord
(+ .5 (* .5 (s~ sample-point-ndc :xy))))
(z-scene-ndc
(1- (* 2 (x (texture g-depth sample-point-tex-coord)))))
(delta (- (z sample-point-ndc) z-scene-ndc)))
(if (and (> delta .0001) (< delta .005))
(incf oclussion 1f0)))))
(v! (vec3 (- 1 (/ oclussion (1- (* kernel-effect kernel)))))
1)))
;; https://learnopengl.com/Advanced-Lighting/SSAO
(defvar *used-frag* 1f0)
(defparameter *kernel* 30)
;; (defun-g ssao-frag ((uv :vec2)
;; &uniform
;; (g-position :sampler-2d)
;; (g-normal :sampler-2d)
;; (tex-noise :sampler-2d)
;; (random-kernel random-kernel :ubo)
;; (res :vec2)
;; (view-clip :mat4))
;; (let* ((kernel-size *kernel*)
;; (radius .5)
;; (bias .025)
;; (noise-scale (/ res 4))
;; ;;
;; (frag-pos
;; (s~ (texture g-position uv) :xyz))
;; (normal
;; (normalize (s~ (texture g-normal uv) :xyz)))
;; (random-vec
;; (normalize (s~ (texture tex-noise (* uv noise-scale)) :xyz)))
;; ;;
;; (tangent
;; (normalize
;; (- random-vec (* normal (dot random-vec normal)))))
;; (bitangent (cross normal tangent))
;; (tbn (mat3 tangent bitangent normal))
;; (oclussion 0f0))
;; (with-slots (random-v3) random-kernel
;; (dotimes (i kernel-size)
;; (let* ((s (aref random-v3 (int i)))
;; (s (* tbn s))
;; (s (+ (* frag-pos *used-frag*)
;; (* s radius) ))
;; (offset (v! s 1))
;; (offset (* view-clip offset))
;; (offset (/ offset (w offset)))
;; (offset (v! (+ .5 (* .5 (s~ offset :xyz))) (w offset)))
;; (sample-depth (z (texture g-position (s~ offset :xy))))
;; (range-check
;; (smoothstep 0f0 1f0 (/ radius (abs (- (z frag-pos)
;; sample-depth))))))
;; (incf oclussion
;; (* (if (>= sample-depth (+ bias (z s)))
;; 1f0
;; 0f0)
;; range-check)))))
;; (v! (vec3 (- 1f0 (/ oclussion kernel-size))) 1)))
;; http://ogldev.atspace.co.uk/www/tutorial45/tutorial45.html
(defparameter *kernel* 20)
;; (defun-g ssao-frag ((uv :vec2)
;; &uniform
;; (g-position :sampler-2d)
;; (g-normal :sampler-2d)
;; (tex-noise :sampler-2d)
;; (random-kernel random-kernel :ubo)
;; (res :vec2)
;; (view-clip :mat4))
;; (let* ((pos (s~ (texture g-position uv) :xyz))
;; (a 0f0)
;; (kernel *kernel*))
;; (with-slots (random-v3) random-kernel
;; (dotimes (i kernel)
;; (let* ((sample-pos (+ pos (aref random-v3 (int i))))
;; (offset (v! sample-pos 1))
;; (offset (* view-clip offset))
;; (offset (/ offset (w offset)))
;; (offset (v! (+ .5 (* .5 (s~ offset :xy)))
;; (s~ offset :zw)))
;; (sample-depth (z (texture g-position (s~ offset :xy)))))
;; (if (< (abs (- (z pos) sample-depth)) .05)
;; (incf a (step sample-depth (z sample-pos)))))))
;; (setf a (- 1f0 (/ a 128f0)))
;; (v! (vec3 (pow a 2f0)) 1)))
(defpipeline-g ssao-pipe (:points)
:fragment (ssao-frag :vec2))
| 17,360 | Common Lisp | .lisp | 449 | 31.507795 | 81 | 0.448707 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | aafe51b1e78baad98a8b5fcc6c5a6e3502e54935d1390416c94fa159f07da9aa | 9,112 | [
-1
] |
9,113 | camera.lisp | azimut_shiny/examples/infinity-plane/camera.lisp | (in-package :shiny)
(defclass camera ()
((pos :initarg :pos :initform (v! 0 0 0) :accessor pos)
(rot :initarg :rot :initform (q:identity) :accessor rot)
(near :initarg :near :initform .1 :accessor near)
(far :initarg :far :initform 400f0 :accessor far)
(frame-size
:initarg :frame-size :initform nil :accessor frame-size)
(buf :initform (box))))
(defclass orth (camera) ())
(defclass pers (camera)
((fov :initform 60f0 :accessor fov)))
(defparameter *camera* (make-instance 'pers))
(defparameter *camera1* (make-instance 'orth))
(defparameter *currentcamera* *camera*)
(defun world->view (camera)
(m4:* (m4:translation (v3:negate (pos camera)))
(q:to-mat4 (q:inverse (rot camera)))))
(defgeneric projection (camera)
(:method ((camera pers))
(let ((fs (or (frame-size camera)
(viewport-resolution (current-viewport)))))
(rtg-math.projection:perspective
(x fs)
(y fs)
(near camera)
(far camera)
(fov camera))))
(:method ((camera orth))
(let ((fs (or (frame-size camera)
(viewport-resolution (current-viewport)))))
(rtg-math.projection:orthographic
(x fs)
(y fs)
(near camera)
(far camera)))))
(defmethod update ((camera orth))
(setf (pos camera) (v! 0 0 0))
(setf (frame-size camera) (v2! 5))
;; (setf (rot camera) (v! 0 0 0))
(setf (rot camera)
;; TOP
;; (q:from-axis-angle (v! 1 0 0)
;; (radians -90))
;; FRONT
(q:from-axis-angle (v! 1 0 0)
(radians -45))
))
(defparameter *crotate* nil)
(defparameter *head* nil)
(defparameter *wave* 1f0)
(defparameter *cam-vector* (v! 1 0 0))
(defmethod update ((camera pers))
(with-slots (pos rot) camera
;; (setf rot (q:*
;; (q:from-axis-angle (v! 1 0 0) (radians 20))
;; (q:from-axis-angle (v! 0 1 0)
;; (radians (* 40 (sin (* .2 (mynow))))))))
;;(setf rot (q:from-axis-angle (v! 0 0 1) (radians 80)))
(setf pos (v! (* .1 (cos (* .5 (mynow))))
(+ 0 (* .1 (sin (* .5 (mynow)))))
(+ 3 (* 1 (cos (* .5 (mynow)))))))
;;(setf rot (q:look-at (v! 0 1 0) pos (v! 0 -1 0)))
))
| 2,301 | Common Lisp | .lisp | 64 | 30.03125 | 77 | 0.549125 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | ae6eba99aba04b411f9b0f4789c0ffc8c18d749ae3c6b4384a8f89a19fef8a90 | 9,113 | [
-1
] |
9,114 | main.lisp | azimut_shiny/examples/infinity-plane/main.lisp | (in-package :shiny)
(defvar *fbo* nil)
(defvar *sam* nil)
(defvar *bs* nil)
(defvar *blend* (make-blending-params))
(defun initialize ()
;;--------------------------------------------------
;; Buffer stream for single stage pipelines
(unless *bs* (setf *bs* (make-buffer-stream nil :primitive :points)))
;;--------------------------------------------------
;; HDR fbo(s)
(when *fbo*
(free *fbo*))
(setf *fbo* (make-fbo (list 0 :element-type :rgb16f)
:d))
(setf *sam* (cepl:sample (attachment-tex *fbo* 0)
:wrap :clamp-to-edge))
(setf (clear-color) (v! 0 0 0 1))
(setf *actors* nil)
(make-pbr)
;;(make-celestial-sphere)
;; (dotimes (i 40)
;; (make-pbr (v! (+ -10 (random 15f0))
;; (+ -2 (random 4f0))
;; (+ -10 (random 20f0)))))
;;(make-piso (v! 0 -2 0))
;; (make-piso (v! 0 2 0)
;; (q:from-axis-angle (v! 1 0 0) (radians 180)))
(%gl::sampler-parameter-f
(%cepl.types::%sampler-id (get-tex "static/checker.dds"))
:texture-max-anisotropy-ext 1f0)
NIL)
(defun draw! ()
(let ((res (surface-resolution (current-surface)))
(time (mynow)))
(setf (resolution (current-viewport)) res)
(setf *pointlight-pos* (v! (* 4 (sin time))
(* 4 (cos time))
0))
(update *currentcamera*)
(update-all-the-things *actors*)
(with-fbo-bound (*fbo*)
(clear-fbo *fbo*)
(loop :for actor :in *actors* :do
(draw actor *currentcamera*))
;; (with-blending *blend*
;; (map-g #'billboard-pipe *bs*
;; :camera-pos (pos *currentcamera*)
;; :tex (get-tex "static/float-alpha.png")
;; :time (mynow)
;; :world-view (world->view *currentcamera*)
;; :view-clip (projection *currentcamera*)))
)
(as-frame
(with-setf* ((depth-mask) nil
(cull-face) nil
(clear-color) (v! 0 0 0 1)
(depth-test-function) #'always)
(map-g #'generic-2d-pipe *bs*
:sam *sam*)))
))
(def-simple-main-loop runplay
(:on-start #'initialize)
(draw!))
| 2,241 | Common Lisp | .lisp | 64 | 28.234375 | 71 | 0.495616 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 8af1bf5d8f3b5e45c7cae52b688f8ca0f35aa98da7baddbe4e5cbbf1e91ca6d7 | 9,114 | [
-1
] |
9,115 | draw.lisp | azimut_shiny/examples/infinity-plane/draw.lisp | (in-package :shiny)
(defparameter *dirlight-pos* (v! 1000 1000 1000))
(defparameter *dirlight-mul* .5)
(defparameter *pointlight-pos* (v! 0 0 0))
(defun render-all-the-things (actor camera)
(update actor)
(draw actor camera))
(defgeneric draw (actor camera))
(defmethod draw (actor camera))
;; (defmethod draw ((actor camera) camera)
;; (with-slots (buf tex) actor
;; (map-g #'generic-tex-pipe buf
;; :time (mynow)
;; :scale 1f0
;; :tex tex
;; ;; :color (v! .1 .1 .8)
;; :model-world (model->world actor)
;; :world-view (world->view camera)
;; :view-clip (projection camera))))
(defmethod draw ((actor piso) camera)
(with-slots (buf scale tex) actor
(map-g #'tex-pipe buf
:scale 1f0
:albedo tex
:cam-pos (pos camera)
:model-world (model->world actor)
:world-view (world->view camera)
:view-clip (projection camera))))
(defmethod draw ((actor box) camera)
(with-slots (buf scale) actor
(map-g #'generic-pipe buf
:scale scale
:color (v! .9 .9 .9)
:model-world (model->world actor)
:world-view (world->view camera)
:view-clip (projection camera))))
(defmethod draw ((actor pbr) camera)
(with-slots (buf albedo normal height roughness scale ao) actor
(map-g #'pbr-pipe buf
:scale scale
:albedo albedo
:height-map height
:ao ao
:time (mynow)
:rough roughness
:cam-pos (pos camera)
:model-world (model->world actor)
:world-view (world->view camera)
:view-clip (projection camera))))
;; (defmethod draw ((actor sphere) camera)
;; (with-slots (buf scale) actor
;; (map-g #'generic-pipe buf
;; :time (mynow)
;; :scale scale
;; :color (v! 1 1 1)
;; :model-world (model->world actor)
;; :world-view (world->view camera)
;; :view-clip (projection camera))))
(defmethod draw ((actor celestial-sphere) camera)
(with-slots (buf scale) actor
(with-setf* ((cull-face) :front
;;(depth-test-function) #'always
;;(depth-mask) nil
)
(map-g #'light-pipe buf
:color (v! .5 .2 .5)
:scale 20f0
:time (mynow)
:model-world (model->world actor)
:world-view (world->view camera)
:view-clip (projection camera)))))
| 2,549 | Common Lisp | .lisp | 71 | 29.211268 | 65 | 0.55389 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 4e8c237cbb841dad4bba956b6f820bbc794426356d2c9d26bf54a2b994d7583f | 9,115 | [
-1
] |
9,116 | render.lisp | azimut_shiny/examples/infinity-plane/render.lisp | (in-package :shiny)
(defparameter *exposure* .5f0)
(defun-g treat-uvs ((uv :vec2))
(v! (x uv) (- 1.0 (y uv))))
;;--------------------------------------------------
;; 3D - g-pnt with tangent info in tb-data AND textures
(defun-g vert-with-tbdata
((vert g-pnt) (tb tb-data)
&uniform
(model-world :mat4)
(world-view :mat4)
(view-clip :mat4)
(scale :float)
;; Parallax vars
(light-pos :vec3)
(cam-pos :vec3))
(let* ((pos (* scale (pos vert)))
(norm (norm vert))
(uv (treat-uvs (tex vert)))
(norm (* (m4:to-mat3 model-world) norm))
(world-pos (* model-world (v! pos 1)))
(view-pos (* world-view world-pos))
(clip-pos (* view-clip view-pos))
(t0 (normalize
(s~ (* model-world
(v! (tb-data-tangent tb) 0))
:xyz)))
(n0 (normalize
(s~ (* model-world
(v! norm 0))
:xyz)))
(t0 (normalize (- t0 (* (dot t0 n0) n0))))
(b0 (cross n0 t0))
(tbn (mat3 t0 b0 n0)))
(values clip-pos
uv
norm
(s~ world-pos :xyz)
tbn
(* tbn light-pos)
(* tbn cam-pos)
(* tbn (s~ world-pos :xyz)))))
(defun-g frag-tex-tbn ((uv :vec2)
(frag-norm :vec3)
(frag-pos :vec3)
(tbn :mat3)
(tan-light-pos :vec3)
(tan-cam-pos :vec3)
(tan-frag-pos :vec3)
&uniform
(cam-pos :vec3)
(albedo :sampler-2d)
(normap :sampler-2d)
(height-map :sampler-2d))
(let* ((light-pos *pointlight-pos*)
;; Parallax
(tan-cam-dir (- tan-cam-pos tan-frag-pos))
(newuv (parallax-mapping uv tan-cam-dir height-map .1))
;; ---------
(light-color (v! 1 1 1))
(light-strength 1f0)
;;--------------------
(vec-to-light (- light-pos frag-pos))
(dir-to-light (normalize vec-to-light))
;;--------------------
(color (expt (s~ (texture albedo newuv) :xyz)
(vec3 2.2)))
;;(normal (normalize frag-norm))
(nfm (norm-from-map normap newuv))
(normal (* tbn nfm))
;; (direc-light-strength
;; (* *dirlight-mul*
;; light-color
;; (saturate
;; (dot normal
;; (normalize (- *dirlight-pos* frag-pos))))))
;; (point-light-strength
;; (* light-color
;; light-strength
;; ;; saturate?
;; (saturate (dot normal dir-to-light))
;; ;; attenuation - constant, linear, cuadratic
;; (/ 1f0 (+ 1f0
;; (* .014 (length vec-to-light))
;; (* .07 (pow (length vec-to-light)
;; 2))))))
;; (final-color
;; (+ (* color point-light-strength)
;; (* color direc-light-strength)))
)
(values
;; (v! final-color 1)
;; (v! 1 1 1 1)
;;frag-pos
(normalize frag-norm))))
(defpipeline-g generic-tex-pipe ()
:vertex (vert-with-tbdata g-pnt tb-data)
:fragment (frag-tex-tbn :vec2 :vec3 :vec3 :mat3
;; Parallax
:vec3 :vec3 :vec3))
;;--------------------------------------------------
;; 3D - g-pnt mesh without tangents
(defun-g vert
((vert g-pnt) &uniform
(model-world :mat4) (world-view :mat4) (view-clip :mat4)
(scale :float))
(let* ((pos (* scale (pos vert)))
(norm (norm vert))
(tex (tex vert))
(world-norm (* (m4:to-mat3 model-world) norm))
(world-pos (* model-world (v! pos 1)))
(view-pos (* world-view world-pos))
(clip-pos (* view-clip view-pos)))
(values clip-pos
tex
world-norm
(s~ world-pos :xyz))))
;; http://wiki.ogre3d.org/tiki-index.php?page=-Point+Light+Attenuation
(defun-g frag
((uv :vec2) (frag-norm :vec3) (frag-pos :vec3) &uniform
(time :float) (color :vec3) (cam-pos :vec3))
(let* ((light-pos *pointlight-pos*)
(light-color (v! 1 .7 .4))
(light-strength 1f0)
;;--------------------
(vec-to-light (- light-pos frag-pos))
(dir-to-light (normalize vec-to-light))
;;--------------------
(direc-light-strength
(* *dirlight-mul*
light-color
(saturate
(dot frag-norm
(normalize (- *dirlight-pos* frag-pos))))))
(point-light-strength
(* light-color
light-strength
;; saturate?
(saturate (dot frag-norm dir-to-light))
;; attenuation - constant, linear, cuadratic
(/ 1f0 (+ 1f0
(* .014 (length vec-to-light))
(* .07 (pow (length vec-to-light)
2))))))
(final-color (+ (* color point-light-strength)
(* color direc-light-strength)
))
(final-color (apply-fog final-color
.02
frag-pos
cam-pos
(v! 0 -100 0))))
(v! 1 1 1)
;; (v! color 0)
))
;;--------------------------------------------------
;; 2D - Post Processing
(defun-g vert-2d ((vert :vec2))
(let* ((uv (+ .5 (* .5 vert))))
(values (v! vert 0 1)
uv)))
(defun-g frag-2d ((uv :vec2) &uniform (sam :sampler-2d))
(let* ((color (s~ (texture sam uv) :xyz))
;; (color
;; (s~ (nineveh.anti-aliasing:fxaa3 uv sam (v2! (/ 1 320f0))) :xyz))
(ldr (nineveh.tonemapping:tone-map-reinhard color *exposure*))
(luma (rgb->luma-bt601 ldr))
)
;;(v! (pow ldr (vec3 2.2)) 1)
(v! ldr luma)
;;(v! color 1)
;;(v! ldr 1)
))
(defpipeline-g generic-2d-pipe (:points)
:fragment (frag-2d :vec2))
;;--------------------------------------------------
;; 3D - g-pnt mesh with light shading
(defpipeline-g generic-pipe ()
:vertex (vert g-pnt)
:fragment (frag :vec2 :vec3 :vec3))
;;--------------------------------------------------
;; 3D - Lamp solid color
(defun-g light-frag
((uv :vec2) (frag-norm :vec3) (frag-pos :vec3)
&uniform (color :vec3) (time :float))
(nineveh.noise:perlin-noise
(+ (* .1 time) frag-pos))
)
(defpipeline-g light-pipe ()
:vertex (vert g-pnt)
:fragment (light-frag :vec2 :vec3 :vec3))
(defun-g frag-tex ((uv :vec2)
(frag-norm :vec3)
(frag-pos :vec3)
&uniform
(cam-pos :vec3)
(albedo :sampler-2d))
(let* ((light-pos *pointlight-pos*)
;; ---------
(light-color (v! 1 1 1))
(light-strength 1f0)
;;--------------------
(vec-to-light (- light-pos frag-pos))
(dir-to-light (normalize vec-to-light))
;;--------------------
(color (* 10 (s~ (texture albedo (* 20 uv)) :xyz)))
;;(color (expt color (vec3 2.2)))
;;--------------------
;; Fog
;;(fog-color (v! 0 1 1))
(fog-color (* 1 (v! 0.14901961 0.3019608 0.69803923)))
;;(fog-factor (fog-linear frag-pos cam-pos .1 30))
;;(fog-factor (fog-exp2 frag-pos cam-pos .16))
;;(normal (normalize frag-norm))
;;(nfm (norm-from-map normap uv))
;; (direc-light-strength
;; (* *dirlight-mul*
;; light-color
;; (saturate
;; (dot normal
;; (normalize (- *dirlight-pos* frag-pos))))))
;; (point-light-strength
;; (* light-color
;; light-strength
;; ;; saturate?
;; (saturate (dot normal dir-to-light))
;; ;; attenuation - constant, linear, cuadratic
;; (/ 1f0 (+ 1f0
;; (* .014 (length vec-to-light))
;; (* .07 (pow (length vec-to-light)
;; 2))))))
;; (final-color
;; (+ (* color point-light-strength)
;; (* color direc-light-strength)))
(color (apply-fog color
.07
frag-pos
cam-pos
(v! 0 100 0))))
(v! color 1)))
(defpipeline-g tex-pipe ()
:vertex (vert g-pnt)
:fragment (frag-tex :vec2 :vec3 :vec3))
;;--------------------------------------------------
;; Billboard
;; https://www.youtube.com/watch?v=puOTwCrEm7Q
;; - basis vectors:
;; -- 3 vectors are true orthogonal
;; -- fill space (span)
;;
(defparameter *quad-3d*
(list '(-1 -1 0) '( 1 -1 0)
'( 1 1 0) '(-1 1 0)))
(defun-g billboard-vert ((pos :vec3)
&uniform
(time :float)
(world-view :mat4))
(* world-view (v! .5 0 18.5 1)))
(defun-g billboard-geom (&uniform (camera-pos :vec3)
(view-clip :mat4))
(declare (output-primitive :kind :triangle-strip :max-vertices 4))
(let* ((p (s~ (gl-position (aref gl-in 0)) :xyz))
(to-camera (normalize (- camera-pos p)))
;;(to-camera (v! (x to-camera) 0 (z to-camera)))
(up (v! 0 1 0))
(right (cross to-camera up)))
;;
(decf p (* .5 right))
(emit ()
(* view-clip (v! p 1))
(v! 0 0))
;;
(incf (y p) 1f0)
(emit ()
(* view-clip (v! p 1))
(v! 0 1))
;;
(decf (y p) 1f0)
(incf p right)
(emit ()
(* view-clip (v! p 1))
(v! 1 0))
;;
(incf (y p) 1f0)
(emit ()
(* view-clip (v! p 1))
(v! 1 1))
(end-primitive)
(values)))
(defun-g billboard-frag ((uv :vec2) &uniform (tex :sampler-2d) (time :float))
(let* ((color (expt (texture tex (treat-uvs (* (m2:rotation-from-euler (radians (+ 0 (sin (* 5 time))))) uv))) (vec4 2.2) )))
color))
(defpipeline-g billboard-pipe (:points)
:vertex (billboard-vert :vec3)
:geometry (billboard-geom)
:fragment (billboard-frag :vec2))
;;--------------------------------------------------
(defun-g pbr-frag ((uv :vec2)
(frag-norm :vec3)
(frag-pos :vec3)
(tbn :mat3)
(tan-light-pos :vec3)
(tan-cam-pos :vec3)
(tan-frag-pos :vec3)
&uniform
(time :float)
(cam-pos :vec3)
(rough :sampler-2d)
(albedo :sampler-2d)
(height-map :sampler-2d)
(normal-map :sampler-2d)
(ao :sampler-2d))
(let* (;;(n (normalize frag-norm))
(tan-cam-dir (- tan-cam-pos tan-frag-pos))
(uv (parallax-mapping uv tan-cam-dir height-map .001))
(n (* tbn (norm-from-map normal-map uv)))
(v (normalize (- cam-pos frag-pos)))
(metallic .001)
(f0 (vec3 .04))
(color (pow (s~ (texture albedo uv) :xyz) (vec3 2.2)))
(ao-color (x (texture ao uv)))
(f0 (mix f0 color metallic))
;; reflectance
(lo (vec3 0f0))
;; calculate per light radiance
(light-pos (+ cam-pos (v! (* 5 (sin time))
0
(* 5 (cos time))
)))
(l (normalize (- light-pos frag-pos)))
(h (normalize (+ v l)))
(distance (length (- light-pos frag-pos)))
(attenuation (/ 1 (* distance distance)))
(radiance (* (v! 1 1 1) attenuation))
;; cook-torrance brdf
(roughness (x (texture rough uv)))
(ndf (distribution-ggx n h roughness))
(g (geometry-smith n v l roughness))
(f (fresnel-schlick (max (dot h v) 0) f0))
;;
(ks f)
(kd (* (- (vec3 1) ks)
(- 1 metallic)))
(numerator (* ndf g f))
(denominator (* 4 (max (dot n v) 0) (max (dot n l) 0)))
(specular (/ numerator (max denominator .001)))
;; add to outgoing radiance lo
(n-dot-l (max (dot n l) 0))
(lo (* (+ specular (/ (* kd color) 3.141516))
radiance
n-dot-l))
(ambient (* (vec3 .03) color ao-color))
(final-color (+ ambient lo))
(final-color (/ final-color (+ color (vec3 1))))
(final-color (pow final-color (vec3 (/ 1 2.2)))))
final-color))
(defpipeline-g pbr-pipe ()
:vertex (vert-with-tbdata g-pnt tb-data)
:fragment (pbr-frag :vec2 :vec3 :vec3
:mat3 :vec3 :vec3 :vec3))
| 13,119 | Common Lisp | .lisp | 360 | 25.936111 | 127 | 0.440446 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 875fa86eb8bfc464c2a5f34ae8ef725c10fda55d13cf57ac2137729c5e5f9f3e | 9,116 | [
-1
] |
9,117 | camera.lisp | azimut_shiny/examples/helpers/camera.lisp | ;; This software is Copyright (c) 2012 Chris Bagley
;; (techsnuffle<at>gmail<dot>com)
;; Chris Bagley grants you the rights to
;; distribute and use this software as governed
;; by the terms of the Lisp Lesser GNU Public License
;; (http://opensource.franz.com/preamble.html),
;; known as the LLGPL.
;;
;; ======================================================
;; This is an example camera class.
;; It doesnt so much special and isnt very optimized but
;; it exists to show that cepl doesnt require you to use
;; the cepl.camera library to make a camera.
;;
;; This camera also doesnt use the 'vec-space type from cepl
;; so this shows what code looks like without that
;; feature
;; ======================================================
;;(in-package :cepl.examples.camera)
(in-package :shiny)
;;;--------------------------------------------------------------
(defclass camera ()
((cam->clip :type (simple-array single-float (16)) :reader cam->clip)
(viewport :initform (make-viewport) :initarg :viewport :reader cam-viewport)
(near :type single-float :reader near :initarg :near)
(far :type single-float :reader far :initarg :far)
(fov :type single-float :reader fov :initarg :fov)))
(defgeneric update-cam->clip (camera))
(defgeneric look-at (camera point-vec3))
(defgeneric (setf near) (distance camera))
(defgeneric (setf far) (distance camera))
(defgeneric (setf fov) (angle camera))
(defgeneric frame-size (camera))
(defgeneric (setf frame-size) (frame camera))
(defmethod update-cam->clip ((camera camera))
(setf (slot-value camera 'cam->clip)
(rtg-math.projection:perspective
(coerce (first (frame-size camera)) 'single-float)
(coerce (second (frame-size camera)) 'single-float)
(coerce (near camera) 'single-float)
(coerce (far camera) 'single-float)
(coerce (fov camera) 'single-float))))
(defmethod (setf near) (distance (camera camera))
(setf (slot-value camera 'near) distance)
(update-cam->clip camera))
(defmethod (setf far) (distance (camera camera))
(setf (slot-value camera 'far) distance)
(update-cam->clip camera))
(defmethod (setf fov) (angle (camera camera))
(setf (slot-value camera 'fov) angle)
(update-cam->clip camera))
(defmethod frame-size ((camera camera))
(viewport-dimensions (cam-viewport camera)))
(defmethod (setf frame-size) (frame (camera camera))
(let ((frame
(etypecase frame
(simple-array (list (aref frame 0)
(aref frame 1)))
(cepl:viewport (cepl:viewport-dimensions frame))
(list frame))))
(setf (viewport-dimensions (cam-viewport camera)) frame))
(update-cam->clip camera))
(defgeneric world->cam (camera))
(defclass pos-dir-cam (camera)
((world-up :type (simple-array single-float (3))
:initform (v3:make 0.0 1.0 0.0)
:initarg :world-up
:accessor world-up)
(position :type (simple-array single-float (3))
:initform (v3:make 0.0 0.0 0.0)
:initarg :pos
:accessor pos)
(direction :type (simple-array single-float (3))
:initform (v3:make 0.0 0.0 -1.0)
:initarg :dir
:accessor dir)))
(defmethod look-at ((camera pos-dir-cam) point-vec3)
(with-slots (world-up position direction) camera
(setf direction (v3:normalize (v3:- point-vec3 position)))))
(defmethod world->cam ((camera pos-dir-cam))
(with-slots (world-up position direction) camera
(let* ((up (v3:normalize
(v3:- world-up
(v3:*s direction (v3:dot world-up direction)))))
(side (v3:cross direction up))
(rotate (m3:from-rows side up (v3:negate direction)))
(eye-inv (v3:negate (m3:*v rotate position)))
(result (m4:rotation-from-mat3 rotate)))
(setf (m4:melm result 0 3) (aref eye-inv 0)
(m4:melm result 1 3) (aref eye-inv 1)
(m4:melm result 2 3) (aref eye-inv 2))
result)))
(defun make-camera (&optional (near 1.0) (far 1000.0) (fov 60.0))
(let* ((camera (make-instance 'pos-dir-cam :near near :far far :fov fov)))
(update-cam->clip camera)
camera))
;;;--------------------------------------------------------------
| 4,244 | Common Lisp | .lisp | 97 | 38.340206 | 79 | 0.622427 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 3b5015897c9a27fe0cea2457d24e6366d5a78ec273e317122b532b7b2aa522a0 | 9,117 | [
-1
] |
9,118 | model-parsers.lisp | azimut_shiny/examples/helpers/model-parsers.lisp | (in-package :shiny)
;;(in-package :cepl.examples.model-parsers)
(defun meshes->lists (scene)
(map 'list #'mesh->lists (classimp:meshes scene)))
(defun mesh->lists (mesh)
(let* ((v (classimp:vertices mesh))
(n (classimp:normals mesh))
(tcs (classimp:texture-coords mesh))
(tc (when (> (length tcs) 0) (aref tcs 0)))
(f (classimp:faces mesh))
(n-len (length n))
(tc-len (length tc))
(set (remove nil `(,v ,@(when n-len (list n))
,@(when tc-len (list tc))))))
`((:data ,(calc-type v n tc)
,(apply #'map 'list #'list set))
(:indices ,(loop :for % :across f :append (coerce % 'list))))))
(defun calc-type (v n tc)
(apply #'cepl-utils:symb-package :cepl
(remove nil (cons :g- (list (and v :p)
(and (> (length n) 0) :n)
(and (> (length tc) 0) :t))))))
(defun mesh-list->gpu (mesh-list)
(list
(destructuring-bind (_ type data) (assoc :data mesh-list)
(declare (ignore _))
(make-gpu-array data :element-type type))
(destructuring-bind (_ data) (assoc :indices mesh-list)
(declare (ignore _))
(make-gpu-array data :element-type :ushort))))
(defun scene-meshes->gpu (scene)
(mapcar #'mesh-list->gpu (meshes->lists scene)))
(defun mesh->gpu (mesh)
(mesh-list->gpu (mesh->lists mesh)))
(defun load-file (file-path)
(scene-meshes->gpu (classimp:import-into-lisp file-path)))
| 1,507 | Common Lisp | .lisp | 36 | 34.027778 | 69 | 0.56587 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | feb93f2d4740a21c791698c5cade02fd3af94589c64100cb94495424c1a8230c | 9,118 | [
-1
] |
9,119 | meshes.lisp | azimut_shiny/examples/helpers/meshes.lisp | (in-package :shiny)
;;(in-package :cepl.examples.meshes)
(defclass region () ())
(defclass linear-region (region) ((points :initarg :points :reader points)))
(defclass implicit-region (region) ((func :initarg :func :reader func)))
(defclass mesh ()
((vertices :initarg :vertices :reader vertices)
(indicies :initarg :index :reader indicies)
(primitive-type :initarg :primitive-type :reader primitive-type)))
(defgeneric vert-layout (mesh))
(defgeneric polygonize (region primitive-type
&key index-data normals texture-coords))
(defmethod vert-layout ((mesh mesh)) (element-type (vertices mesh)))
(defun transform-mesh (mesh &key (translation (v! 0 0 0))
(rotation (v! 0 0 0))
(linear-scale 1.0)
(rotation-type :euler))
;;{TODO} need to add cpu side caching to mesh, is it object that lives on gpu?
(labels ((transform-normal (n)
(cond
((eq rotation-type :euler)
(let ((m (m3:rotation-from-euler rotation)))
(m3:*v m n)))
((or (eq rotation-type :mat3)
(eq rotation-type :matrix)
(eq rotation-type :matrix3))
(m3:*v rotation n))
((or (eq rotation-type :quat)
(eq rotation-type :quaternion))
(q:rotate n rotation)))))
(let ((verts (pull-g (vertices mesh)))
(has-normals (member (vert-layout mesh)
'(:g-pn :g-pnc :g-pnt :g-pntc))))
(push-g
(loop :for v :in verts :collect
(if has-normals
(append (list (v3:*s (v3:+ (first v) translation)
linear-scale)
(transform-normal (second v)))
(subseq v 2))
(cons (v3:*s (v3:+ (first v) translation) linear-scale)
(subseq v 1))))
(vertices mesh))
mesh)))
(defun transform-mesh-with-matrix (mesh matrix &optional normal-matrix)
;;{TODO} need to add cpu side caching to mesh, is it object that lives on gpu?
(let ((verts (pull-g (vertices mesh)))
(has-normals (member (vert-layout mesh)
'(:g-pn :g-pnc :g-pnt :g-pntc))))
(push-g
(loop :for v :in verts :collect
(if has-normals
(append (list (m3:*v matrix (first v))
(m3:*v (or normal-matrix matrix)
(second v)))
(subseq v 2))
(cons (m3:*v matrix (first v)) (subseq v 1))))
verts)
mesh))
(defmethod polygonize ((region linear-region) primitive-type
&key index-data normals texture-coords)
(let* ((points (points region))
(element-type (calc-type
points normals texture-coords)))
(make-instance
'mesh
:vertices (make-gpu-array (apply #'map 'list #'list
(remove nil (list points
normals
texture-coords)))
:element-type element-type)
:vert-layout :element-type
:index (when index-data
(make-gpu-array (flatten-index index-data)
:element-type :ushort))
:primitive-type primitive-type)))
(defun flatten-index (sequence)
(if (typep (elt sequence 0) 'sequence)
(make-array (* (length sequence) (length (elt sequence 0)))
:element-type 'fixnum
:initial-contents
(typecase sequence
(array (loop :for x :across sequence :append (coerce x 'list)))
(list (loop :for x :in sequence :append (coerce x 'list)))))
(make-array (length sequence)
:element-type 'fixnum
:initial-contents sequence)))
| 3,983 | Common Lisp | .lisp | 87 | 31.896552 | 83 | 0.522131 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | ecb348524bfec5c20be7bf596dfd10c09e3fa7c9617d05330f747d8b6d891d3a | 9,119 | [
-1
] |
9,120 | camera.lisp | azimut_shiny/examples/walls/camera.lisp | (in-package :shiny)
(defclass camera ()
((pos :initarg :pos :initform (v! 0 0 0) :accessor rot)
(rot :initarg :rot :initform (q:identity) :accessor pos)
(near :initarg :near :initform .1 :accessor near)
(far :initarg :far :initform 400f0 :accessor far)
(frame-size
:initarg :frame-size :initform nil :accessor frame-size)))
(defclass orth (camera) ())
(defclass pers (camera)
((fov :initform 60f0 :accessor fov)))
(defparameter *camera* (make-instance 'pers))
(defparameter *camera1* (make-instance 'orth))
(defparameter *currentcamera* *camera*)
(defun world->view (camera)
(m4:* (m4:translation (v3:negate (pos camera)))
(q:to-mat4 (q:inverse (rot camera)))))
(defgeneric projection (camera)
(:method ((camera pers))
(let ((fs (or (frame-size camera)
(viewport-resolution (current-viewport)))))
(rtg-math.projection:perspective
(x fs)
(y fs)
(near camera)
(far camera)
(fov camera))))
(:method ((camera orth))
(let ((fs (or (frame-size camera)
(viewport-resolution (current-viewport)))))
(rtg-math.projection:orthographic
(x fs)
(y fs)
(near camera)
(far camera)))))
(defmethod update ((camera orth))
(setf (pos camera)
(v! 0 30 0))
(setf (frame-size camera) (v! 300 300))
;; (setf (rot camera) (v! 0 0 0))
(setf (rot camera)
;; (q:*
;; (q:from-axis-angle (v! 0 1 0)
;; (radians 180)))
(q:from-axis-angle (v! 1 0 0)
(radians -45))))
(defparameter *crotate* nil)
(defparameter *head* nil)
(defparameter *wave* 1f0)
(defmethod update ((camera pers))
(if *head*
(setf (pos camera) *head*)
(setf (pos camera) (v! 2 (+ 40 (* *wave* (sync (mynow)))) 30)))
(if *crotate*
(setf (rot camera)
(q:*
(q:from-axis-angle
(v! 0 1 0)
(radians (mod (* .05 (get-internal-real-time)) 360)))
(q:from-axis-angle
(v! 1 0 0)
(radians (* 45 (sync (* .001 (get-internal-real-time))))))))
(setf (rot camera) (v! 0 0 0)))
;;; (setf (rot camera) (q:from-axis-angle (v! 1 0 0) (radians -10)))
;; (setf (rot camera)
;; ;; (q:*
;; ;; (q:from-axis-angle (v! 0 1 0)
;; ;; (radians 180)))
;; (q:from-axis-angle (v! 1 0 1)
;; (radians 30)))
;; (setf (pos camera) (v! 30 10 70))
;; (setf (pos camera) (v! 0 2 10))
;; (setf (rot camera) (v! 0 0 0))
;; (setf (rot camera)
;; (q:* (q:from-axis-angle
;; (v! 0 1 0)
;; (radians 180))
;; (q:from-axis-angle
;; (v! 1 -1 0)
;; (radians -45))))
)
(defvar *light-camera* (make-instance 'orth))
(setf (pos *light-camera*) (v! 0 5 0))
(setf (rot *light-camera*) (q:from-axis-angle (v! 1 0 0)
(radians -55)))
(setf (frame-size *light-camera*) (v! 20 20))
(defvar *portal-camera* (make-instance 'pers))
(setf (pos *portal-camera*) (v! 0 100 200))
(setf (rot *portal-camera*) (q:from-axis-angle (v! 1 0 0) (radians -10)))
(setf (frame-size *portal-camera*) (v! 30 30))
| 3,290 | Common Lisp | .lisp | 90 | 30.577778 | 80 | 0.53074 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 85a936b22b9db80e370cd99b3f1f21f242eac006b9eb90f3bad41f562caf48ea | 9,120 | [
-1
] |
9,121 | main.lisp | azimut_shiny/examples/walls/main.lisp | (in-package :shiny)
(defun initialize ()
(unless *fbo*
(setf *fbo* (make-fbo 0))
(setf *sam* (cepl:sample (attachment-tex *fbo* 0))))
(unless *lfbo*
(setf *lfbo* (make-fbo '(:d :dimensions (1024 1024))))
(setf *sfbo* (cepl:sample (attachment-tex *lfbo* :d))))
(setf (clear-color) (v! .2 .2 .2 0))
(setf *actors* nil)
(setf *outsiders* nil)
(setf *lead* nil)
;;--------------------------------------------------
;; Make!!!
(make-planet)
(make-sphere)
;; (setf *lead* (make-lead))
;; (make-voz)
;; (make-portal)
;;(make-ground)
nil)
(defun draw! ()
(let ((res (surface-resolution (current-surface))))
(setf (resolution (current-viewport))
res)
(as-frame
(update *currentcamera*)
;; Noise texture
(map-g-into *fbo* #'pass-pipe
(get-quad-stream-v2)
:time (mynow))
;; Shadow
;; (with-fbo-bound (*lfbo* :attachment-for-size :d)
;; (loop :for actor :in *actors* :do
;; (draw actor *light-camera*)))
;;(draw-tex *sam*)
;;; Render
(update-all-the-things *outsiders*)
;;(update *currentcamera*)
(with-fbo-bound (*fbo*)
(clear-fbo *fbo*)
(loop :for actor :in *actors* :do
(draw actor *portal-camera*)))
(loop :for actor :in *outsiders* :do
(draw actor *currentcamera*))
)))
(defun draw! ()
(let ((res (surface-resolution (current-surface))))
(setf (resolution (current-viewport))
res)
(as-frame
(update *currentcamera*)
;; Noise texture
(map-g-into *fbo* #'pass-pipe
(get-quad-stream-v2)
:time (mynow))
;; Shadow
;; (with-fbo-bound (*lfbo* :attachment-for-size :d)
;; (loop :for actor :in *actors* :do
;; (draw actor *light-camera*)))
;;(draw-tex-br *sam*)
;;; Render
;;(update-all-the-things *outsiders*)
;;(update *currentcamera*)
;; (with-fbo-bound (*fbo*)
;; (clear-fbo *fbo*)
;; (loop :for actor :in *actors* :do
;; (draw actor *portal-camera*)))
(loop :for actor :in *actors* :do
(draw actor *currentcamera*)))))
(def-simple-main-loop runplay
(:on-start #'initialize)
(draw!))
| 2,294 | Common Lisp | .lisp | 73 | 24.958904 | 59 | 0.531828 | azimut/shiny | 18 | 2 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | c22b9a46e8f317f6a43d882704d48fdbc0a8c76d22f1a67e2c85484689d15072 | 9,121 | [
-1
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.