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
10,508
MLKValuesFunction.m
benkard_toilet/MLKValuesFunction.m
/* -*- mode: objc; coding: utf-8 -*- */ /* Toilet Lisp, a Common Lisp subset for the Étoilé runtime. * Copyright (C) 2008 Matthias Andreas Benkard. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #import "MLKValuesFunction.h" #import "runtime-compatibility.h" #import "util.h" @implementation MLKValuesFunction -(NSArray *) applyToArray:(NSArray *)arguments { return arguments; } @end
1,000
Common Lisp
.l
26
36.576923
72
0.756198
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
ee9075c290e2eb0be79573c89fe6d6ee3c2229aa71c40742fb6480bfada11101
10,508
[ -1 ]
10,509
MLKNoSuchSymbolError.h
benkard_toilet/MLKNoSuchSymbolError.h
/* -*- mode: objc; coding: utf-8 -*- */ /* Toilet Lisp, a Common Lisp subset for the Étoilé runtime. * Copyright (C) 2008 Matthias Andreas Benkard. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #import "MLKPackage.h" #import <Foundation/NSException.h> #import <Foundation/NSString.h> @interface MLKNoSuchSymbolError : NSException { MLKPackage *_package; NSString *_symbolName; } -(id) initWithPackage:(MLKPackage *)package symbolName:(NSString *)name; -(void) dealloc; @end
1,106
Common Lisp
.l
29
35.827586
72
0.749298
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
4e659a465863028d96b670d57acdc04c793c4bf1b7fc1c0756c84327d738ef50
10,509
[ -1 ]
10,510
MLKReadEvalPrintLoop.h
benkard_toilet/MLKReadEvalPrintLoop.h
/* -*- mode: objc; coding: utf-8 -*- */ /* Toilet Lisp, a Common Lisp subset for the Étoilé runtime. * Copyright (C) 2008 Matthias Andreas Benkard. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #import <Foundation/NSObject.h> @interface MLKReadEvalPrintLoop : NSObject +(void) run; @end
900
Common Lisp
.l
21
40.952381
72
0.752
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
2afc1ac20e32eea593e08ae61f3cab7ad9eaa4d2ea3e3cf8e5d27957a6018d97
10,510
[ -1 ]
10,512
MLKListenerController.h
benkard_toilet/MLKListenerController.h
/* -*- mode: objc; coding: utf-8 -*- */ /* Toilet Lisp, a Common Lisp subset for the Étoilé runtime. * Copyright (C) 2008 Matthias Andreas Benkard. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #import "MLKCharacterStream.h" #import <Cocoa/Cocoa.h> @interface MLKListenerController : MLKCharacterStream { IBOutlet id indicatorText; IBOutlet id inputField; IBOutlet id outputTextView; IBOutlet id statusText; IBOutlet id submitButton; } + (void)initialize; - (void)initialiseInterpreter; - (void)writeChar:(unichar)ch; - (void)writeString:(NSString *)string; - (void)evalObject:(id)object; - (void)enableSubmitButton:(id)sender; - (IBAction)submit:(id)sender; @end
1,303
Common Lisp
.l
35
34.942857
72
0.756757
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
99f40d0b5df68e712e4770323ee0c9babb8e4d616ad3f962a1d7272bf7818aa0
10,512
[ -1 ]
10,513
MLKSemicolonReader.h
benkard_toilet/MLKSemicolonReader.h
/* -*- mode: objc; coding: utf-8 -*- */ /* Toilet Lisp, a Common Lisp subset for the Étoilé runtime. * Copyright (C) 2008 Matthias Andreas Benkard. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #import "MLKFuncallable.h" #import <Foundation/NSArray.h> @interface MLKSemicolonReader : NSObject <MLKFuncallable> -(NSArray *) applyToArray:(NSArray *)arguments; @end
978
Common Lisp
.l
22
42.5
72
0.755789
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
20683777bda8411143bb2f44d1138df0eed0e859e3b240f84c9dd8d6ab78a684
10,513
[ -1 ]
10,514
MLKLowLevelTests.m
benkard_toilet/MLKLowLevelTests.m
/* -*- mode: objc; coding: utf-8 -*- */ /* Toilet Lisp, a Common Lisp subset for the Étoilé runtime. * Copyright (C) 2008 Matthias Andreas Benkard. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <UnitKit/UnitKit.h> #include <Foundation/Foundation.h> #include "MLKCons.h" #include "MLKDoubleFloat.h" #include "MLKDynamicContext.h" #include "MLKEnvironment.h" #include "MLKPackage.h" #include "MLKRatio.h" #include "MLKReader.h" #include "MLKReadtable.h" #include "MLKSingleFloat.h" #include "MLKSymbol.h" #import "runtime-compatibility.h" @interface MLKLowLevelTests : NSObject <UKTest> @end // static void MLKNSUncaughtExceptionHandler (NSException *exception) // { // NSLog (@"Caught unhandled exception.\nName:%@\nReason:%@", // [exception name], // [exception reason]); // } @implementation MLKLowLevelTests -(id) initForTest { self = [super init]; [MLKDynamicContext currentContext]; // NSSetUncaughtExceptionHandler (MLKNSUncaughtExceptionHandler); return self; } -(id) testCons { id obj1 = @"Mulk."; id obj2 = LAUTORELEASE ([[NSMutableDictionary alloc] init]); MLKCons *cons2 = [MLKCons cons:obj1 with:obj2]; MLKCons *cons3 = [MLKCons cons:obj1 with:nil]; MLKCons *cons4 = [MLKCons cons:nil with:nil]; MLKCons *cons5 = [MLKCons cons:nil with:obj2]; MLKCons *cons6 = LAUTORELEASE ([[MLKCons alloc] initWithCar:obj1 cdr:obj2]); MLKCons *cons7 = LAUTORELEASE ([[MLKCons alloc] initWithCar:obj1 cdr:nil]); MLKCons *cons8 = LAUTORELEASE ([[MLKCons alloc] initWithCar:nil cdr:nil]); MLKCons *cons9 = LAUTORELEASE ([[MLKCons alloc] initWithCar:nil cdr:obj2]); UKTrue ([cons2 car] == obj1); UKTrue ([cons3 car] == obj1); UKFalse ([cons4 car] == obj1); UKFalse ([cons5 car] == obj1); UKTrue ([cons6 car] == obj1); UKTrue ([cons7 car] == obj1); UKFalse ([cons8 car] == obj1); UKFalse ([cons9 car] == obj1); UKTrue ([cons2 cdr] == obj2); UKFalse ([cons3 cdr] == obj2); UKFalse ([cons4 cdr] == obj2); UKTrue ([cons5 cdr] == obj2); UKTrue ([cons6 cdr] == obj2); UKFalse ([cons7 cdr] == obj2); UKFalse ([cons8 cdr] == obj2); UKTrue ([cons9 cdr] == obj2); [cons2 setCdr:obj1]; UKTrue ([cons2 cdr] == obj1); [cons2 setCar:obj2]; UKTrue ([cons2 car] == obj2); return nil; } -(id) testInitialReadtable { MLKDynamicContext *ctx = [MLKDynamicContext currentContext]; MLKReadtable *readtable = [ctx valueForSymbol: [[MLKPackage findPackage:@"COMMON-LISP"] intern:@"*READTABLE*"]]; UKTrue ([readtable characterHasCase:'a']); UKTrue ([readtable characterHasCase:'x']); UKTrue ([readtable characterHasCase:'F']); UKTrue ([readtable characterHasCase:228]); // ä UKTrue ([readtable characterHasCase:196]); // Ä UKFalse ([readtable characterHasCase:'=']); UKFalse ([readtable characterHasCase:'.']); UKFalse ([readtable characterHasCase:223]); // ß return nil; } -(id) testTokens { UKObjectKindOf ([MLKReader readFromString:@"a"], MLKSymbol); UKObjectKindOf ([MLKReader readFromString:@"MULK"], MLKSymbol); UKObjectKindOf ([MLKReader readFromString:@"+"], MLKSymbol); UKObjectKindOf ([MLKReader readFromString:@"1-"], MLKSymbol); UKObjectKindOf ([MLKReader readFromString:@"1+"], MLKSymbol); UKObjectKindOf ([MLKReader readFromString:@"0AA0A"], MLKSymbol); UKObjectKindOf ([MLKReader readFromString:@"0AA0A"], MLKSymbol); UKObjectKindOf ([MLKReader readFromString:@"0\\aA0A"], MLKSymbol); UKObjectKindOf ([MLKReader readFromString:@"\\0"], MLKSymbol); UKObjectKindOf ([MLKReader readFromString:@"|abc def (mulk!)|"], MLKSymbol); UKObjectKindOf ([MLKReader readFromString:@"0\\.3"], MLKSymbol); UKObjectKindOf ([MLKReader readFromString:@"134651234"], MLKInteger); UKObjectKindOf ([MLKReader readFromString:@"223555."], MLKInteger); UKObjectKindOf ([MLKReader readFromString:@"-134651234"], MLKInteger); UKObjectKindOf ([MLKReader readFromString:@"-223555."], MLKInteger); UKObjectKindOf ([MLKReader readFromString:@"+134651234"], MLKInteger); UKObjectKindOf ([MLKReader readFromString:@"+223555."], MLKInteger); UKObjectKindOf ([MLKReader readFromString:@"-1."], MLKInteger); UKObjectKindOf ([MLKReader readFromString:@"+2"], MLKInteger); UKObjectKindOf ([MLKReader readFromString:@"3."], MLKInteger); UKObjectKindOf ([MLKReader readFromString:@"3"], MLKInteger); UKObjectKindOf ([MLKReader readFromString:@"55/11"], MLKRatio); UKObjectKindOf ([MLKReader readFromString:@"-55/11"], MLKRatio); UKObjectKindOf ([MLKReader readFromString:@"1234.5678e99"], MLKSingleFloat); UKObjectKindOf ([MLKReader readFromString:@"-1234.5678e99"], MLKSingleFloat); UKObjectKindOf ([MLKReader readFromString:@"+1234.5678e99"], MLKSingleFloat); UKObjectKindOf ([MLKReader readFromString:@"1234.5678e-99"], MLKSingleFloat); UKObjectKindOf ([MLKReader readFromString:@"1234.5678e+99"], MLKSingleFloat); UKObjectKindOf ([MLKReader readFromString:@"-1234.5678e-99"], MLKSingleFloat); UKObjectKindOf ([MLKReader readFromString:@"1234.5678"], MLKSingleFloat); UKObjectKindOf ([MLKReader readFromString:@"-1234.5678"], MLKSingleFloat); UKObjectKindOf ([MLKReader readFromString:@".5678"], MLKSingleFloat); UKObjectKindOf ([MLKReader readFromString:@"-.5678"], MLKSingleFloat); UKObjectKindOf ([MLKReader readFromString:@"+.5678"], MLKSingleFloat); UKObjectKindOf ([MLKReader readFromString:@".5678e3"], MLKSingleFloat); UKObjectKindOf ([MLKReader readFromString:@"-.5678e3"], MLKSingleFloat); UKObjectKindOf ([MLKReader readFromString:@"+.5678e3"], MLKSingleFloat); UKStringsEqual ([[MLKReader readFromString:@"a"] name], @"A"); UKStringsEqual ([[MLKReader readFromString:@"1+"] name], @"1+"); UKStringsEqual ([[MLKReader readFromString:@"mulkmulk"] name], @"MULKMULK"); UKStringsEqual ([[MLKReader readFromString:@"ABCDefghIJKL"] name], @"ABCDEFGHIJKL"); UKStringsEqual ([[MLKReader readFromString:@"class-name"] name], @"CLASS-NAME"); UKStringsEqual ([[MLKReader readFromString:@"\\class-\\name"] name], @"cLASS-nAME"); UKStringsEqual ([[MLKReader readFromString:@"|Class Name|"] name], @"Class Name"); UKStringsEqual ([[MLKReader readFromString:@"class\\ name"] name], @"CLASS NAME"); UKStringsEqual ([[MLKReader readFromString:@"\\100"] name], @"100"); UKStringsEqual ([[MLKReader readFromString:@"a b c d e"] name], @"A"); UKObjectKindOf ([MLKReader readFromString:@"cl::if"], MLKSymbol); UKObjectKindOf ([MLKReader readFromString:@"cl:if"], MLKSymbol); UKObjectKindOf ([MLKReader readFromString:@"cl-user::mulk"], MLKSymbol); UKObjectsSame ([MLKReader readFromString:@"common-lisp-user::a"], [MLKReader readFromString:@"cl-user::a"]); UKObjectsSame ([MLKReader readFromString:@"a"], [MLKReader readFromString:@"cl-user::a"]); return nil; } -(id) testParenReading { UKObjectKindOf ([MLKReader readFromString:@"(1 2)"], MLKCons); UKObjectKindOf ([MLKReader readFromString:@"(1 . 2)"], MLKCons); UKObjectKindOf ([MLKReader readFromString:@"(a b)"], MLKCons); UKNil ([MLKReader readFromString:@"()"]); UKObjectKindOf ([[MLKReader readFromString:@"(1 . 2)"] car], MLKInteger); UKObjectKindOf ([[MLKReader readFromString:@"(1 . 2)"] cdr], MLKInteger); UKObjectKindOf ([[MLKReader readFromString:@"(a b)"] car], MLKSymbol); UKObjectKindOf ([[MLKReader readFromString:@"(a b)"] cdr], MLKCons); UKObjectKindOf ([[MLKReader readFromString:@"((a) b)"] car], MLKCons); return nil; } -(id) testStuff { // UKPass(); UKFail(); // UKNotNil (nil); // UKTrue (1); // UKStringsNotEqual (@"a", @"b"); // UKPass(); return nil; } @end
8,334
Common Lisp
.l
177
43.638418
86
0.716533
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
fddbbc5270c05e738162281add3d6352decae982c3ac1b5f38bda796d9424843
10,514
[ -1 ]
10,515
MLKCompiledClosure.m
benkard_toilet/MLKCompiledClosure.m
/* -*- mode: objc; coding: utf-8 -*- */ /* Toilet Lisp, a Common Lisp subset for the Étoilé runtime. * Copyright (C) 2008 Matthias Andreas Benkard. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #import "MLKCompiledClosure.h" #import "MLKCons.h" #import "functions.h" #import "globals.h" #import "runtime-compatibility.h" #import "util.h" #import <Foundation/NSDictionary.h> #import <Foundation/NSSet.h> #ifdef __OBJC_GC__ #import <Foundation/NSZone.h> #endif #import <stdlib.h> @implementation MLKCompiledClosure -(id) initWithCode:(void *)code data:(id *)data length:(intptr_t)dataLength { int i; m_dataLength = dataLength; m_code = code; #ifdef __OBJC_GC__ m_data = NSAllocateCollectable (dataLength * sizeof(id), NSScannedOption); #else m_data = malloc (dataLength * sizeof(id)); #endif for (i = 0; i < m_dataLength; i++) { m_data[i] = LRETAIN (data[i]); } return self; } +(id) closureWithCode:(void *)code data:(id *)data length:(intptr_t)dataLength { return LAUTORELEASE ([[self alloc] initWithCode:code data:data length:dataLength]); } -(NSArray *) applyToArray:(NSArray *)arguments { int argc = ([arguments count] + 3); ffi_cif cif; ffi_type *arg_types[argc]; ffi_status status; void *argv[argc]; id argpointers[argc - 2]; ffi_arg return_value; int i; id return_values = nil; id *return_values_ptr = &return_values; arg_types[0] = &ffi_type_pointer; argv[0] = &m_data; arg_types[1] = &ffi_type_pointer; argv[1] = &return_values_ptr; for (i = 2; i < argc - 1; i++) { arg_types[i] = &ffi_type_pointer; argpointers[i-2] = denullify([arguments objectAtIndex:(i-2)]); argv[i] = &argpointers[i-2]; } arg_types[argc - 1] = &ffi_type_pointer; argv[argc - 1] = &MLKEndOfArgumentsMarker; status = ffi_prep_cif (&cif, FFI_DEFAULT_ABI, argc, &ffi_type_pointer, arg_types); if (status != FFI_OK) { [NSException raise:@"MLKInvalidFFITypeException" format:@"FFI type is invalid (this is probably a bug)."]; } // NSLog (@"Calling %p (argc = %d)", _code, argc); // for (i = 0; i < argc; i++) // { // NSLog (@"Argument %d: %p", i, *((void**)argv[i])); // } ffi_call (&cif, FFI_FN (m_code), &return_value, (void**)argv); // return_value = ((id (*)(void *, ...))_code) (_data, argpointers[0], argpointers[1], MLKEndOfArgumentsMarker); if (return_values) { MLKCons *values = [return_values cdr]; return (values ? (id)[values array] : (id)[NSArray array]); } else { return [NSArray arrayWithObject:nullify((id)return_value)]; } } -(NSString *) description { return MLKPrintToString (self); } -(NSString *) descriptionForLisp { return [NSString stringWithFormat:@"<Compiled closure @%p>", self]; } -(id (*)()) code { return m_code; } -(void *) closureData { return m_data; } -(void) dealloc { int i; [super dealloc]; // FIXME: Decrease refcount of _code. for (i = 0; i < m_dataLength; i++) { LRELEASE (m_data[i]); } free (m_data); } @end
3,739
Common Lisp
.l
129
25.627907
113
0.656233
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
f450999d1a1b983e08d3ca0d3372c748d7adee62ad53d5fc24846dd949e93909
10,515
[ -1 ]
10,516
MLKSingleFloat.m
benkard_toilet/MLKSingleFloat.m
/* -*- mode: objc; coding: utf-8 -*- */ /* Toilet Lisp, a Common Lisp subset for the Étoilé runtime. * Copyright (C) 2008 Matthias Andreas Benkard. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #define _XOPEN_SOURCE 600 // strtof #import "MLKSingleFloat.h" #import "MLKDoubleFloat.h" #import "runtime-compatibility.h" #import "util.h" #import <Foundation/NSString.h> #include <stdio.h> #include <stdlib.h> #include <locale.h> @implementation MLKSingleFloat -(MLKSingleFloat *) initWithIntegerPart:(NSString *)intPart negative:(BOOL)negative fractionalPart:(NSString *)fractPart exponent:(NSString *)exponent exponentNegative:(BOOL)exponentNegative { self = [super init]; char *locale; // FIXME: This is probably not thread-safe. locale = setlocale (LC_NUMERIC, NULL); setlocale (LC_NUMERIC, "C"); // strtof or sscanf -- is there a difference? sscanf ([[NSString stringWithFormat:@"%c%@.%@e%c%@", (negative ? '-' : '+'), intPart, fractPart, (exponentNegative ? '-' : '+'), ([exponent length] > 0 ? (id)exponent : (id)@"0")] UTF8String], "%f", &value); setlocale (LC_NUMERIC, locale); return self; } +(MLKSingleFloat *) singleFloatWithIntegerPart:(NSString *)intPart negative:(BOOL)negative fractionalPart:(NSString *)fractPart exponent:(NSString *)exponent exponentNegative:(BOOL)exponentNegative { return LAUTORELEASE ([[self alloc] initWithIntegerPart:intPart negative:negative fractionalPart:fractPart exponent:exponent exponentNegative:exponentNegative]); } -(MLKSingleFloat *) initWithFloat:(float)aFloat { self = [super init]; value = aFloat; return self; } +(MLKSingleFloat *) singleFloatWithFloat:(float)aFloat { return LAUTORELEASE ([[self alloc] initWithFloat:aFloat]); } -(float) floatValue { return value; } -(double) doubleValue { return value; } -(MLKNumber *) add:(MLKNumber *)arg { if ([arg isKindOfClass:[MLKDoubleFloat class]]) return [MLKDoubleFloat doubleFloatWithDouble:(value + [(MLKFloat*)arg doubleValue])]; else return [MLKSingleFloat singleFloatWithFloat:(value + [(MLKFloat*)arg floatValue])]; } -(MLKNumber *) subtract:(MLKNumber *)arg { if ([arg isKindOfClass:[MLKDoubleFloat class]]) return [MLKDoubleFloat doubleFloatWithDouble:(value - [(MLKFloat*)arg doubleValue])]; else return [MLKSingleFloat singleFloatWithFloat:(value - [(MLKFloat*)arg floatValue])]; } -(MLKNumber *) multiplyWith:(MLKNumber *)arg { if ([arg isKindOfClass:[MLKDoubleFloat class]]) return [MLKDoubleFloat doubleFloatWithDouble:(value * [(MLKFloat*)arg doubleValue])]; else return [MLKSingleFloat singleFloatWithFloat:(value * [(MLKFloat*)arg floatValue])]; } -(MLKNumber *) divideBy:(MLKNumber *)arg { if ([arg isKindOfClass:[MLKDoubleFloat class]]) return [MLKDoubleFloat doubleFloatWithDouble:(value / [(MLKFloat*)arg doubleValue])]; else return [MLKSingleFloat singleFloatWithFloat:(value / [(MLKFloat*)arg floatValue])]; } -(NSComparisonResult) compare:(MLKSingleFloat *)arg { if (self->value == arg->value) return NSOrderedSame; else if (self->value < arg->value) return NSOrderedAscending; else return NSOrderedDescending; } -(BOOL) isEqual:(id)arg { return ([arg isKindOfClass:[MLKSingleFloat class]] && self->value == ((MLKSingleFloat *)arg)->value); } -(NSString *) description { NSString *str = [NSString stringWithFormat:@"%e", value]; int i; for (i = 0; i < [str length]; i++) { if ([str characterAtIndex:i] == 'e') { str = [NSString stringWithFormat:@"%@s%@", [str substringToIndex:i], [str substringFromIndex:(i+1)]]; return str; } } return [NSString stringWithFormat:@"%@s0",str]; } -(NSString *) descriptionForLisp { return [self description]; } @end
4,960
Common Lisp
.l
144
27.923611
89
0.643409
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
06dabd5de807e4634426021dc201427acf3df00891d8f2fb2f5549d3b952072c
10,516
[ -1 ]
10,517
MLKUnboundVariableError.h
benkard_toilet/MLKUnboundVariableError.h
/* -*- mode: objc; coding: utf-8 -*- */ /* Toilet Lisp, a Common Lisp subset for the Étoilé runtime. * Copyright (C) 2008 Matthias Andreas Benkard. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #import "MLKEnvironment.h" #import "MLKSymbol.h" #import <Foundation/NSException.h> #import <Foundation/NSString.h> @interface MLKUnboundVariableError : NSException { MLKSymbol *_symbol; MLKEnvironment *_env; } -(id) initWithSymbol:(MLKSymbol *)symbol inEnvironment:(MLKEnvironment *)env; -(void) dealloc; @end
1,133
Common Lisp
.l
30
35.633333
72
0.754338
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
9811f4abe6a602936157ac9ab3ef9137df5c82bb75a18a0bf4ba62fbdd0e1d9d
10,517
[ -1 ]
10,518
MLKLexicalContext-MLKLLVMCompilation.h
benkard_toilet/MLKLexicalContext-MLKLLVMCompilation.h
/* -*- mode: objc; coding: utf-8 -*- */ /* Toilet Lisp, a Common Lisp subset for the Étoilé runtime. * Copyright (C) 2008 Matthias Andreas Benkard. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #import "MLKForm.h" #import "MLKLexicalContext.h" #ifdef __cplusplus //#define __STDC_CONSTANT_MACROS #include <vector> #include <llvm/Value.h> #include <llvm/BasicBlock.h> #include <llvm/Instructions.h> //using namespace llvm; #endif #import <Foundation/NSObject.h> #import <Foundation/NSString.h> extern id MLKDummyUseLLVMLexicalContext; @interface MLKLexicalContext (MLKLLVMCompilation) #ifdef __cplusplus -(void) setVariableHeapAllocation:(BOOL)heapp forSymbol:(id)name; -(BOOL) variableHeapAllocationForSymbol:(id)name; -(llvm::Instruction *) functionCellValueForSymbol:(id)name; -(llvm::Instruction *) closureDataPointerValueForSymbol:(id)name; -(llvm::Instruction *) closureDataLengthValueForSymbol:(id)name; -(llvm::Value *) bindingValueForSymbol:(id)name; -(void) locallySetBindingValue:(llvm::Value *)value forSymbol:(id)name; -(void) setBindingValue:(llvm::Value *)value forSymbol:(id)name; -(llvm::Value *) functionBindingValueForSymbol:(id)name; -(void) locallySetFunctionBindingValue:(llvm::Value *)value forSymbol:(id)name; -(void) setFunctionBindingValue:(llvm::Value *)value forSymbol:(id)name; -(llvm::Instruction *) globalBindingValueForSymbol:(id)name; -(llvm::Value *) valueValueForSymbol:(id)name; //-(void) setFunctionCellValue:(llvm::Value *)cellPtr forSymbol:(id)name; //-(void) setClosureDataPointerValue:(llvm::Value *)pointer forSymbol:(id)name; //-(void) setBindingValue:(llvm::Value *)binding forSymbol:(id)name; -(void) setValueValue:(llvm::Value *)value forSymbol:(id)name; #endif @end
2,329
Common Lisp
.l
51
44.215686
79
0.773568
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
d0e64600870135b31f0f2ea5e2beaa01ed30426fb297daaf7656a1e188cb7ecf
10,518
[ -1 ]
10,519
MLKReadtable.h
benkard_toilet/MLKReadtable.h
/* -*- mode: objc; coding: utf-8 -*- */ /* Toilet Lisp, a Common Lisp subset for the Étoilé runtime. * Copyright (C) 2008 Matthias Andreas Benkard. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #import "MLKFuncallable.h" #import <Foundation/NSDictionary.h> #import <Foundation/NSObject.h> #import <Foundation/NSString.h> enum MLKReadtableCase { MLKReadtableCase_UPCASE, MLKReadtableCase_DOWNCASE, MLKReadtableCase_INVERT, MLKReadtableCase_PRESERVE }; enum MLKSyntaxType { CONSTITUENT = 0, WHITESPACE = 1, TERMINATING_MACRO = 2, NONTERMINATING_MACRO = 3, SINGLE_ESCAPE = 4, MULTI_ESCAPE = 5 }; enum MLKConstituentTrait { ALPHABETIC = 1, INVALID = 2, PACKAGE_MARKER = 4, ALPHA_DIGIT = 8, EXPONENT_MARKER = 16, NUMBER_MARKER = 32, RATIO_MARKER = 64, DECIMAL_POINT = 128, MINUS_SIGN = 256, PLUS_SIGN = 512, SIGN = 1024, DOT = 2048 }; @interface MLKReadtable : NSObject <NSCopying> { NSMutableDictionary *_syntaxTable; NSMutableDictionary *_readerMacros; NSMutableDictionary *_traits; //id <MLKFuncallable> _caseConverter; enum MLKReadtableCase _case; } -(MLKReadtable *) init; -(MLKReadtable *) copyWithZone:(NSZone *)zone; -(BOOL) isWhitespaceCharacter:(unichar)ch; -(BOOL) isMacroCharacter:(unichar)ch; -(BOOL) isNonTerminatingMacroCharacter:(unichar)ch; -(BOOL) isTerminatingMacroCharacter:(unichar)ch; -(BOOL) isSingleEscapeCharacter:(unichar)ch; -(BOOL) isMultipleEscapeCharacter:(unichar)ch; -(BOOL) isConstituentCharacter:(unichar)ch; -(BOOL) characterHasCase:(unichar)ch; // Constituent traits. -(BOOL) isInvalid:(unichar)ch; -(BOOL) isAlphabetic:(unichar)ch; -(BOOL) isPackageMarker:(unichar)ch; -(BOOL) isAlphaDigit:(unichar)ch; -(BOOL) isExponentMarker:(unichar)ch; -(BOOL) isNumberMarker:(unichar)ch; -(BOOL) isRatioMarker:(unichar)ch; -(BOOL) isDecimalPoint:(unichar)ch; -(BOOL) isMinusSign:(unichar)ch; -(BOOL) isPlusSign:(unichar)ch; -(BOOL) isSign:(unichar)ch; -(BOOL) isDot:(unichar)ch; // Read-base-dependent digit properties. -(BOOL) isDecimalDigit:(unichar)ch; -(BOOL) isDigit:(unichar)ch inBase:(int)base; -(int) digitWeight:(unichar)ch; -(id <MLKFuncallable>) macroFunctionForCharacter:(unichar)ch; -(void) setMacroFunction:(id <MLKFuncallable>)function forCharacter:(unichar)ch; -(unichar) charWithReadtableCase:(unichar)ch; -(int) characterConstituentTraits:(unichar)ch; -(BOOL) character:(unichar)ch hasTrait:(enum MLKConstituentTrait)trait; -(enum MLKSyntaxType) characterSyntaxType:(unichar)ch; -(void) setSyntaxType:(enum MLKSyntaxType)type forCharacter:(unichar)ch; -(void) setConstituentTrait:(enum MLKConstituentTrait)trait forCharacter:(unichar)ch; -(void) unsetConstituentTrait:(enum MLKConstituentTrait)trait forCharacter:(unichar)ch; @end
3,401
Common Lisp
.l
101
31.316832
80
0.761731
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
7e2744024904f24d9a4de6cd7698cc1ff6c46a0f20e26048585d384eff13c999
10,519
[ -1 ]
10,520
MLKFileHandleStream.h
benkard_toilet/MLKFileHandleStream.h
/* -*- mode: objc; coding: utf-8 -*- */ /* Toilet Lisp, a Common Lisp subset for the Étoilé runtime. * Copyright (C) 2008 Matthias Andreas Benkard. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #import "MLKBinaryStream.h" #import <Foundation/NSFileHandle.h> @interface MLKFileHandleStream : MLKBinaryStream { NSFileHandle *_fileHandle; BOOL _closeWhenDone; } -(id) initWithFileHandle:(NSFileHandle *)fileHandle; -(id) initWithFileHandle:(NSFileHandle *)fileHandle closeWhenDone:(BOOL)closeWhenDone; -(uint8_t) readOctet; -(void) writeOctet:(uint8_t)octet; @end
1,192
Common Lisp
.l
30
37.5
72
0.758442
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
73bf35b71ef6a65b579a8644722e85bb1d0499799a12f3d8b0cffeba2c978742
10,520
[ -1 ]
10,521
MLKFloat.m
benkard_toilet/MLKFloat.m
/* -*- mode: objc; coding: utf-8 -*- */ /* Toilet Lisp, a Common Lisp subset for the Étoilé runtime. * Copyright (C) 2008 Matthias Andreas Benkard. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #import "MLKFloat.h" #import "MLKSingleFloat.h" #import "MLKDoubleFloat.h" #import "MLKPackage.h" #import "MLKDynamicContext.h" #import "runtime-compatibility.h" #import <Foundation/NSException.h> @implementation MLKFloat +(MLKFloat *) floatWithExponentMarker:(unichar)exponentMarker integerPart:(NSString *)intPart negative:(BOOL)negative fractionalPart:(NSString *)fractPart exponent:(NSString *)exponent exponentNegative:(BOOL)exponentNegative { MLKSymbol *defaultFormat; MLKPackage *cl; cl = [MLKPackage findPackage:@"COMMON-LISP"]; defaultFormat = [[MLKDynamicContext currentContext] valueForSymbol:[cl intern:@"*READ-DEFAULT-FLOAT-FORMAT*"]]; // FIXME: Shouldn't the readtable decide which exponent markers do what? if (exponentMarker == 'd' || exponentMarker == 'D' || exponentMarker == 'l' || exponentMarker == 'L' || ((exponentMarker == 'e' || exponentMarker == 'E') && ((defaultFormat == [cl intern:@"DOUBLE-FLOAT"]) || (defaultFormat == [cl intern:@"LONG-FLOAT"])))) return [MLKDoubleFloat doubleFloatWithIntegerPart:intPart negative:negative fractionalPart:fractPart exponent:exponent exponentNegative:exponentNegative]; else return [MLKSingleFloat singleFloatWithIntegerPart:intPart negative:negative fractionalPart:fractPart exponent:exponent exponentNegative:exponentNegative]; } #define DECLARE_ABSTRACT(SIGNATURE, RETURN_VALUE) \ SIGNATURE \ { \ [NSException raise:@"MLKInternalInconsistencyError" \ format:@"Tried to invoke an abstract method."]; \ return RETURN_VALUE; \ } DECLARE_ABSTRACT (-(float) floatValue, 0.0) DECLARE_ABSTRACT (-(double) doubleValue, 0.0) DECLARE_ABSTRACT (-(MLKNumber *) add:(MLKNumber *)arg, nil) DECLARE_ABSTRACT (-(MLKNumber *) subtract:(MLKNumber *)arg, nil) DECLARE_ABSTRACT (-(MLKNumber *) multiplyWith:(MLKNumber *)arg, nil) DECLARE_ABSTRACT (-(MLKNumber *) divideBy:(MLKNumber *)arg, nil) -(NSString *) description { return [super description]; } @end
3,393
Common Lisp
.l
73
38.890411
79
0.617709
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
bd68978ffb4054d35771c64d00d62c4d786abe6c0000ba68f592bb78b9d6a5b4
10,521
[ -1 ]
10,522
MLKClosure.h
benkard_toilet/MLKClosure.h
/* -*- mode: objc; coding: utf-8 -*- */ /* Toilet Lisp, a Common Lisp subset for the Étoilé runtime. * Copyright (C) 2008 Matthias Andreas Benkard. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #import "MLKEnvironment.h" #import "MLKFuncallable.h" #import "MLKFunction.h" #import <Foundation/NSArray.h> #import <Foundation/NSData.h> @interface MLKClosure : NSObject <MLKFuncallable> { MLKFunction *_code; NSData *_closedOverVariableVector; } -(MLKClosure *) initWithFunction:(MLKFunction *)code environment:(MLKEnvironment *)lexenv; -(NSArray *) applyToArray:(NSArray *)arguments; -(void) dealloc; @end
1,246
Common Lisp
.l
32
36.40625
72
0.746888
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
caad998950a30beda8dd778fbb4e845b3f3614786165f5ece56dd25c610a14a3
10,522
[ -1 ]
10,525
classes.nib
benkard_toilet/MainMenu.nib/classes.nib
{ IBClasses = ( {CLASS = FirstResponder; LANGUAGE = ObjC; SUPERCLASS = NSObject; }, { ACTIONS = {submit = id; }; CLASS = MLKListenerController; LANGUAGE = ObjC; OUTLETS = { indicatorText = id; inputField = id; outputTextView = id; statusText = id; submitButton = id; }; SUPERCLASS = NSObject; }, { CLASS = MLKToiletApplicationController; LANGUAGE = ObjC; OUTLETS = {initialListener = id; }; SUPERCLASS = NSObject; } ); IBVersion = 1; }
705
Common Lisp
.l
25
16.44
76
0.446402
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
249dccfbdc79ca423482a5aba6a3a5cf5d256c03d4fee951b2949ee9982fb85e
10,525
[ -1 ]
10,526
STShell+output.m
benkard_toilet/StepTalkShell/STShell+output.m
/** STShell+output Copyright (c) 2002 Free Software Foundation Written by: Stefan Urbanek <[email protected]> Date: 2002 Jun 7 This file is part of the StepTalk project. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02111, USA. */ #import "STShell.h" #import <StepTalk/StepTalk.h> #import <Foundation/NSArray.h> #import <Foundation/NSBundle.h> #import <Foundation/NSDebug.h> #import <Foundation/NSNotification.h> #import <Foundation/NSException.h> #import <Foundation/NSSet.h> #import <Foundation/NSString.h> #import <Foundation/NSValue.h> #include <readline/readline.h> @implementation STShell(STShellOutput) - show:(id)anObject { printf("%s", [[anObject description] cString]); return self; } - showLine:(id)anObject { [self show:anObject]; putchar('\n'); return nil; } - (void)showError:(NSString *)errString { fprintf(stderr, "%s\n\n", [errString cString]); } - showResult:(id)obj { const char *className = [NSStringFromClass([obj class]) cString]; int objIndex = [objectStack count] - 1; int i; if(obj) { if([obj isKindOfClass:[NSArray class]]) { printf("(%i) %s\n", objIndex, className); for(i = 0;i<[obj count]; i++) { printf("%i %s\n", i, [self displayCStringForObject:[obj objectAtIndex:i]]); } } else if([obj isKindOfClass:[NSSet class]]) { printf("(%i) %s\n", objIndex, className); obj = [[obj allObjects] sortedArrayUsingSelector:@selector(compare:)]; for(i = 0;i<[obj count]; i++) { printf("%s\n", [self displayCStringForObject:[obj objectAtIndex:i]]); } } else if([obj isKindOfClass:[NSDictionary class]]) { NSString *key; NSArray *keys; printf("(%i) %s\n", objIndex, className); keys = [[obj allKeys] sortedArrayUsingSelector:@selector(compare:)]; for(i = 0;i<[keys count]; i++) { key = [keys objectAtIndex:i]; printf("%s : %s\n", [self displayCStringForObject:key], [self displayCStringForObject:[obj objectForKey:key]]); } } else { printf("(%i) %s\n", objIndex, [self displayCStringForObject:obj]); } } return self; } - (char *)displayCStringForObject:(id)object { NSString *str = [object description]; if( [str length] > 60 ) { str = [str substringToIndex:60]; str = [str stringByAppendingString:@"..."]; } return [str cString]; } - showException:(NSException *)exception { printf("Error (%s): %s\n", [[exception name] cString], [[exception reason] cString]); return self; } - (id)listObjects { NSString *str; int i; id object; printf("Objects\n"); for(i = 0; i < [objectStack count]; i++) { object = [objectStack objectAtIndex:i]; str = [object description]; if( [str length] > 60 ) { str = [str substringToIndex:60]; str = [str stringByAppendingString:@"..."]; } printf("%4i: '%s' (%s)\n", i, [str cString], [[[object class] description] cString]); } return nil; } @end
4,276
Common Lisp
.l
131
24.335878
82
0.590749
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
2732b085503c2af5003ac4664f67dd9c47c902505aa37ba078eaca4083c6bb97
10,526
[ -1 ]
10,527
STShell.m
benkard_toilet/StepTalkShell/STShell.m
/** STShell StepTalk Shell Copyright (c) 2002 Free Software Foundation Written by: Stefan Urbanek <[email protected]> Date: 2002 May 29 This file is part of the StepTalk project. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02111, USA. */ #import "STShell.h" #import <StepTalk/StepTalk.h> #import <Foundation/NSArray.h> #import <Foundation/NSBundle.h> #import <Foundation/NSDebug.h> #import <Foundation/NSNotification.h> #import <Foundation/NSException.h> #import <Foundation/NSFileManager.h> #import <Foundation/NSSet.h> #import <Foundation/NSString.h> #import <Foundation/NSValue.h> #include <readline/readline.h> static Class NSString_class; static Class NSNumber_class; NSArray *objcSelectors = nil; static STShell *sharedShell = nil; @interface STShell(STPrivateMethods) - (int) completion; - (NSString *)readLine; - (void)initReadline; @end int complete_handler(void) { return [sharedShell completion]; } @implementation STShell + (void)initialize { NSString_class = [NSString class]; NSNumber_class = [NSNumber class]; } + sharedShell { return sharedShell; } - initWithConversation:(STConversation *)conv { self = [super init]; [self initReadline]; objectStack = [[NSMutableArray alloc] init]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bundleLoaded:) name:NSBundleDidLoadNotification object:nil]; scriptsManager = RETAIN([STScriptsManager defaultManager]); prompt = @"StepTalk > "; conversation = RETAIN(conv); /* FIXME: make this more clever for completion handler */ if(!sharedShell) { sharedShell = self; } return self; } - (void)updateCompletionList { NSMutableArray *array = [[NSMutableArray alloc] init]; RELEASE(completionList); [array addObjectsFromArray:STAllObjectiveCSelectors()]; completionList = [[NSArray alloc] initWithArray:array]; updateCompletionList = NO; } - (void)dealloc { RELEASE(objectStack); RELEASE(completionList); RELEASE(scriptsManager); RELEASE(conversation); [[NSNotificationCenter defaultCenter] removeObserver:self]; [super dealloc]; } -(void)bundleLoaded:(NSNotification *)notif { updateCompletionList = YES; } - (void)initReadline { rl_initialize(); rl_bind_key('\t', complete_handler); } - (void)setLanguage:(NSString *)langName { NSDebugLog(@"Setting language to %@", langName); [conversation setLanguage:langName]; } - (void)setEnvironment:(STEnvironment *)newEnv { [conversation setEnvironment:newEnv]; } - (STEnvironment *)environment { return [conversation context]; } - (void)run { STEnvironment *env; NSString *line; id result; [self showLine:@"Welcome to the StepTalk shell."]; // NSLog(@"Environment %@", env); if(![conversation isKindOfClass:[STRemoteConversation class]]) { completionEnabled = YES; } else { [self showLine:@"Note: Completion disabled for distant conversation"]; } while(1) { line = [self readLine]; if(exitRequest) break; if(!line) continue; result = [self executeLine:line]; if(result) { if(result != objectStack) { [objectStack addObject:result]; } [self showResult:result]; } else { [self showResult:result]; } } printf("\n"); } - (id)executeLine:(NSString *)line { NSString *cmd; id result = nil; /* FIXME: why? */ cmd = [line stringByAppendingString:@" "]; NS_DURING [conversation interpretScript:cmd]; result = [conversation result]; NS_HANDLER [self showException:localException]; NS_ENDHANDLER return result; } - (NSString *)readLine { char *str; NSString *actualPrompt = prompt; NSString *line = @""; BOOL done = NO; int len; while(!done) { str = readline([actualPrompt cString]); done = YES; if(!str) { exitRequest = YES; return nil; } len = strlen(str); if(!len) return nil; if(str[len-1] == '\\') { actualPrompt = @"... ? "; str[strlen(str) - 1] = '\0'; done = NO; } line = [line stringByAppendingString:[NSString stringWithCString:str]]; } add_history([line cString]); return line; } - (int)completion { STEnvironment *env; NSEnumerator *enumerator; NSMutableSet *set; NSString *match; NSString *tail; NSString *str; NSArray *array; int pos = 0; int c; if(!completionEnabled) { return 0; } if(rl_point <= 0) { return 0; } pos = rl_point - 1; c = rl_line_buffer[pos]; while((isalnum(c) || c == '_') && pos >= 0) { pos--; c = rl_line_buffer[pos]; } pos++; match = [NSString stringWithCString:rl_line_buffer + pos length:rl_point - pos]; set = [NSMutableSet set]; if(!completionList || updateCompletionList) { [self updateCompletionList]; } enumerator = [completionList objectEnumerator]; while( (str = [enumerator nextObject]) ) { if( [str hasPrefix:match] ) { [set addObject:str]; } } env = [conversation context]; enumerator = [[env knownObjectNames] objectEnumerator]; while( (str = [enumerator nextObject]) ) { if( [str hasPrefix:match] ) { [set addObject:str]; } } array = [set allObjects]; if( [array count] == 0 ) { printf("\nNo match for completion.\n"); rl_forced_update_display(); } else if ( [array count] == 1 ) { str = [array objectAtIndex:0]; str = [str substringFromIndex:rl_point - pos]; rl_insert_text([str cString]); rl_insert_text(" "); rl_redisplay(); } else { enumerator = [array objectEnumerator]; tail = [enumerator nextObject]; while( (str = [enumerator nextObject]) ) { tail = [str commonPrefixWithString:tail options:NSLiteralSearch]; } tail = [tail substringFromIndex:[match length]]; if( tail && ![tail isEqualToString:@""] ) { rl_insert_text([tail cString]); rl_redisplay(); } else { printf("\n"); enumerator = [array objectEnumerator]; while( (str = [enumerator nextObject]) ) { printf("%s\n", [str cString]); } rl_forced_update_display(); } } return 0; } - (void)exit { /* FIXME: this is not nice */ exit(0); } - (id)executeScriptNamed:(NSString *)scriptName { STScript *script = [scriptsManager scriptWithName:scriptName]; id result = nil; if(!script) { [self showError:[NSString stringWithFormat: @"Unable to find script with name '%@'", scriptName]]; } else { NS_DURING result = [conversation runScriptFromString:[script source]]; NS_HANDLER [self showException:localException]; NS_ENDHANDLER } return result; } - (void)setPrompt:(NSString *)aString { ASSIGN(prompt, aString); } - (NSString *)prompt { return prompt; } @end
8,640
Common Lisp
.l
321
20.05919
80
0.601062
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
8060f9741ae9b12535212235923d666fcbb0a81f1b9d97e021b720009ac92dcb
10,527
[ -1 ]
10,528
GNUmakefile
benkard_toilet/StepTalkShell/GNUmakefile
# # StepTalk tools # # Copyright (C) 2002 Stefan Urbanek # # This file is part of the StepTalk. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Library General Public License for more details. # # You should have received a copy of the GNU Library General Public # License along with this library; if not, write to the Free # Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02111, USA. # include $(GNUSTEP_MAKEFILES)/common.make TOOL_NAME = stshell stshell_OBJC_FILES = STShell.m STShell+output.m stshell_tool.m ADDITIONAL_TOOL_LIBS += -lStepTalk -lreadline -lncurses -lToiletKit -L../ToiletKit.framework ADDITIONAL_OBJCFLAGS = -Wall -Wno-import -include GNUmakefile.preamble include $(GNUSTEP_MAKEFILES)/tool.make -include GNUMakefile.postamble
1,186
Common Lisp
.l
29
39.689655
92
0.782798
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
7bf705b81b6c055489467b0530fbf5eda7954c6b9b730e1c9d43bd716d652e2a
10,528
[ -1 ]
10,529
stshell_tool.m
benkard_toilet/StepTalkShell/stshell_tool.m
/** stshell StepTalk Shell Copyright (c) 2002 Free Software Foundation Written by: Stefan Urbanek <[email protected]> Date: 2002 May 29 This file is part of the StepTalk project. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02111, USA. */ #import <StepTalk/StepTalk.h> #import "STShell.h" #import <Foundation/NSArray.h> #import <Foundation/NSAutoreleasePool.h> #import <Foundation/NSDebug.h> #import <Foundation/NSException.h> #import <Foundation/NSProcessInfo.h> #import <Foundation/NSString.h> @interface STShellTool:NSObject { STConversation *conversation; NSArray *arguments; unsigned int currentArg; NSString *environmentName; NSString *hostName; NSString *typeName; NSString *languageName; } - (int)parseArguments; - (NSString *)nextArgument; - (void)reuseArgument; - (void)run; - (void)printHelp; @end @implementation STShellTool - (int)parseArguments { NSString *arg; BOOL isOption = NO; arguments = [[NSProcessInfo processInfo] arguments]; [self nextArgument]; while( (arg = [self nextArgument]) ) { isOption = NO; if( [arg hasPrefix:@"--"] ) { arg = [arg substringFromIndex:2]; isOption = YES; } else if( [arg hasPrefix:@"-"] ) { arg = [arg substringFromIndex:1]; isOption = YES; } if ([@"help" hasPrefix:arg]) { [self printHelp]; return 1; } else if ([@"language" hasPrefix:arg]) { RELEASE(languageName); languageName = [self nextArgument]; if(!languageName) { [NSException raise:@"STShellToolException" format:@"Language name expected"]; } } else if ([@"environment" hasPrefix:arg]) { RELEASE(environmentName); environmentName = [self nextArgument]; if(!environmentName) { [NSException raise:@"STShellToolException" format:@"Environment name expected"]; } } else if ([@"host" hasPrefix:arg]) { RELEASE(hostName); hostName = [self nextArgument]; if(!hostName) { [NSException raise:@"STShellToolException" format:@"Host name expected"]; } } else if ([@"type" hasPrefix:arg]) { RELEASE(typeName); typeName = [self nextArgument]; if(!typeName) { [NSException raise:@"STShellToolException" format:@"Environment description (type) name expected"]; } } else if(!isOption) { break; } } if(arg) { [self reuseArgument]; } return 0; } - (NSString *)nextArgument { if(currentArg < [arguments count]) { return [arguments objectAtIndex:currentArg++]; } return nil; } - (void)reuseArgument { currentArg--; } /* Method taken from stexec.m - look there for updates */ - (void)createConversation { STEnvironmentDescription *desc; STEnvironment *environment; if(environmentName) { /* user wants to connect to a distant environment */ conversation = [[STRemoteConversation alloc] initWithEnvironmentName:environmentName host:hostName language:languageName]; if(!conversation) { NSLog(@"Unable to connect to %@@%@", environmentName, hostName); return; } } else { /* User wants local temporary environment */ if(!typeName || [typeName isEqualToString:@""]) { environment = [STEnvironment environmentWithDefaultDescription]; } else { desc = [STEnvironmentDescription descriptionWithName:typeName]; environment = [STEnvironment environmentWithDescription:desc]; } /* Register basic objects: Environment, Transcript */ [environment setObject:environment forName:@"Environment"]; [environment loadModule:@"SimpleTranscript"]; [environment setCreatesUnknownObjects:YES]; /* FIXME: make this an option */ [environment setFullScriptingEnabled:YES]; conversation = [[STConversation alloc] initWithContext:environment language:languageName]; } } - (void)run { STShell *shell; [self parseArguments]; [self createConversation]; if(!languageName || [languageName isEqualToString:@""]) { languageName = [[STLanguageManager defaultManager] defaultLanguage]; } [conversation setLanguage:languageName]; shell = [[STShell alloc] initWithConversation:conversation]; [shell run]; NSDebugLog(@"Exiting StepTalk shell"); } - (void)printHelp { NSProcessInfo *info = [NSProcessInfo processInfo]; printf("%s - StepTalk shell\n" "Usage: %s [options]\n\n" "Options are:\n" " -help this text\n" " -language lang use language lang\n" " -environment env use scripting environment with name env\n" " -host host find environment on host\n" " -type desc use environment description with name 'desc'\n", [[info processName] cString],[[info processName] cString] ); } @end int main(int argc, const char **argv) { NSAutoreleasePool *pool; STShellTool *tool; pool = [NSAutoreleasePool new]; tool = [[STShellTool alloc] init]; [tool run]; RELEASE(pool); return 0; }
6,748
Common Lisp
.l
210
23.433333
84
0.589197
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
7de93e66cd8f317a3c52970899b64975bc64c2601bf8939491fa21f5777e25f8
10,529
[ -1 ]
10,530
STShell.h
benkard_toilet/StepTalkShell/STShell.h
/** STShell StepTalk Shell Copyright (c) 2002 Free Software Foundation Written by: Stefan Urbanek <[email protected]> Date: 2002 May 29 This file is part of the StepTalk project. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02111, USA. */ #import <Foundation/NSObject.h> @class STConversation; @class STEnvironment; @class STScriptsManager; @class NSMutableArray; @class NSException; @interface STShell:NSObject { STScriptsManager *scriptsManager; STConversation *conversation; NSString *prompt; NSString *source; NSMutableArray *objectStack; BOOL exitRequest; BOOL updateCompletionList; NSArray *completionList; BOOL completionEnabled; } - initWithEnvironment:(STEnvironment *)env; - (void)setLanguage:(NSString *)langName; - (void)setEnvironment:(STEnvironment *)newEnv; - (STEnvironment *)environment; - (void)run; - show:(id)anObject; - showLine:(id)anObject; - (id)executeLine:(NSString *)line; - showResult:(id)obj; - showException:(NSException *)exception; - (void)showError:(NSString *)errString; @end @interface STShell(STShellOutput) - show:(id)anObject; - showLine:(id)anObject; - showResult:(id)obj; - (char *)displayCStringForObject:(id)object; - showException:(NSException *)exception; - (id)listObjects; @end
2,040
Common Lisp
.l
57
32.175439
72
0.736462
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
909da894e81592fd73a1270c37cc4b2ebb68b0f173f5f21335d36028f256a3ea
10,530
[ -1 ]
10,531
all-wcprops
benkard_toilet/StepTalkShell/.svn/all-wcprops
K 25 svn:wc:ra_dav:version-url V 62 /svn/gnustep/!svn/ver/21700/libs/steptalk/trunk/Examples/Shell END Unix.txt K 25 svn:wc:ra_dav:version-url V 71 /svn/gnustep/!svn/ver/16926/libs/steptalk/trunk/Examples/Shell/Unix.txt END STShell.h K 25 svn:wc:ra_dav:version-url V 72 /svn/gnustep/!svn/ver/21700/libs/steptalk/trunk/Examples/Shell/STShell.h END STShell+output.m K 25 svn:wc:ra_dav:version-url V 79 /svn/gnustep/!svn/ver/13926/libs/steptalk/trunk/Examples/Shell/STShell+output.m END AppKit.txt K 25 svn:wc:ra_dav:version-url V 73 /svn/gnustep/!svn/ver/16927/libs/steptalk/trunk/Examples/Shell/AppKit.txt END stshell_tool.m K 25 svn:wc:ra_dav:version-url V 77 /svn/gnustep/!svn/ver/21700/libs/steptalk/trunk/Examples/Shell/stshell_tool.m END ChangeLog K 25 svn:wc:ra_dav:version-url V 72 /svn/gnustep/!svn/ver/21700/libs/steptalk/trunk/Examples/Shell/ChangeLog END GNUmakefile K 25 svn:wc:ra_dav:version-url V 74 /svn/gnustep/!svn/ver/16959/libs/steptalk/trunk/Examples/Shell/GNUmakefile END STShell.m K 25 svn:wc:ra_dav:version-url V 72 /svn/gnustep/!svn/ver/21700/libs/steptalk/trunk/Examples/Shell/STShell.m END .cvsignore K 25 svn:wc:ra_dav:version-url V 73 /svn/gnustep/!svn/ver/14479/libs/steptalk/trunk/Examples/Shell/.cvsignore END README K 25 svn:wc:ra_dav:version-url V 69 /svn/gnustep/!svn/ver/16028/libs/steptalk/trunk/Examples/Shell/README END
1,357
Common Lisp
.l
65
19.876923
79
0.825077
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
f27217da090c28e44eb1ba7f4b2afb32ca973191dcc3ce642870e9df48c26480
10,531
[ -1 ]
10,532
stshell_tool.m.svn-base
benkard_toilet/StepTalkShell/.svn/text-base/stshell_tool.m.svn-base
/** stshell StepTalk Shell Copyright (c) 2002 Free Software Foundation Written by: Stefan Urbanek <[email protected]> Date: 2002 May 29 This file is part of the StepTalk project. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02111, USA. */ #import <StepTalk/StepTalk.h> #import "STShell.h" #import <Foundation/NSArray.h> #import <Foundation/NSAutoreleasePool.h> #import <Foundation/NSDebug.h> #import <Foundation/NSException.h> #import <Foundation/NSProcessInfo.h> #import <Foundation/NSString.h> @interface STShellTool:NSObject { STConversation *conversation; NSArray *arguments; unsigned int currentArg; NSString *environmentName; NSString *hostName; NSString *typeName; NSString *languageName; } - (int)parseArguments; - (NSString *)nextArgument; - (void)reuseArgument; - (void)run; - (void)printHelp; @end @implementation STShellTool - (int)parseArguments { NSString *arg; BOOL isOption = NO; arguments = [[NSProcessInfo processInfo] arguments]; [self nextArgument]; while( (arg = [self nextArgument]) ) { isOption = NO; if( [arg hasPrefix:@"--"] ) { arg = [arg substringFromIndex:2]; isOption = YES; } else if( [arg hasPrefix:@"-"] ) { arg = [arg substringFromIndex:1]; isOption = YES; } if ([@"help" hasPrefix:arg]) { [self printHelp]; return 1; } else if ([@"language" hasPrefix:arg]) { RELEASE(languageName); languageName = [self nextArgument]; if(!languageName) { [NSException raise:@"STShellToolException" format:@"Language name expected"]; } } else if ([@"environment" hasPrefix:arg]) { RELEASE(environmentName); environmentName = [self nextArgument]; if(!environmentName) { [NSException raise:@"STShellToolException" format:@"Environment name expected"]; } } else if ([@"host" hasPrefix:arg]) { RELEASE(hostName); hostName = [self nextArgument]; if(!hostName) { [NSException raise:@"STShellToolException" format:@"Host name expected"]; } } else if ([@"type" hasPrefix:arg]) { RELEASE(typeName); typeName = [self nextArgument]; if(!typeName) { [NSException raise:@"STShellToolException" format:@"Environment description (type) name expected"]; } } else if(!isOption) { break; } } if(arg) { [self reuseArgument]; } return 0; } - (NSString *)nextArgument { if(currentArg < [arguments count]) { return [arguments objectAtIndex:currentArg++]; } return nil; } - (void)reuseArgument { currentArg--; } /* Method taken from stexec.m - look there for updates */ - (void)createConversation { STEnvironmentDescription *desc; STEnvironment *environment; if(environmentName) { /* user wants to connect to a distant environment */ conversation = [[STRemoteConversation alloc] initWithEnvironmentName:environmentName host:hostName language:languageName]; if(!conversation) { NSLog(@"Unable to connect to %@@%@", environmentName, hostName); return; } } else { /* User wants local temporary environment */ if(!typeName || [typeName isEqualToString:@""]) { environment = [STEnvironment environmentWithDefaultDescription]; } else { desc = [STEnvironmentDescription descriptionWithName:typeName]; environment = [STEnvironment environmentWithDescription:desc]; } /* Register basic objects: Environment, Transcript */ [environment setObject:environment forName:@"Environment"]; [environment loadModule:@"SimpleTranscript"]; [environment setCreatesUnknownObjects:YES]; /* FIXME: make this an option */ [environment setFullScriptingEnabled:YES]; conversation = [[STConversation alloc] initWithContext:environment language:languageName]; } } - (void)run { STShell *shell; [self parseArguments]; [self createConversation]; if(!languageName || [languageName isEqualToString:@""]) { languageName = [[STLanguageManager defaultManager] defaultLanguage]; } [conversation setLanguage:languageName]; shell = [[STShell alloc] initWithConversation:conversation]; [shell run]; NSDebugLog(@"Exiting StepTalk shell"); } - (void)printHelp { NSProcessInfo *info = [NSProcessInfo processInfo]; printf("%s - StepTalk shell\n" "Usage: %s [options]\n\n" "Options are:\n" " -help this text\n" " -language lang use language lang\n" " -environment env use scripting environment with name env\n" " -host host find environment on host\n" " -type desc use environment description with name 'desc'\n", [[info processName] cString],[[info processName] cString] ); } @end int main(int argc, const char **argv) { NSAutoreleasePool *pool; STShellTool *tool; pool = [NSAutoreleasePool new]; tool = [[STShellTool alloc] init]; [tool run]; RELEASE(pool); return 0; }
6,748
Common Lisp
.l
210
23.433333
84
0.589197
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
fd7bb6b83968f558e55b7beeafe93e8dc0cce82e63926a8b77d21d48492988be
10,532
[ -1 ]
10,533
STShell+output.m.svn-base
benkard_toilet/StepTalkShell/.svn/text-base/STShell+output.m.svn-base
/** STShell+output Copyright (c) 2002 Free Software Foundation Written by: Stefan Urbanek <[email protected]> Date: 2002 Jun 7 This file is part of the StepTalk project. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02111, USA. */ #import "STShell.h" #import <StepTalk/StepTalk.h> #import <Foundation/NSArray.h> #import <Foundation/NSBundle.h> #import <Foundation/NSDebug.h> #import <Foundation/NSNotification.h> #import <Foundation/NSException.h> #import <Foundation/NSSet.h> #import <Foundation/NSString.h> #import <Foundation/NSValue.h> #include <readline/readline.h> @implementation STShell(STShellOutput) - show:(id)anObject { printf("%s", [[anObject description] cString]); return self; } - showLine:(id)anObject { [self show:anObject]; putchar('\n'); return nil; } - (void)showError:(NSString *)errString { fprintf(stderr, "%s\n\n", [errString cString]); } - showResult:(id)obj { const char *className = [NSStringFromClass([obj class]) cString]; int objIndex = [objectStack count] - 1; int i; if(obj) { if([obj isKindOfClass:[NSArray class]]) { printf("(%i) %s\n", objIndex, className); for(i = 0;i<[obj count]; i++) { printf("%i %s\n", i, [self displayCStringForObject:[obj objectAtIndex:i]]); } } else if([obj isKindOfClass:[NSSet class]]) { printf("(%i) %s\n", objIndex, className); obj = [[obj allObjects] sortedArrayUsingSelector:@selector(compare:)]; for(i = 0;i<[obj count]; i++) { printf("%s\n", [self displayCStringForObject:[obj objectAtIndex:i]]); } } else if([obj isKindOfClass:[NSDictionary class]]) { NSString *key; NSArray *keys; printf("(%i) %s\n", objIndex, className); keys = [[obj allKeys] sortedArrayUsingSelector:@selector(compare:)]; for(i = 0;i<[keys count]; i++) { key = [keys objectAtIndex:i]; printf("%s : %s\n", [self displayCStringForObject:key], [self displayCStringForObject:[obj objectForKey:key]]); } } else { printf("(%i) %s\n", objIndex, [self displayCStringForObject:obj]); } } return self; } - (char *)displayCStringForObject:(id)object { NSString *str = [object description]; if( [str length] > 60 ) { str = [str substringToIndex:60]; str = [str stringByAppendingString:@"..."]; } return [str cString]; } - showException:(NSException *)exception { printf("Error (%s): %s\n", [[exception name] cString], [[exception reason] cString]); return self; } - (id)listObjects { NSString *str; int i; id object; printf("Objects\n"); for(i = 0; i < [objectStack count]; i++) { object = [objectStack objectAtIndex:i]; str = [object description]; if( [str length] > 60 ) { str = [str substringToIndex:60]; str = [str stringByAppendingString:@"..."]; } printf("%4i: '%s' (%s)\n", i, [str cString], [[[object class] description] cString]); } return nil; } @end
4,276
Common Lisp
.l
131
24.335878
82
0.590749
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
881e1eb733ee8b9a811358e5213b3aff50efc05d451275876e1ff3c5cc66c209
10,533
[ -1 ]
10,534
STShell.h.svn-base
benkard_toilet/StepTalkShell/.svn/text-base/STShell.h.svn-base
/** STShell StepTalk Shell Copyright (c) 2002 Free Software Foundation Written by: Stefan Urbanek <[email protected]> Date: 2002 May 29 This file is part of the StepTalk project. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02111, USA. */ #import <Foundation/NSObject.h> @class STConversation; @class STEnvironment; @class STScriptsManager; @class NSMutableArray; @class NSException; @interface STShell:NSObject { STScriptsManager *scriptsManager; STConversation *conversation; NSString *prompt; NSString *source; NSMutableArray *objectStack; BOOL exitRequest; BOOL updateCompletionList; NSArray *completionList; BOOL completionEnabled; } - initWithEnvironment:(STEnvironment *)env; - (void)setLanguage:(NSString *)langName; - (void)setEnvironment:(STEnvironment *)newEnv; - (STEnvironment *)environment; - (void)run; - show:(id)anObject; - showLine:(id)anObject; - (id)executeLine:(NSString *)line; - showResult:(id)obj; - showException:(NSException *)exception; - (void)showError:(NSString *)errString; @end @interface STShell(STShellOutput) - show:(id)anObject; - showLine:(id)anObject; - showResult:(id)obj; - (char *)displayCStringForObject:(id)object; - showException:(NSException *)exception; - (id)listObjects; @end
2,040
Common Lisp
.l
57
32.175439
72
0.736462
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
db73a70db67f85b7d454e8e7fe34a8b76b808a9c3a40c7306352f771ea18e1e3
10,534
[ -1 ]
10,535
GNUmakefile.svn-base
benkard_toilet/StepTalkShell/.svn/text-base/GNUmakefile.svn-base
# # StepTalk tools # # Copyright (C) 2002 Stefan Urbanek # # This file is part of the StepTalk. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Library General Public License for more details. # # You should have received a copy of the GNU Library General Public # License along with this library; if not, write to the Free # Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02111, USA. # include $(GNUSTEP_MAKEFILES)/common.make TOOL_NAME = stshell stshell_OBJC_FILES = STShell.m STShell+output.m stshell_tool.m ADDITIONAL_TOOL_LIBS += -lStepTalk -lreadline -lncurses ADDITIONAL_OBJCFLAGS = -Wall -Wno-import -include GNUmakefile.preamble include $(GNUSTEP_MAKEFILES)/tool.make -include GNUMakefile.postamble
1,149
Common Lisp
.l
29
38.413793
69
0.782765
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
e1de78bca4ba1e94aa5324c489e3a9126f3d2ba4ed12df3a9b839e6af71a63ff
10,535
[ -1 ]
10,536
STShell.m.svn-base
benkard_toilet/StepTalkShell/.svn/text-base/STShell.m.svn-base
/** STShell StepTalk Shell Copyright (c) 2002 Free Software Foundation Written by: Stefan Urbanek <[email protected]> Date: 2002 May 29 This file is part of the StepTalk project. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02111, USA. */ #import "STShell.h" #import <StepTalk/StepTalk.h> #import <Foundation/NSArray.h> #import <Foundation/NSBundle.h> #import <Foundation/NSDebug.h> #import <Foundation/NSNotification.h> #import <Foundation/NSException.h> #import <Foundation/NSFileManager.h> #import <Foundation/NSSet.h> #import <Foundation/NSString.h> #import <Foundation/NSValue.h> #include <readline/readline.h> static Class NSString_class; static Class NSNumber_class; NSArray *objcSelectors = nil; static STShell *sharedShell = nil; @interface STShell(STPrivateMethods) - (int) completion; - (NSString *)readLine; - (void)initReadline; @end int complete_handler(void) { return [sharedShell completion]; } @implementation STShell + (void)initialize { NSString_class = [NSString class]; NSNumber_class = [NSNumber class]; } + sharedShell { return sharedShell; } - initWithConversation:(STConversation *)conv { self = [super init]; [self initReadline]; objectStack = [[NSMutableArray alloc] init]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bundleLoaded:) name:NSBundleDidLoadNotification object:nil]; scriptsManager = RETAIN([STScriptsManager defaultManager]); prompt = @"StepTalk > "; conversation = RETAIN(conv); /* FIXME: make this more clever for completion handler */ if(!sharedShell) { sharedShell = self; } return self; } - (void)updateCompletionList { NSMutableArray *array = [[NSMutableArray alloc] init]; RELEASE(completionList); [array addObjectsFromArray:STAllObjectiveCSelectors()]; completionList = [[NSArray alloc] initWithArray:array]; updateCompletionList = NO; } - (void)dealloc { RELEASE(objectStack); RELEASE(completionList); RELEASE(scriptsManager); RELEASE(conversation); [[NSNotificationCenter defaultCenter] removeObserver:self]; [super dealloc]; } -(void)bundleLoaded:(NSNotification *)notif { updateCompletionList = YES; } - (void)initReadline { rl_initialize(); rl_bind_key('\t', complete_handler); } - (void)setLanguage:(NSString *)langName { NSDebugLog(@"Setting language to %@", langName); [conversation setLanguage:langName]; } - (void)setEnvironment:(STEnvironment *)newEnv { [conversation setEnvironment:newEnv]; } - (STEnvironment *)environment { return [conversation context]; } - (void)run { STEnvironment *env; NSString *line; id result; [self showLine:@"Welcome to the StepTalk shell."]; // NSLog(@"Environment %@", env); if(![conversation isKindOfClass:[STRemoteConversation class]]) { completionEnabled = YES; } else { [self showLine:@"Note: Completion disabled for distant conversation"]; } while(1) { line = [self readLine]; if(exitRequest) break; if(!line) continue; result = [self executeLine:line]; if(result) { if(result != objectStack) { [objectStack addObject:result]; } [self showResult:result]; } else { [self showResult:result]; } } printf("\n"); } - (id)executeLine:(NSString *)line { NSString *cmd; id result = nil; /* FIXME: why? */ cmd = [line stringByAppendingString:@" "]; NS_DURING [conversation interpretScript:cmd]; result = [conversation result]; NS_HANDLER [self showException:localException]; NS_ENDHANDLER return result; } - (NSString *)readLine { char *str; NSString *actualPrompt = prompt; NSString *line = @""; BOOL done = NO; int len; while(!done) { str = readline([actualPrompt cString]); done = YES; if(!str) { exitRequest = YES; return nil; } len = strlen(str); if(!len) return nil; if(str[len-1] == '\\') { actualPrompt = @"... ? "; str[strlen(str) - 1] = '\0'; done = NO; } line = [line stringByAppendingString:[NSString stringWithCString:str]]; } add_history([line cString]); return line; } - (int)completion { STEnvironment *env; NSEnumerator *enumerator; NSMutableSet *set; NSString *match; NSString *tail; NSString *str; NSArray *array; int pos = 0; int c; if(!completionEnabled) { return 0; } if(rl_point <= 0) { return 0; } pos = rl_point - 1; c = rl_line_buffer[pos]; while((isalnum(c) || c == '_') && pos >= 0) { pos--; c = rl_line_buffer[pos]; } pos++; match = [NSString stringWithCString:rl_line_buffer + pos length:rl_point - pos]; set = [NSMutableSet set]; if(!completionList || updateCompletionList) { [self updateCompletionList]; } enumerator = [completionList objectEnumerator]; while( (str = [enumerator nextObject]) ) { if( [str hasPrefix:match] ) { [set addObject:str]; } } env = [conversation context]; enumerator = [[env knownObjectNames] objectEnumerator]; while( (str = [enumerator nextObject]) ) { if( [str hasPrefix:match] ) { [set addObject:str]; } } array = [set allObjects]; if( [array count] == 0 ) { printf("\nNo match for completion.\n"); rl_forced_update_display(); } else if ( [array count] == 1 ) { str = [array objectAtIndex:0]; str = [str substringFromIndex:rl_point - pos]; rl_insert_text([str cString]); rl_insert_text(" "); rl_redisplay(); } else { enumerator = [array objectEnumerator]; tail = [enumerator nextObject]; while( (str = [enumerator nextObject]) ) { tail = [str commonPrefixWithString:tail options:NSLiteralSearch]; } tail = [tail substringFromIndex:[match length]]; if( tail && ![tail isEqualToString:@""] ) { rl_insert_text([tail cString]); rl_redisplay(); } else { printf("\n"); enumerator = [array objectEnumerator]; while( (str = [enumerator nextObject]) ) { printf("%s\n", [str cString]); } rl_forced_update_display(); } } return 0; } - (void)exit { /* FIXME: this is not nice */ exit(0); } - (id)executeScriptNamed:(NSString *)scriptName { STScript *script = [scriptsManager scriptWithName:scriptName]; id result = nil; if(!script) { [self showError:[NSString stringWithFormat: @"Unable to find script with name '%@'", scriptName]]; } else { NS_DURING result = [conversation runScriptFromString:[script source]]; NS_HANDLER [self showException:localException]; NS_ENDHANDLER } return result; } - (void)setPrompt:(NSString *)aString { ASSIGN(prompt, aString); } - (NSString *)prompt { return prompt; } @end
8,640
Common Lisp
.l
321
20.05919
80
0.601062
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
7f8a48bd1092284edc0d3c1c879dc68c5e3c0be58d7d3fbedb0e8bf5c7d8536c
10,536
[ -1 ]
10,537
stshell_tool.m.svn-base
benkard_toilet/StepTalkShell/.svn/prop-base/stshell_tool.m.svn-base
K 15 cvs2svn:cvs-rev V 3 1.3 K 13 svn:eol-style V 6 native K 12 svn:keywords V 23 Author Date Id Revision END
110
Common Lisp
.l
13
7.461538
23
0.845361
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
28e69cebc672381f701493f7541035a5d9a88b0a0260ad36f3f36965875e1532
10,537
[ -1 ]
10,539
STShell.h.svn-base
benkard_toilet/StepTalkShell/.svn/prop-base/STShell.h.svn-base
K 15 cvs2svn:cvs-rev V 3 1.9 K 13 svn:eol-style V 6 native K 12 svn:keywords V 23 Author Date Id Revision END
110
Common Lisp
.l
13
7.461538
23
0.845361
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
eed9365326331feda299af5ed56b02b6b7c529ecc19a940539c762a5a54c1742
10,539
[ -1 ]
10,540
GNUmakefile.svn-base
benkard_toilet/StepTalkShell/.svn/prop-base/GNUmakefile.svn-base
K 15 cvs2svn:cvs-rev V 3 1.8 K 13 svn:eol-style V 6 native K 12 svn:keywords V 23 Author Date Id Revision END
110
Common Lisp
.l
13
7.461538
23
0.845361
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
f5e54c5377fa5f6a9e94de975adea2af04a97429c05c8f78a73da84ee442a897
10,540
[ -1 ]
10,541
STShell.m.svn-base
benkard_toilet/StepTalkShell/.svn/prop-base/STShell.m.svn-base
K 15 cvs2svn:cvs-rev V 4 1.18 K 13 svn:eol-style V 6 native K 12 svn:keywords V 23 Author Date Id Revision END
111
Common Lisp
.l
13
7.538462
23
0.846939
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
02b643daca635ab58178b21fdb19c46adce6926760d5640240abcc24ae304332
10,541
[ -1 ]
10,568
must-loop.patch
benkard_toilet/Sacla/tests/must-loop.patch
*** sacla/lisp/test/must-loop.lisp 2004-08-03 08:34:55.000000000 +0200 --- CLISP/clisp-20040712/sacla-tests/must-loop.lisp 2004-08-06 02:49:13.000000000 +0200 *************** *** 1195,1200 **** --- 1195,1202 ---- do (incf x) initially (incf x) (incf x) finally (incf x) (return (incf x))) 7) + #-CLISP ; unfounded expectations about the value of for-as iteration variables + ; in INITIALLY and FINALLY clauses (equal (let (val) (loop for a downto 3 from 100 for b in '(x y z) and c = 50 then (1+ c) initially (setq val (list a b c))
622
Common Lisp
.l
13
40.615385
87
0.581281
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
5f8be13f86d30c9335c90475a908dfa39c862474477530428fb9f4d91dd8637c
10,568
[ -1 ]
10,574
should-array.patch
benkard_toilet/Sacla/tests/should-array.patch
*** sacla/lisp/test/should-array.lisp 2004-08-03 08:34:55.000000000 +0200 --- CLISP/clisp-20040712/sacla-tests/should-array.lisp 2004-08-06 03:27:42.000000000 +0200 *************** *** 31,43 **** (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (progn ! #-(or cmu clisp) (HANDLER-CASE (PROGN (ADJUSTABLE-ARRAY-P "not-a-symbol")) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) ! #+(or cmu clisp) 'skipped) (progn #-cmu --- 31,44 ---- (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) + #-CLISP ; Why expect an error? A string _is_ an array. (progn ! #-(or cmu clispxxx) (HANDLER-CASE (PROGN (ADJUSTABLE-ARRAY-P "not-a-symbol")) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) ! #+(or cmu clispxxx) 'skipped) (progn #-cmu
940
Common Lisp
.l
28
29.428571
90
0.611111
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
96c0a9cf063ac2f78a859db513302de1a17c36a491b5b30695aba2941209dd2d
10,574
[ -1 ]
10,579
must-hash-table.patch
benkard_toilet/Sacla/tests/must-hash-table.patch
*** sacla/lisp/test/must-hash-table.lisp 2004-08-03 08:34:54.000000000 +0200 --- CLISP/clisp-20040712/sacla-tests/must-hash-table.lisp 2004-08-06 02:45:56.000000000 +0200 *************** *** 42,52 **** --- 42,54 ---- (make-hash-table) (hash-table-p (make-hash-table)) + #-CLISP ; unfounded expectations about hash-table-test (dolist (test '(eq eql equal equalp) t) (let ((hash-table (make-hash-table :test test))) (unless (and (hash-table-p hash-table) (eq (hash-table-test hash-table) test)) (return nil)))) + #-CLISP ; unfounded expectations about hash-table-test (dolist (test '(eq eql equal equalp) t) (let* ((test-function (symbol-function test)) (hash-table (make-hash-table :test test-function))) *************** *** 114,135 **** --- 116,148 ---- (= (hash-table-count table) 1))) + #-CLISP ; unfounded expectations about hash-table-rehash-size (let ((table (make-hash-table :size 100 :rehash-size 1.4))) (= (hash-table-rehash-size table) 1.4)) + #-CLISP ; unfounded expectations about hash-table-rehash-threshold (let ((table (make-hash-table :size 100 :rehash-threshold 0.5))) (= (hash-table-rehash-threshold table) 0.5)) (<= 0 (hash-table-size (make-hash-table))) + #-CLISP ; unfounded expectations about hash-table-test (eq 'eq (hash-table-test (make-hash-table :test 'eq))) + #-CLISP ; unfounded expectations about hash-table-test (eq 'eq (hash-table-test (make-hash-table :test #'eq))) + #-CLISP ; unfounded expectations about hash-table-test (eq 'eql (hash-table-test (make-hash-table))) + #-CLISP ; unfounded expectations about hash-table-test (eq 'eql (hash-table-test (make-hash-table :test 'eql))) + #-CLISP ; unfounded expectations about hash-table-test (eq 'eql (hash-table-test (make-hash-table :test #'eql))) + #-CLISP ; unfounded expectations about hash-table-test (eq 'equal (hash-table-test (make-hash-table :test 'equal))) + #-CLISP ; unfounded expectations about hash-table-test (eq 'equal (hash-table-test (make-hash-table :test #'equal))) + #-CLISP ; unfounded expectations about hash-table-test (eq 'equalp (hash-table-test (make-hash-table :test 'equalp))) + #-CLISP ; unfounded expectations about hash-table-test (eq 'equalp (hash-table-test (make-hash-table :test #'equalp))) (let* ((table0 (make-hash-table))
2,367
Common Lisp
.l
47
46.702128
93
0.678416
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
c4b2a9e5b97d90c5a9fab0b831ef32186e59b382a304586c04f758741db362a2
10,579
[ -1 ]
10,580
must-eval.patch
benkard_toilet/Sacla/tests/must-eval.patch
*** sacla/lisp/test/must-eval.lisp 2004-08-03 08:34:54.000000000 +0200 --- CLISP/clisp-20040712/sacla-tests/must-eval.lisp 2004-08-06 02:38:25.000000000 +0200 *************** *** 36,40 **** (every #'special-operator-p '(block catch eval-when flet function go if labels let let* load-time-value locally macrolet multiple-value-call multiple-value-prog1 progn progv quote return-from setq symbol-macrolet tagbody the throw unwind-protect)) (not (special-operator-p 'car)) (not (special-operator-p 'cdr)) ! (not (special-operator-p 'cond)) (not (special-operator-p 'values)) --- 36,40 ---- (every #'special-operator-p '(block catch eval-when flet function go if labels let let* load-time-value locally macrolet multiple-value-call multiple-value-prog1 progn progv quote return-from setq symbol-macrolet tagbody the throw unwind-protect)) (not (special-operator-p 'car)) (not (special-operator-p 'cdr)) ! #-CLISP (not (special-operator-p 'cond)) (not (special-operator-p 'values))
993
Common Lisp
.l
15
64.133333
249
0.734151
benkard/toilet
11
0
0
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
5028a16ae132b02e7adceaa675d37dac34994a4030599a3c715e2171ac185582
10,580
[ -1 ]
10,609
suite.lisp
anwyn_cl-horde3d/test/suite.lisp
;;; suite.lisp --- Main test suite for the horde3d wrappers ;;; _ _ ;;; ___ _ _(_) |_ ___ ;;; / __| | | | | __/ _ \ ;;; \__ \ |_| | | || __/ ;;; |___/\__,_|_|\__\___| ;;; ;;; Copyright (C) 2009 Ole Arndt <[email protected]> ;;; (defpackage :horde3d-test (:use :common-lisp :stefil :horde3d)) (in-package :horde3d-test) (defsuite* horde3d-tests) ;;; suite.lisp ends here
396
Common Lisp
.lisp
14
26.714286
59
0.49734
anwyn/cl-horde3d
15
0
0
EPL-1.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
f5f2a505a231abe263a3ad56f816f9c9e5563de48a56b2ddbf4e4362c46931f0
10,609
[ -1 ]
10,610
gen-binding.lisp
anwyn_cl-horde3d/tools/gen-binding.lisp
;;; gen-binding.lisp --- generate the horde3d low level bindings ;;; _ _ _ _ ;;; __ _ ___ _ __ | |__ (_)_ __ __| (_)_ __ __ _ ;;; / _` |/ _ \ '_ \ _____| '_ \| | '_ \ / _` | | '_ \ / _` | ;;; | (_| | __/ | | |_____| |_) | | | | | (_| | | | | | (_| | ;;; \__, |\___|_| |_| |_.__/|_|_| |_|\__,_|_|_| |_|\__, | ;;; |___/ |___/ ;;; ;;; Copyright (C) 2009 Ole Arndt <[email protected]> ;;; (in-package :cl-user) (eval-when (:compile-toplevel :load-toplevel :execute) (require :asdf)) (eval-when (:compile-toplevel :load-toplevel :execute) (asdf:operate 'asdf:load-op :verrazano)) (in-package :verrazano-user) (defun generate-binding* (name headers &rest args &key (working-directory (verrazano::system-relative-pathname :horde3d "src/")) (gccxml-flags "-I/usr/include") &allow-other-keys) (format *debug-io* "~%~%; *** Processing binding ~S~%" name) (remove-from-plistf args :working-directory :gccxml-flags) (block try (handler-bind ((serious-condition (lambda (error) (warn "Failed to generated binding for ~S, error: ~A" name error) (return-from try)))) (let ((*print-right-margin* 100)) (generate-binding (append (list :cffi :package-name name :input-files headers :working-directory working-directory :gccxml-flags gccxml-flags) args) :keep-temporary-files nil)))) (values)) (defun generate-opengl-binding () (generate-binding* :opengl-cffi-bindings '("GL/gl.h" "GL/glu.h" "GL/glut.h") :standard-name-transformer-replacements ;; transform "3DFoo" patterns (in names like "gluBuild3DMipmaps" => glu-build-3d-mipmaps) `(,(cl-ppcre:create-scanner "([a-z][1-3]D)([A-Z])") ,(lambda (original start end match-start match-end reg-starts reg-ends) (declare (ignore start end match-start match-end)) (flet ((match-group (position) (subseq original (elt reg-starts position) (elt reg-ends position)))) (concatenate 'string (string-downcase (match-group 0)) "-" (string-downcase (match-group 1)))))))) (defun generate-openal-binding () (generate-binding* :openal-cffi-bindings '("AL/al.h" "AL/alut.h" "AL/alc.h") #+win32 :gccxml-flags #+win32 "--gccxml-compiler bcc32 -IC:\\openal\\include\\")) (defun generate-horde3d-binding () (generate-binding* :horde3d-binding '("Horde3D.h" "Horde3DUtils.h") :gccxml-node-types-to-output '(gccxml:typedef) #+unix :gccxml-flags #+unix "-I/home/ole/src/graphics/Horde3D/Horde3D/Bindings/C++/")) ;;; gen-binding.lisp ends here
3,139
Common Lisp
.lisp
70
34.128571
93
0.494114
anwyn/cl-horde3d
15
0
0
EPL-1.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
9e602cd9569403b8c095622181b643392701ae98091d194a1f9d7f11d3e2876b
10,610
[ -1 ]
10,611
package.lisp
anwyn_cl-horde3d/examples/package.lisp
;;; package.lisp --- package for the horde3d examples ;;; _ ;;; _ __ __ _ ___| | ____ _ __ _ ___ ;;; | '_ \ / _` |/ __| |/ / _` |/ _` |/ _ \ ;;; | |_) | (_| | (__| < (_| | (_| | __/ ;;; | .__/ \__,_|\___|_|\_\__,_|\__, |\___| ;;; |_| |___/ ;;; ;;; Copyright (C) 2009 Ole Arndt <[email protected]> ;;; (in-package :cl-user) (defpackage #:horde3d-examples (:use #:common-lisp #:horde3d) (:export #:knight #:chicago)) ;;; package.lisp ends here
514
Common Lisp
.lisp
16
30
55
0.357576
anwyn/cl-horde3d
15
0
0
EPL-1.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
3e58408ad43b0ca5ea6ed085014af11f1ca61451b8419e2d65fbc4af95563238
10,611
[ -1 ]
10,612
knight.lisp
anwyn_cl-horde3d/examples/knight.lisp
;;; knight.lisp --- The knight example from the horde3d distribution ;;; _ _ _ _ ;;; | | ___ __ (_) __ _| |__ | |_ ;;; | |/ / '_ \| |/ _` | '_ \| __| ;;; | <| | | | | (_| | | | | |_ ;;; |_|\_\_| |_|_|\__, |_| |_|\__| ;;; |___/ ;;; ;;; Copyright (C) 2009 Ole Arndt <[email protected]> ;;; (in-package :horde3d-examples) (defclass knight-application (example-application) ((%particle-sys-node :accessor particle-sys-node :initarg :particle-sys-node) (%knight-node :accessor knight-node :initarg :knight-node))) (defun knight () (example-main-sdl (make-instance 'knight-application :viewer-position (make-array 3 :element-type 'single-float :initial-contents '(5.0 3.0 19.0)) :viewer-orientation (make-array 3 :element-type 'single-float :initial-contents '(7.0 15.0 0.0)) :stat-mode 2 :anim-weight 0.0 :content-path (merge-pathnames (make-pathname :directory '(:relative "Horde3D" "Binaries" "Content")) *horde3d-home-directory*)) :width 800 :height 600 :caption "Knight - Horde3D Sample")) (defmethod app-init ((app knight-application)) ;; Add resources (let ((hdr-pipeline (h3d:add-resource :pipeline "pipelines/hdr.pipeline.xml" 0)) (env-res (h3d:add-resource :scene-graph "models/sphere/sphere.scene.xml" 0)) (knight-res (h3d:add-resource :scene-graph "models/knight/knight.scene.xml" 0)) (knight-anim-res-1 (h3d:add-resource :animation "animations/knight_order.anim" 0)) (knight-anim-res-2 (h3d:add-resource :animation "animations/knight_attack.anim" 0)) (particle-sys-res (h3d:add-resource :scene-graph "particles/particleSys1/particleSys1.scene.xml" 0))) ;; Load resources (h3d:load-resources-from-disk (namestring (content-path app))) (setf (hdr-pipeline app) hdr-pipeline) ;; add camera (setf (camera-node app) (h3d:add-camera-node h3d:+root-node+ "Camera" hdr-pipeline)) (let ((env (h3d:add-nodes h3d:+root-node+ env-res)) (knight (h3d:add-nodes h3d:+root-node+ knight-res))) (setf (knight-node app) knight) (h3d:set-node-transform env 0 -20 0 0 0 0 20 20 20) (h3d:set-node-transform knight 0 0 0 0 180 0 0.1 0.1 0.1) (h3d:setup-model-animation-stage knight 0 knight-anim-res-1 0 "" nil) (h3d:setup-model-animation-stage knight 1 knight-anim-res-2 0 "" nil) ;; add particles to hand (h3d:find-nodes knight "Bip01_R_Hand" :joint) (let ((particle-sys-node (h3d:add-nodes (h3d:get-node-find-result 0) particle-sys-res))) (setf (particle-sys-node app) particle-sys-node) (h3d:set-node-transform particle-sys-node 0 40 0 90 0 0 1 1 1)))) ;; Add light source (let ((light (h3d:add-light-node h3d:+root-node+ "Light1" 0 "LIGHTING" "SHADOWMAP"))) (h3d:set-node-transform light 0 15 10 -60 0 0 1 1 1) (setf (h3d:node-parameter light :light-radius) 30 (h3d:node-parameter light :light-fov) 90 (h3d:node-parameter light :light-shadow-map-count) 1 (h3d:node-parameter light :light-shadow-map-bias) 0.01 (h3d:node-parameter light :light-color :component 0) 1.0 (h3d:node-parameter light :light-color :component 1) 0.8 (h3d:node-parameter light :light-color :component 2) 0.7 (h3d:node-parameter light :light-color-multiplier :component 0) 1.0)) ;; Customize post processing effects (let ((mat-res (h3d:find-resource :material "pipelines/postHDR.material.xml"))) (h3d:set-material-uniform mat-res "hdrExposure" 2.5 0.0 0.0 0.0) (h3d:set-material-uniform mat-res "hdrBrightThres" 0.5 0.0 0.0 0.0) (h3d:set-material-uniform mat-res "hdrBrightOffset" 0.08 0.0 0.0 0.0)) ;; Mark end of zero frame (h3d:finalize-frame)) (defmethod app-main-loop ((app knight-application)) (when (gethash :sdl-key-1 (keys app)) (incf (anim-weight app) (/ 2 (curr-fps app))) (when (> (anim-weight app) 1.0) (setf (anim-weight app) 1.0))) (when (gethash :sdl-key-2 (keys app)) (decf (anim-weight app) (/ 2 (curr-fps app))) (when (< (anim-weight app) 0.0) (setf (anim-weight app) 0.0))) (unless (freeze? app) (let ((inv-fps (/ 1.0 (curr-fps app)))) (incf (anim-time app) inv-fps) (h3d:set-model-animation-parameters (knight-node app) 0 (* 24.0 (anim-time app)) (anim-weight app)) (h3d:set-model-animation-parameters (knight-node app) 1 (* 24.0 (anim-time app)) (- 1.0 (anim-weight app))) (h3d:do-nodes (node :start-node (particle-sys-node app) :node-type :emitter) (h3d:advance-emitter-time node inv-fps)))) ;; Set camera parameters (with-accessors ((pos viewer-position) (rot viewer-orientation) (cam camera-node) (font font-resource) (panel panel-resource)) app (h3d:set-node-transform cam (aref pos 0) (aref pos 1) (aref pos 2) (aref rot 0) (aref rot 1) 0 1 1 1 ) (when (> (stat-mode app) 0) (h3d:show-frame-statistics font panel (stat-mode app)) ;; Display weight (h3d:show-text (format nil "Weight: ~a" (anim-weight app)) 0.03 0.24 0.026 1 1 1 font)) ;; Show logo (let* ((ww (float (/ (h3d:node-parameter cam :camera-viewport-width) (h3d:node-parameter cam :camera-viewport-height)))) (logo (make-array 16 :element-type 'single-float :initial-contents (list (- ww 0.4) 0.8 0.0 1.0 (- ww 0.4) 1.0 0.0 0.0 ww 1.0 1.0 0.0 ww 0.8 1.0 1.0)))) (h3d:show-overlays logo 4 1.0 1.0 1.0 1.0 (logo-resource app) 0)) ;; Render scene (h3d:render cam))) ;;; knight.lisp ends here
6,285
Common Lisp
.lisp
117
42.495726
109
0.567612
anwyn/cl-horde3d
15
0
0
EPL-1.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
bd5a88e355d9b3f335772b9f1ef6d42c1fe7e0c6c1401f80342ce660be4a2c35
10,612
[ -1 ]
10,613
chicago.lisp
anwyn_cl-horde3d/examples/chicago.lisp
;;; chicago.lisp --- horde3d example ;;; _ _ ;;; ___| |__ (_) ___ __ _ __ _ ___ ;;; / __| '_ \| |/ __/ _` |/ _` |/ _ \ ;;; | (__| | | | | (_| (_| | (_| | (_) | ;;; \___|_| |_|_|\___\__,_|\__, |\___/ ;;; |___/ ;;; ;;; Copyright (C) 2009 Ole Arndt <[email protected]> ;;; (in-package :horde3d-examples) (defclass particle () ((px :accessor px :initarg :px) (pz :accessor pz :initarg :pz) (dx :accessor dx :initarg :dx) (dz :accessor dz :initarg :dz) (fx :accessor fx :initarg :fx) (fz :accessor fz :initarg :fz) (ox :accessor ox :initarg :ox :initform 0.0) (oz :accessor oz :initarg :oz :initform 0.0) (node :accessor node :initarg :node :initform nil) (anim-time :accessor anim-time :initarg :anim-time :initform 0.0))) (defclass chicago-application (example-application) ((deferred-pipeline :accessor deferred-pipeline :initarg :deferred-pipeline) (particles :accessor particles :initarg :particles :initform (make-array 100 :element-type '(or particle null) :initial-element nil)))) (defun chicago () (example-main-sdl (make-instance 'chicago-application :viewer-position (make-array 3 :element-type 'single-float :initial-contents '(5.0 3.0 19.0)) :viewer-orientation (make-array 3 :element-type 'single-float :initial-contents '(7.0 15.0 0.0)) :stat-mode 2 :content-path (merge-pathnames (make-pathname :directory '(:relative "Horde3D" "Binaries" "Content")) *horde3d-home-directory*)) :width 800 :height 600 :caption "Chicago - Horde3D Sample")) (defun choose-destination (particle) (let ((ang (* 6.28 (/ (random 360.0) 360.0))) (rad (random 20.0))) (setf (dx particle) (* (sin ang) rad) (dz particle) (* (cos ang) rad)))) (defmethod app-init ((app chicago-application)) ;; Add resources (let ((env-res (h3d:add-resource :scene-graph "models/platform/platform.scene.xml")) (skybox-res (h3d:add-resource :scene-graph "models/skybox/skybox.scene.xml")) (light-mat-res (h3d:add-resource :material "materials/light.material.xml")) (deferred-pipeline (h3d:add-resource :pipeline "pipelines/deferred.pipeline.xml")) (char-res (h3d:add-resource :scene-graph "models/man/man.scene.xml")) (char-walk-res (h3d:add-resource :animation "animations/man.anim"))) ;; Load resources (h3d:load-resources-from-disk (namestring (content-path app))) (setf (hdr-pipeline app) deferred-pipeline) ;; add camera (setf (camera-node app) (h3d:add-camera-node h3d:+root-node+ "Camera" deferred-pipeline)) (h3d:set-node-transform (h3d:add-nodes h3d:+root-node+ env-res) 0 0 0 0 0 0 0.23 0.23 0.23) (h3d:set-node-transform (h3d:add-nodes h3d:+root-node+ skybox-res) 0 0 0 0 0 0 210 50 201) ;; Add light source (let ((light (h3d:add-light-node h3d:+root-node+ "Light1" light-mat-res "LIGHTING" "SHADOWMAP"))) (h3d:set-node-transform light 0 20 50 -30 0 0 1 1 1) (setf (h3d:node-parameter light :light-radius) 200 (h3d:node-parameter light :light-fov) 90 (h3d:node-parameter light :light-shadow-map-count) 3 (h3d:node-parameter light :light-shadow-split-lambda) 0.9 (h3d:node-parameter light :light-shadow-map-bias) 0.001 (h3d:node-parameter light :light-color :component 0) 0.9 (h3d:node-parameter light :light-color :component 1) 0.7 (h3d:node-parameter light :light-color :component 2) 0.75)) ;; initialize particles (dotimes (i (length (particles app))) (let ((p (make-instance 'particle :node (h3d:add-nodes h3d:+root-node+ char-res) :px (* 10.0 (sin (* 6.28 (float (/ i 100.0))))) :pz (* 10.0 (cos (* 6.28 (float (/ i 100.0)))))))) (h3d:setup-model-animation-stage (node p) 0 char-walk-res 0 "" nil) (choose-destination p) (h3d:set-node-transform (node p) (px p) 0.02 (pz p) 0 0 0 1 1 1) (setf (aref (particles app) i) p)))) ;; Mark end of frame (h3d:finalize-frame)) (defmethod app-main-loop ((app chicago-application)) (unless (freeze? app) (update-crowd app)) ;; Set camera parameters (with-accessors ((pos viewer-position) (rot viewer-orientation) (cam camera-node) (font font-resource) (panel panel-resource)) app (h3d:set-node-transform cam (aref pos 0) (aref pos 1) (aref pos 2) (aref rot 0) (aref rot 1) 0 1 1 1 ) (when (> (stat-mode app) 0) (h3d:show-frame-statistics font panel (stat-mode app)) ;; Display weight (h3d:show-text (format nil "Pipeline: ~a" (if (eql (h3d:node-parameter cam :camera-pipeline-resource) (fwd-pipeline app)) "forward" "deferred")) 0.03 0.24 0.026 1 1 1 font)) ;; Show logo ;; (h3d:show-overlay 0.75 0.8 0 1 0.75 1 0 0 ;; 1 1 1 0 1 0.8 1 1 ;; 1 1 1 1 (logo-resource app) 7) ;; Render scene (h3d:render cam))) (defun update-crowd (app) (let ((d1 0.25) (d2 2.0) (d3 4.5) (f1 3.0) (f2 1.0) (f3 0.1) (fps (curr-fps app))) (declare (type single-float d1 d2 d3 f1 f2 f3 fps) (optimize (speed 3) (safety 1))) (loop :for p :across (particles app) :do (let ((px (px p)) (pz (pz p)) (dx (dx p)) (dz (dz p)) (ox (ox p)) (oz (oz p)) (fx 0.0) (fz 0.0)) (declare (type single-float px pz dx dz ox oz fx fz)) ;; reset force (let ((dist (sqrt (+ (* (- dx px) (- dx px)) (* (- dz pz) (- dz pz)))))) (declare (type single-float dist)) (cond ((> dist 3.0) ;; destination not reached, walk towards destination (incf fx (* 0.035 (/ (- dx px) dist))) (incf fz (* 0.035 (/ (- dz pz) dist))) (loop :for p2 :across (particles app) :when (not (eq p p2)) :do (let* ((p2x (px p2)) (p2z (pz p2)) (dist2 (sqrt (+ (* (- px p2x) (- px p2x)) (* (- pz p2z) (- pz p2z))))) (strength (cond ((and (<= dist2 d3) (> dist2 d2)) (let* ((m (/ (- f3 0) (- d2 d3))) (n (- 0 (* m d3)))) (+ (* m dist2) n))) ((and (<= dist2 d2) (> dist2 d1)) (let* ((m (/ (- f2 f3) (- d1 d2))) (n (- f3 (* m d2)))) (+ (* m dist2) n))) ((<= dist2 d1) (let* ((m (/ (- f1 f2) (- 0 d1))) (n (- f2 (* m d1)))) (+ (* m dist2) n))) (t 0.0)))) (declare (type single-float p2x p2z dist strength)) (incf fx (* strength (the single-float (/ (- px p2x) dist2)))) (incf fz (* strength (the single-float (/ (- pz p2z) dist2))))))) (t ;; near destination, choose a new one (choose-destination p))) ;; make force framerate independant (setf fx (* fx (coerce (/ 30.0f0 fps) 'single-float)) fz (* fz (coerce (/ 30.0f0 fps) 'single-float))) ;; set new position (incf px fx) (incf pz fz) (setf (px p) px) (setf (pz p) pz) ;; calculate orientation (setf ox (the single-float (/ (+ ox fx) 2.0))) (setf oz (the single-float (/ (+ oz fz) 2.0))) ;; update character position (let ((ry (radtodeg (if (/= oz 0.0) (atan ox oz) 0.0)))) (declare (type single-float ry)) (setf (ox p) ox) (setf (oz p) oz) (h3d:set-node-transform (node p) px 0.02 pz 0 ry 0 1 1 1)) ;; update character animation (let ((vel (sqrt (+ (* fx fx) (* fz fz))))) (declare (type single-float vel)) (incf (anim-time p) (* vel 35.0)) (h3d:set-model-animation-parameters (node p) 0 (anim-time p) 1.0))))))) ;;; chicago.lisp ends here
9,450
Common Lisp
.lisp
185
35.918919
103
0.462297
anwyn/cl-horde3d
15
0
0
EPL-1.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
419aaae729dfb0c572561ff8bf33afa0fcc8b0197dcb45329ab1123ff8e2f942
10,613
[ -1 ]
10,614
examples.lisp
anwyn_cl-horde3d/examples/examples.lisp
;;; examples.lisp --- Examples of the standard horde3d distribution ported to Lisp ;;; _ ;;; _____ ____ _ _ __ ___ _ __ | | ___ ___ ;;; / _ \ \/ / _` | '_ ` _ \| '_ \| |/ _ \/ __| ;;; | __/> < (_| | | | | | | |_) | | __/\__ \ ;;; \___/_/\_\__,_|_| |_| |_| .__/|_|\___||___/ ;;; |_| ;;; ;;; Copyright (C) 2009 Ole Arndt <[email protected]> ;;; (in-package :horde3d-examples) (defparameter *horde3d-home-directory* (asdf:system-relative-pathname (asdf:find-system :horde3d-examples) (make-pathname :directory '(:relative "Horde3D")))) (defclass example-application () ((viewer-position :accessor viewer-position :initarg :viewer-position :initform (make-array 3 :initial-element 0.0 :element-type '(or null single-float))) (viewer-orientation :accessor viewer-orientation :initarg :viewer-orientation :initform (make-array 2 :initial-element 0.0 :element-type '(or null single-float))) (velocity :accessor velocity :initform 10.0) (keys :accessor keys :initform (make-hash-table)) (modifiers :accessor modifiers :initform nil) (fullscreen :accessor fullscreen? :initarg :fullscreen :initform nil) (width :accessor width :initarg :width) (height :accessor height :initarg :height) (hdr-pipeline :accessor hdr-pipeline :initarg :hdr-pipeline) (fwd-pipeline :accessor fwd-pipeline :initarg :fwd-pipeline) (camera-node :accessor camera-node :initarg :camera-node) (anim-time :accessor anim-time :initarg :anim-time :initform 0.0) (anim-weight :accessor anim-weight :initarg :anim-weight :initform 1.0) (curr-fps :accessor curr-fps :initarg :curr-fps :initform 30.0) (logo-resource :accessor logo-resource :initarg :logo-resource) (font-resource :accessor font-resource :initarg :font-resource) (panel-resource :accessor panel-resource :initarg :panel-resource) (content-path :accessor content-path :initarg :content-path) (debug-view :accessor show-debug-view? :initarg :show-debug-view :initform nil) (wire-frame :accessor show-wire-frame? :initarg :show-wire-frame :initform nil) (freeze :accessor freeze? :initarg :freeze :initform nil) (stat-mode :accessor stat-mode :initarg :stat-mode :initform 0)) (:documentation "Base class for Horde3D Examples. Inits/releases Horde and handles basic keys and mouse movement.")) (defgeneric app-init (app) (:method :before ((app example-application)) (h3d:init) (h3d:set-option :load-textures 1) (h3d:set-option :texture-compression 0) (h3d:set-option :fast-animation 0) (h3d:set-option :max-anisotropy 4) (h3d:set-option :shadow-map-size 2048) (setf (fwd-pipeline app) (h3d:add-resource :pipeline "pipelines/forward.pipeline.xml" 0) (font-resource app) (h3d:add-resource :material "overlays/font.material.xml" 0) (panel-resource app) (h3d:add-resource :material "overlays/panel.material.xml" 0) (logo-resource app) (h3d:add-resource :material "overlays/logo.material.xml" 0)))) (defgeneric app-release (app) (:method ((app example-application)) (declare (ignore app))) (:method :after ((app example-application)) (declare (ignore app)) (h3d:release))) (defgeneric app-resize (app width height) (:documentation "Set window of app to new width and height.") (:method :after ((app example-application) width height) (setf (width app) width (height app) height)) (:method ((app example-application) width height) (let ((cam (camera-node app))) (setf (h3d:node-parameter cam :camera-viewport-x) 0 (h3d:node-parameter cam :camera-viewport-y) 0 (h3d:node-parameter cam :camera-viewport-width) width (h3d:node-parameter cam :camera-viewport-height) height) (h3d:setup-camera-view cam 45.0 (/ width height) 0.1 1000.0) (h3d:resize-pipeline-buffers (hdr-pipeline app) width height) (h3d:resize-pipeline-buffers (fwd-pipeline app) width height)))) (defgeneric app-key-press-event (app key) (:documentation "Key handler") (:method ((app example-application) key) (declare (ignore app key))) (:method ((app example-application) (key (eql :sdl-key-escape))) (sdl:push-quit-event)) (:method ((app example-application) (key (eql :sdl-key-space))) (setf (freeze? app) (not (freeze? app)))) (:method ((app example-application) (key (eql :sdl-key-f1))) (toggle-fullscreen app)) (:method ((app example-application) (key (eql :sdl-key-f3))) (with-accessors ((cam camera-node)) app (if (eql (h3d:node-parameter cam :camera-pipeline-resource) (fwd-pipeline app)) (setf (h3d:node-parameter cam :camera-pipeline-resource) (hdr-pipeline app)) (setf (h3d:node-parameter cam :camera-pipeline-resource) (fwd-pipeline app))))) (:method ((app example-application) (key (eql :sdl-key-f7))) (setf (show-debug-view? app) (not (show-debug-view? app)))) (:method ((app example-application) (key (eql :sdl-key-f8))) (setf (show-wire-frame? app) (not (show-wire-frame? app)))) (:method ((app example-application) (key (eql :sdl-key-f9))) (when (> (incf (stat-mode app)) 2) (setf (stat-mode app) 0)))) (defgeneric app-key-release-event (app key) (:method ((app example-application) key) (declare (ignore app key)))) (defgeneric app-mouse-move-event (app x y) (:method ((app example-application) x y) (declare (ignore app x y))) (:method :before ((app example-application) x y) (decf (aref (viewer-orientation app) 1) (coerce (* 30 (/ x 100)) 'single-float)) (incf (aref (viewer-orientation app) 0) (coerce (max -90 (min 90 (* 30 (/ y 100)))) 'single-float)))) (declaim (inline degtorad)) (defun degtorad (angle) (coerce (* angle (/ pi 180.0)) 'single-float)) (declaim (inline radtodeg)) (defun radtodeg (angle) (coerce (* angle (/ 180.0 pi)) 'single-float)) (defun handle-movement (app) (let ((curr-vel (/ (velocity app) (curr-fps app)))) (declare (type single-float curr-vel)) (with-accessors ((mods modifiers) (keys keys) (pos viewer-position) (rot viewer-orientation)) app (when (member :sdl-key-mod-lshift mods) (setf curr-vel (* 5 curr-vel))) (let ((w (gethash :sdl-key-w keys)) (s (gethash :sdl-key-s keys))) (when (or w s) (let ((rx (degtorad (aref rot 0))) (ry (degtorad (aref rot 1)))) (declare (type single-float rx ry)) (when w (decf (aref pos 0) (coerce (* curr-vel (sin ry) (cos (- rx))) 'single-float)) (decf (aref pos 1) (coerce (* curr-vel (sin (- rx))) 'single-float)) (decf (aref pos 2) (coerce (* curr-vel (cos ry) (cos (- rx))) 'single-float))) (when s (incf (aref pos 0) (coerce (* curr-vel (sin ry) (cos (- rx))) 'single-float)) (incf (aref pos 1) (coerce (* curr-vel (sin (- rx))) 'single-float)) (incf (aref pos 2) (coerce (* curr-vel (cos ry) (cos (- rx))) 'single-float)))))) (let ((a (gethash :sdl-key-a keys)) (d (gethash :sdl-key-d keys))) (when (or a d) (let ((ry-90 (degtorad (- (aref rot 1) 90.0f0))) (ry+90 (degtorad (+ (aref rot 1) 90.0f0)))) (declare (type single-float ry-90 ry+90)) (when a (incf (aref pos 0) (coerce (* curr-vel (sin ry-90)) 'single-float)) (incf (aref pos 2) (coerce (* curr-vel (cos ry-90)) 'single-float))) (when (gethash :sdl-key-d keys) (incf (aref pos 0) (coerce (* curr-vel (sin ry+90)) 'single-float)) (incf (aref pos 2) (coerce (* curr-vel (cos ry+90)) 'single-float))))))))) (defgeneric app-main-loop (app) (:method :before ((app example-application)) (h3d:set-option :debug-view-mode (if (show-debug-view? app) 1 0)) (h3d:set-option :wireframe-mode (if (show-wire-frame? app) 1 0)) (handle-movement app)) (:method :after ((app example-application)) (h3d:finalize-frame) (h3d:clear-overlays) (h3d:dump-messages))) (defgeneric toggle-fullscreen (app) (:documentation "Switch from windowed mode to fullscreen an vice versa.") (:method ((app example-application)) (let ((width (width app)) (height (height app))) (app-release app) (if (fullscreen? app) (sdl:resize-window width height :flags '(sdl:sdl-opengl sdl:sdl-resizable)) (sdl:resize-window width height :flags '(sdl:sdl-opengl sdl:sdl-fullscreen))) (setf (fullscreen? app) (if (fullscreen? app) nil t)) (app-init app) (app-resize app width height)))) (defun example-main-sdl (app &key (width 800) (height 600) (caption "Horde3D example")) "Main example function. This function contains the game loop. Call it with an instance of a class derived from example-application." (sdl:with-init () (sdl:window width height :bpp 32 :flags sdl:sdl-opengl :title-caption caption :icon-caption caption) (app-init app) (app-resize app width height) (setf (sdl:frame-rate) 0) (sdl:enable-unicode) (let ((frames 0) (fps 100.0) (mx 0) (my 0) (m-init nil)) (sdl:with-events () ;; Redraw display (:video-expose-event () (sdl:update-display)) ;; leave example (:quit-event () (app-release app) t) (:active-event (:gain gain) (when (= gain 1) (setf m-init nil))) (:mouse-motion-event (:x x :y y) (when (null m-init) (setf m-init t) (setf mx x my y)) (when (not (freeze? app)) (app-mouse-move-event app (- x mx) (- y my))) (setf mx x my y)) ;; Key pressed (:key-down-event (:key key :mod-key mod) (setf (modifiers app) mod) (setf (gethash key (keys app)) t) (app-key-press-event app key)) ;; Key released (:key-up-event (:key key :mod-key mod) (setf (modifiers app) mod) (setf (gethash key (keys app)) nil) (app-key-release-event app key)) ;; Do work (:idle () (when (>= (incf frames) 3) (setf fps (max 100.0 (sdl:average-fps))) (setf frames 0)) (setf (curr-fps app) (coerce fps 'single-float)) (with-simple-restart (skip-game-loop "Skip game loop for this frame") (app-main-loop app)) ;; #+horde3d-debug ;; (with-simple-restart ;; (skip-swank-request "Skip swank evaluation") ;; (let ((connection ;; (or swank::*emacs-connection* (swank::default-connection)))) ;; (swank::handle-requests connection t))) (sdl:update-display)))))) ;;; examples.lisp ends here
11,845
Common Lisp
.lisp
227
42.859031
166
0.565721
anwyn/cl-horde3d
15
0
0
EPL-1.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
b3663a8149fb1aa3f57953c087196b27ed9b6233df63d3e7705f1f95bfab3f3f
10,614
[ -1 ]
10,615
horde3d.lisp
anwyn_cl-horde3d/src/horde3d.lisp
;;; horde3d.lisp --- lispification for the horde3d wrapper ;;; _ _ _____ _ ;;; | |__ ___ _ __ __| | ___|___ / __| | ;;; | '_ \ / _ \| '__/ _` |/ _ \ |_ \ / _` | ;;; | | | | (_) | | | (_| | __/___) | (_| | ;;; |_| |_|\___/|_| \__,_|\___|____/ \__,_| ;;; ;;; Copyright (C) 2009 Ole Arndt <[email protected]> ;;; (in-package :horde3d) (defmacro import-export (&rest symbols) `(eval-when (:compile-toplevel :load-toplevel :execute) ;; Unintern first to avoid conflicts. (dolist (sym ',symbols) (let ((s (find-symbol (symbol-name sym)))) (when s (unintern s)))) ;; Import and re-export. (import ',symbols) (export ',symbols))) (defmacro with-unique-names (symbols &body body) `(let ,(mapcar (lambda (symbol) (let* ((symbol-name (symbol-name symbol)) (stem (if (every #'alpha-char-p symbol-name) symbol-name (concatenate 'string symbol-name "-")))) `(,symbol (gensym ,stem)))) symbols) ,@body)) (defmacro define-get-function (name (&rest head-args) &body clauses) (with-unique-names (return-type return-count p) `(defun ,name (,@head-args ,return-type &optional (,return-count 1)) (with-foreign-object (,p ,return-type ,return-count) (ecase ,return-type ,@(loop for (func . types) in clauses collect `((,@types) (,func ,@head-args ,p)))) (if (= ,return-count 1) (mem-aref ,p ,return-type 0) (loop for i from 0 to (1- ,return-count) collect (mem-aref ,p ,return-type i))))))) ;;;; Typedefs and constants (import-export resource node %h3d:+root-node+ no-such-enum-type) ;;;; Enumerations ;;;; Basic functions (import-export %h3d:get-version-string %h3d:check-extension %h3d:get-error) (defun init () (load-foreign-library '%h3d:horde3d) (load-foreign-library '%h3d:horde3d-utils) (%h3d:init)) (defun release () (%h3d:release) (close-foreign-library '%h3d:horde3d-utils) (close-foreign-library '%h3d:horde3d)) (import-export %h3d:render %h3d:finalize-frame %h3d:clear) (defun get-message () (with-foreign-objects ((level :int) (time :float)) (values (%h3d:get-message level time) (mem-ref level :int) (mem-ref time :float)))) (import-export %h3d:get-option %h3d:set-option) (defun set-options (&rest plist &key max-log-level max-num-messages trilinear-filtering max-anisotropy texture-compression load-textures fast-animation shadow-map-size sample-count wireframe-mode debug-view-mode dump-failed-shaders) (declare (ignore max-log-level max-num-messages trilinear-filtering max-anisotropy texture-compression load-textures fast-animation shadow-map-size sample-count wireframe-mode debug-view-mode dump-failed-shaders)) (loop for (key . rest) on plist by #'cddr do (set-option key (car rest)))) (import-export %h3d:get-statistics %h3d:clear-overlays) (defun show-overlays (vertices count col-r col-g col-b col-a material flags) (with-pointer-to-vector-data (verts vertices) (%h3d:show-overlays verts count col-r col-g col-b col-a material flags))) ;;;; General resource management functions (import-export %h3d:get-resource-type %h3d:get-resource-name %h3d:get-next-resource %h3d:find-resource) (import-export %h3d:clone-resource %h3d:remove-resource %h3d:resource-loaded-p %h3d:load-resource %h3d:unload-resource %h3d:get-resource-element-count %h3d:find-resource-element) (defun add-resource (type name &optional (flags 0)) (%h3d:add-resource type name flags)) (defun resource-parameter (resource element element-index parameter &key (component 0)) (let ((return-type (%h3d:enum-type parameter))) (ecase return-type ((:int :resource) (%h3d:get-resource-parameter-i resource element element-index parameter)) (:float (%h3d:get-resource-parameter-f resource element element-index parameter component)) (:string (%h3d:get-resource-parameter-str resource element element-index parameter))))) (define-compiler-macro resource-parameter (&whole form resource element element-index parameter &key (component 0)) (if (keywordp parameter) (let ((return-type (%h3d:enum-type parameter))) (ecase return-type ((:int :resource) `(%h3d:get-resource-parameter-i ,resource ,element ,element-index ,parameter)) (:float `(%h3d:get-resource-parameter-f ,resource ,element ,element-index ,parameter ,component)) (:string `(%h3d:get-resource-parameter-str ,resource ,element ,element-index ,parameter)))) form)) (defun set-resource-parameter (resource element element-index parameter value &key (component 0)) (let ((type (%h3d:enum-type parameter))) (ecase type ((:int :resource) (%h3d:set-resource-parameter-i resource element element-index parameter value)) (:float (%h3d:set-resource-parameter-f resource element element-index parameter component value)) (:string (%h3d:set-resource-parameter-str resource element element-index parameter value))) value)) (define-compiler-macro set-resource-parameter (&whole form resource element element-index parameter value &key (component 0)) (if (keywordp parameter) (with-unique-names (val) (let ((type (%h3d:enum-type parameter))) (when (null type) (error 'no-such-enum-type :enum parameter)) (ecase type ((:int :resource) `(let ((,val ,value)) (%h3d:set-resource-parameter-i ,resource ,element ,element-index ,parameter ,val) ,val)) (:float `(let ((,val ,value)) (%h3d:set-resource-parameter-f ,resource ,element ,element-index ,parameter ,component ,val) ,val)) (:string `(let ((,val ,value)) (%h3d:set-resource-parameter-str ,resource ,element ,element-index ,parameter ,val) ,val))))) form)) (defsetf resource-parameter (resource element element-index parameter &key (component 0)) (store) `(set-resource-parameter ,resource ,element ,element-index ,parameter ,component ,store)) (import-export %h3d:map-resource-stream %h3d:unmap-resource-stream %h3d:query-unloaded-resource %h3d:release-unused-resources) ;;;; Specific resource management functions (import-export %h3d:create-texture %h3d:set-shader-preambles %h3d:set-material-uniform %h3d:resize-pipeline-buffers) (defun get-render-target-data (pipeline-res target-name buf-index &optional data-buffer buffer-size) (with-foreign-objects ((w :int) (h :int) (count :int)) (if (and (pointerp data-buffer) (not (null buffer-size))) (%h3d:get-render-target-data pipeline-res target-name buf-index w h count data-buffer buffer-size) (%h3d:get-render-target-data pipeline-res target-name buf-index w h count (null-pointer) 0)) (values (mem-ref w :int) (mem-ref h :int) (mem-ref count :int)))) ;;;; General scene graph functions (import-export %h3d:get-node-type %h3d:get-node-parent %h3d:get-node-child %h3d:add-nodes %h3d:remove-node %h3d:set-node-activation %h3d:check-node-transform-flag) (defun get-node-transform (handle) (with-foreign-objects ((tx :float) (ty :float) (tz :float) (rx :float) (ry :float) (rz :float) (sx :float) (sy :float) (sz :float)) (%h3d:get-node-transform handle tx ty tz rx ry rz sx sy sz) (values (mem-ref tx :float) (mem-ref ty :float) (mem-ref tz :float) (mem-ref rx :float) (mem-ref ry :float) (mem-ref rz :float) (mem-ref sx :float) (mem-ref sy :float) (mem-ref sz :float)))) (import-export %h3d:set-node-transform %h3d:get-node-transform-matrices %h3d:set-node-transform-matrix) (defun node-parameter (node parameter &key (component 0)) (let ((type (%h3d:enum-type parameter))) (ecase type ((:int :resource) (%h3d:get-node-parameter-i node parameter)) (:float (%h3d:get-node-parameter-f node parameter component)) (:string (%h3d:get-node-parameter-str node parameter))))) (define-compiler-macro node-parameter (&whole form node parameter &key (component 0)) (if (keywordp parameter) (let ((type (%h3d:enum-type parameter))) (ecase type ((:int :resource) `(%h3d:get-node-parameter-i ,node ,parameter)) (:float `(%h3d:get-node-parameter-f ,node ,parameter ,component)) (:string `(%h3d:get-node-parameter-str ,node ,parameter)))) form)) (defun set-node-parameter (node parameter value &key (component 0)) (let ((type (%h3d:enum-type parameter))) (ecase type ((:int :resource) (%h3d:set-node-parameter-i node parameter value)) (:float (%h3d:set-node-parameter-f node parameter component value)) (:string (%h3d:set-node-parameter-str node parameter value))) value)) (define-compiler-macro set-node-parameter (&whole form node parameter value &key (component 0)) (if (keywordp parameter) (with-unique-names (val) (let ((type (%h3d:enum-type parameter))) (ecase type ((:int :resource) `(let ((,val ,value)) (%h3d:set-node-parameter-i ,node ,parameter ,val) ,val)) (:float `(let ((,val ,value)) (%h3d:set-node-parameter-f ,node ,parameter ,component ,val) ,val)) (:string `(let ((,val ,value)) (%h3d:set-node-parameter-str ,node ,parameter ,val) ,val))))) form)) (defsetf node-parameter (node param &key (component 0)) (store) `(set-node-parameter ,node ,param ,store :component ,component)) (import-export %h3d:get-node-flags %h3d:set-node-flags) (defun get-node-aabb (node) (with-foreign-objects ((minx :float) (miny :float) (minz :float) (maxx :float) (maxy :float) (maxz :float)) (%h3d:get-node-aabb node minx miny minz maxy maxy maxz) (values (mem-ref minx :float) (mem-ref miny :float) (mem-ref minz :float) (mem-ref maxx :float) (mem-ref maxy :float) (mem-ref maxz :float)))) (import-export %h3d:find-nodes %h3d:get-node-find-result %h3d:cast-ray) (define-condition no-such-node-result (error) ((index :initarg :index :reader index))) (defun get-cast-ray-result (index &optional intersection-point) (let ((point (or intersection-point (make-array 3 :element-type 'single-float)))) (with-pointer-to-vector-data (intersection point) (with-foreign-objects ((node :int) (distance :float)) (unless (%h3d:get-cast-ray-result index node distance intersection) (error 'no-such-node-result :index index)) (values (mem-ref node :int) (mem-ref distance :float) intersection))))) ;;; Lispification (defmacro do-nodes ((node &key (node-name "") (node-type :undefined) (start-node +root-node+)) &body body) (with-unique-names (index) `(dotimes (,index (find-nodes ,start-node ,node-name ,node-type)) (let ((,node (get-node-find-result ,index))) ,@body)))) (defmacro do-ray-cast ((node origin direction &key (max-results 0)) (rnode distance intersection) &body body) (with-unique-names (index orig dir point) `(let ((,orig ,origin) (,dir ,direction) (,point (make-array 3 :element-type 'single-float))) (dotimes (,index (cast-ray ,node (aref orig 0) (aref orig 1) (aref orig 2) (aref dir 0) (aref dir 1) (aref dir 2) ,max-results)) (multiple-value-bind (,rnode ,distance ,intersection ) (get-cast-ray-result ,index) ,@body))))) (import-export %h3d:check-node-visibility) ;;;; Group-specific scene graph functions (import-export %h3d:add-group-node) ;;;; Model-specific scene graph functions (import-export %h3d:add-model-node %h3d:setup-model-animation-stage %h3d:set-model-animation-parameters %h3d:set-model-morpher) ;;;; Mesh-specific scene graph functions (import-export %h3d:add-mesh-node) ;;;; Joint-specific scene graph functions (import-export %h3d:add-joint-node) ;;;; Light-specific scene graph functions (import-export %h3d:add-light-node) ;;;; Camera-specific scene graph functions (import-export %h3d:add-camera-node %h3d:setup-camera-view) (defun get-camera-projection-matrix (camera-node &optional matrix) (with-pointer-to-vector-data (mat (or matrix (make-array 16 :element-type 'single-float))) (%h3d:get-camera-projection-matrix camera-node mat) mat)) ;;;; Emitter-specific scene graph functions (import-export %h3d:add-emitter-node %h3d:advance-emitter-time %h3d:emitter-finished-p) ;;;; Util Library (import-export %h3d:dump-messages %h3d:init-open-gl %h3d:release-open-gl %h3d:swap-buffers) ;;;; Resource management (import-export %h3d:get-resource-path %h3d:set-resource-path %h3d:load-resources-from-disk) (defun set-resource-paths (&rest plist &key scene-graph geometry animation material code shader texture-2d texture-cube effect pipeline) (declare (ignore scene-graph geometry animation material code shader texture-2d texture-cube effect pipeline)) (loop for (key . rest) on plist by #'cddr do (%h3d:set-resource-path key (car rest)))) (defun create-tga-image (pixels width height bpp) (with-foreign-objects ((out-data :pointer) (out-size :int)) (%h3d:create-tga-image pixels width height bpp out-data out-size) (values (mem-ref out-data :pointer) (mem-ref out-size :int)))) ;;;; Scene graph (defun pick-ray (camera-node nwx nwy) (with-foreign-objects ((ox :float) (oy :float) (oz :float) (dx :float) (dy :float) (dz :float)) (%h3d:pick-ray camera-node nwx nwy ox oy oz dx dy dz) (values (mem-ref ox :float) (mem-ref oy :float) (mem-ref oz :float) (mem-ref dx :float) (mem-ref dy :float) (mem-ref dz :float)))) (import-export %h3d:pick-node) ;;;; Overlays (import-export %h3d:show-text %h3d:show-frame-statistics) ;;; horde3d.lisp ends here
16,296
Common Lisp
.lisp
374
32.671123
97
0.572051
anwyn/cl-horde3d
15
0
0
EPL-1.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
a5f42434ec525ad432d5b38d23b2cbf674677b31dd660e9c560b5da80e4ff46e
10,615
[ -1 ]
10,616
package.lisp
anwyn_cl-horde3d/src/package.lisp
;;; packages.lisp --- package definition and exported symbols ;;; _ ;;; _ __ __ _ ___| | ____ _ __ _ ___ ___ ;;; | '_ \ / _` |/ __| |/ / _` |/ _` |/ _ \/ __| ;;; | |_) | (_| | (__| < (_| | (_| | __/\__ \ ;;; | .__/ \__,_|\___|_|\_\__,_|\__, |\___||___/ ;;; |_| |___/ ;;; ;;; Copyright (C) 2009 Ole Arndt <[email protected]> ;;; (in-package :cl-user) (defpackage #:horde3d (:nicknames #:h3d) (:use #:common-lisp #:cffi) (:export #:resource #:node #:+root-node+ #:get-version-string #:check-extension #:get-error #:init #:release #:render #:finalize-frame #:clear ;; General functions #:get-message #:get-option #:set-option #:get-stat ;; Overlays #:show-overlays #:clear-overlays ;; Resource management #:get-resource-type #:get-resource-name #:find-resource #:add-resource #:clone-resource #:remove-resource #:is-resource-loaded #:load-resource #:unload-resource #:resource-parameter #:query-unloaded-resource #:release-unused-resources #:create-texture-2d #:set-shader-preambles #:set-material-uniform #:set-material-sampler #:set-pipeline-stage-activation #:resize-pipeline-buffers #:get-render-target-data ;; General scene graph functions #:get-node-type #:get-node-parent #:set-node-parent #:get-node-child #:add-nodes #:remove-node #:set-node-activation #:check-node-transform-flag #:get-node-transform #:set-node-transform #:get-node-transform-matrices #:set-node-transform-matrix #:node-parameter #:get-node-flags #:set-node-flags #:get-node-aabb #:find-nodes #:get-node-find-result #:cast-ray #:get-cast-ray-result #:check-node-visibility ;; Group-specific scene graph functions #:add-group-node #:add-model-node #:setup-model-animation-stage #:set-model-animation-parameters #:set-model-morpher #:add-mesh-node #:add-joint-node #:add-light-node #:set-light-contexts #:add-camera-node #:setup-camera-view #:get-camera-projection-matrix #:add-emitter-node #:advance-emitter-time #:emitter-finished-p ;; Horde3d utilities #:dump-messages #:init-open-gl #:release-open-gl #:swap-buffers #:get-resource-path #:set-resource-path #:load-resources-from-disk #:create-tga-image #:pick-ray #:pick-node #:show-text #:show-frame-stats ;; lispification #:set-resource-paths #:set-options #:add-resource #:do-nodes #:do-ray-cast)) ;;; packages.lisp ends here
2,616
Common Lisp
.lisp
112
19.625
61
0.608347
anwyn/cl-horde3d
15
0
0
EPL-1.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
9c3d06188f08fa9ffa3bcc304c90c611811885f47508169a410e170e6de60b8f
10,616
[ -1 ]
10,617
types.lisp
anwyn_cl-horde3d/src/types.lisp
;;; types.lisp --- cffi types for the horde3d lisp bindings ;;; _ ;;; | |_ _ _ _ __ ___ ___ ;;; | __| | | | '_ \ / _ \/ __| ;;; | |_| |_| | |_) | __/\__ \ ;;; \__|\__, | .__/ \___||___/ ;;; |___/|_| ;;; ;;; Copyright (C) 2009 Ole Arndt <[email protected]> ;;; (in-package :horde3d-cffi) ;;;; CFFI types (define-foreign-type ensure-integer () () (:actual-type :int) (:simple-parser ensure-integer)) (defmethod translate-to-foreign (value (type ensure-integer)) (truncate value)) (defmethod expand-to-foreign (value (type ensure-integer)) (if (constantp value) (truncate (eval value)) `(truncate ,value))) (define-foreign-type ensure-float () () (:actual-type :float) (:simple-parser ensure-float)) (defmethod translate-to-foreign (value (type ensure-float)) (cl:float value 1.0)) (defmethod expand-to-foreign (value (type ensure-float)) (if (constantp value) (cl:float (eval value) 1.0) `(cl:float ,value 1.0))) (define-foreign-type ensure-double () () (:actual-type :double) (:simple-parser ensure-double)) (defmethod translate-to-foreign (value (type ensure-double)) (cl:float value 1.0d0)) (defmethod expand-to-foreign (value (type ensure-double)) (if (constantp value) (cl:float (eval value) 1.0d0) `(cl:float ,value 1.0d0))) ;;;; C types (defctype boolean (:boolean :unsigned-char)) (defctype int ensure-integer) (defctype sizei ensure-integer) (defctype void :void) (defctype string :string) (defctype float ensure-float) (defctype double ensure-double) ;;;; Enums (define-foreign-type multi-enum () ((enums :accessor enums :initarg :enums :initform nil)) (:actual-type :int) (:simple-parser multi-enum)) (defmethod translate-to-foreign (value (type multi-enum)) (or (some (lambda (enum) (foreign-enum-value enum value :errorp nil)) (enums type)) (error "~S is not defined as a value for multi enum type ~S." value type))) (defmethod translate-from-foreign (value (type multi-enum)) (or (some (lambda (enum) (foreign-enum-keyword enum value :errorp nil)) (enums type)) (error "~S is not defined as a keyword for multi enum type ~S." value type))) (defmethod expand-to-foreign (value (type multi-enum)) (if (constantp value) (or (some (lambda (enum) (foreign-enum-value enum (eval value) :errorp nil)) (enums type)) (error "~S is not defined as a value for multi enum type ~S." value type)) `(or (some (lambda (enum) (foreign-enum-value enum ,value :errorp nil)) ',(enums type)) (error "~S is not defined as a value for multi enum type ~S." ,value ,type)))) (defmethod expand-from-foreign (value (type multi-enum)) (if (constantp value) (or (some (lambda (enum) (foreign-enum-keyword enum (eval value) :errorp nil)) (enums type)) (error "~S is not defined as a keyword for multi enum type ~S." value type)) `(or (some (lambda (enum) (foreign-enum-keyword enum ,value :errorp nil)) ',(enums type)) (error "~S is not defined as a keyword for multi enum type ~S." ,value ,type)))) ;;;; Group: Typedefs and constants (defctype resource ensure-integer "Handle to a resource (int).") (defctype node ensure-integer "Handle to a scene node (int).") ;;;; Macros (eval-when (:compile-toplevel :load-toplevel :execute) (let ((enum-types (make-hash-table))) (defun enum-type (keyword) (gethash keyword enum-types)) (defun notice-enum-type (keyword type) (setf (gethash keyword enum-types) type))) (defun emit-typed-enum-form (name enums) (let ((e-values (loop for enum in enums by #'cddr collect enum)) (e-types (loop for (enum . rest) on enums by #'cddr collect (cons (if (listp enum) (car enum) enum) (car rest)))) (i (gensym))) `(progn (eval-when (:compile-toplevel :load-toplevel :execute) (dolist (,i ',e-types) (notice-enum-type (car ,i) (cdr ,i)))) (defcenum ,name ,@e-values))))) (defmacro deftypedenum (name &body enum-values) (when (and (stringp (car enum-values)) (cdr enum-values)) (pop enum-values)) (emit-typed-enum-form name enum-values)) (define-condition no-such-enum-type (simple-error) ((enum :initarg :enum :reader enum)) (:report (lambda (condition stream) (format stream "There is no enum type associated with keyword ~A." (enum condition))))) ;;; Helper macro to define a horde3d API function and declare it inline. (defmacro defh3fun ((cname lname) result-type &body body) `(progn (declaim (inline ,lname)) (defcfun (,cname ,lname :library horde3d) ,result-type ,@body))) ;;; Helper macro to define a horde3d utils API function and declare it inline. (defmacro defh3ufun ((cname lname) result-type &body body) `(progn (declaim (inline ,lname)) (defcfun (,cname ,lname :library horde3d-utils) ,result-type ,@body))) ;;; types.lisp ends here
5,308
Common Lisp
.lisp
130
34.169231
85
0.613919
anwyn/cl-horde3d
15
0
0
EPL-1.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
cd47d70ad83c78ab244356c4b62a9e3a488e0601b2a41ab22edbe716042fe264
10,617
[ -1 ]
10,618
sound.lisp
anwyn_cl-horde3d/src/sound.lisp
;;; sound.lisp --- bindings to the horde3d sound extension ;;; _ ;;; ___ ___ _ _ _ __ __| | ;;; / __|/ _ \| | | | '_ \ / _` | ;;; \__ \ (_) | |_| | | | | (_| | ;;; |___/\___/ \__,_|_| |_|\__,_| ;;; ;;; Copyright (C) 2009 Ole Arndt <[email protected]> ;;; ;;; Make symbols available in the horde3d package (in-package :horde3d) (import-export %h3d-sound:open-device %h3d-sound:close-device %h3d-sound:get-open-device %h3d-sound:query-device %h3d-sound:get-distance-model %h3d-sound:set-distance-model %h3d-sound:add-listener-node %h3d-sound:get-active-listener %h3d-sound:set-active-listener %h3d-sound:add-sound-node %h3d-sound:sound-playing-p %h3d-sound:play-sound %h3d-sound:pause-sound %h3d-sound:rewind-sound) ;;; sound.lisp ends here
977
Common Lisp
.lisp
26
28.846154
58
0.486772
anwyn/cl-horde3d
15
0
0
EPL-1.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
8258825817a629f688b1bdcda9a4b39fc0b0ed463fdcae16946600219f963274
10,618
[ -1 ]
10,619
terrain-bindings.lisp
anwyn_cl-horde3d/src/terrain-bindings.lisp
;;; terrain-bindings.lisp --- bindings to the horde3d terrain extension ;;; _ _ _ _ _ _ ;;; | |_ ___ _ __ _ __ __ _(_)_ __ | |__ (_)_ __ __| (_)_ __ __ _ ___ ;;; | __/ _ \ '__| '__/ _` | | '_ \ _____| '_ \| | '_ \ / _` | | '_ \ / _` / __| ;;; | || __/ | | | | (_| | | | | |_____| |_) | | | | | (_| | | | | | (_| \__ \ ;;; \__\___|_| |_| \__,_|_|_| |_| |_.__/|_|_| |_|\__,_|_|_| |_|\__, |___/ ;;; |___/ ;;; ;;; Copyright (C) 2009 Ole Arndt <[email protected]> ;;; (cl:defpackage #:horde3d-terrain-cffi (:nicknames #:%h3d-terrain) (:use #:cffi #:%h3d) (:import-from #:common-lisp #:in-package) (:export #:add-terrain-node #:create-geometry-resource)) (in-package :horde3d-terrain-cffi) (defcenum terrain-node-type "The available scene node types. :terrain - Terrain node " (:terrain 100)) (deftypedenum terrain-node-parameters "The available Terrain node parameters: :terrain-height-map-resource - Height map texture; must be square and a power of two [type: resource, write-only] :terrain-material-resource - Material resource used for rendering the terrain [type: resource] :terrain-mesh-quality - Constant controlling the overall resolution of the terrain mesh (default: 50.0) [type: float] :terrain-skirt-height - Height of the skirts used to hide cracks (default: 0.1) [type: float] :terrain-block-size - Size of a terrain block that is drawn in a single render call; must be 2^n+1 (default: 17) [type: int] " (:terrain-height-map-resource 10000) :resource :terrain-material-resource :resource :terrain-mesh-quality :float :terrain-skirt-height :float :terrain-block-size :int) ;;;; Group: Terrain Extension ;; NodeHandle addTerrainNode( NodeHandle parent, const char *name, ResHandle heightMapRes, ResHandle materialRes ); (defh3fun ("h3dAddTerrainNode" add-terrain-node) node "Adds a Terrain node to the scene. This function creates a new Terrain node and attaches it to the specified parent node. Parameters: parent - handle to parent node to which the new node will be attached name - name of the node height-map - handle to a Texture2D resource that contains the terrain height information (must be square and POT) material - handle to the Material resource used for rendering the terrain Returns: handle to the created node or 0 in case of failure " (parent node) (name string) (height-map resource) (material resource)) ;; ResHandle createGeometryResource( NodeHandle node, const char *resName, float meshQuality ); (defh3fun ("h3dCreateGeometryResource" create-geometry-resource) resource "Creates a Geometry resource from a specified Terrain node. This function creates a new Geometry resource that contains the vertex data of the specified Terrain node. To reduce the amount of data, it is possible to specify a quality value which controls the overall resolution of the terrain mesh. The algorithm will automatically create a higher resoultion in regions where the geometrical complexity is higher and optimize the vertex count for flat regions. Parameters: node - handle to terrain node that will be accessed resName - name of the Geometry resource that shall be created meshQuality - constant controlling the overall mesh resolution Returns: handle to the created Geometry resource or 0 in case of failure " (node node) (res-name string) (mesh-quality float)) ;;; terrain-bindings.lisp ends here
3,664
Common Lisp
.lisp
67
51.41791
134
0.651215
anwyn/cl-horde3d
15
0
0
EPL-1.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
cc02a525443cd980c098967a280bd002f810ead20496c9c908abcbd9c8eb8068
10,619
[ -1 ]
10,620
bindings.lisp
anwyn_cl-horde3d/src/bindings.lisp
;;; bindings.lisp --- bindings for the core of the Horde3D engine ;;; _ _ _ _ ;;; | |__ (_)_ __ __| (_)_ __ __ _ ___ ;;; | '_ \| | '_ \ / _` | | '_ \ / _` / __| ;;; | |_) | | | | | (_| | | | | | (_| \__ \ ;;; |_.__/|_|_| |_|\__,_|_|_| |_|\__, |___/ ;;; |___/ ;;; ;;; Copyright (C) 2009 Ole Arndt <[email protected]> ;;; (in-package :horde3d-cffi) ;;;; Constants: Predefined constants (defconstant +root-node+ 1 "Scene root node handle.") ;;;; --------------------------------------------------------------------------- ;;;; * Group: Basic functions ;; const char* h3dGetVersionString(); (defh3fun ("h3dGetVersionString" get-version-string) string "Returns the engine version string. This function returns a pointer to a string containing the current version of Horde3D. Parameters: none Returns: pointer to the version string ") ;; bool h3dCheckExtension( const char* extensionName ); (defh3fun ("h3dCheckExtension" check-extension) boolean "Checks if an extension is part of the engine library. This function checks if a specified extension is contained in the DLL/shared object of the engine. Parameters: extension-name - name of the extension Returns: true if extension is implemented, otherwise false " (extension-name string)) ;; bool h3dGetError(); (defh3fun ("h3dGetError" get-error) boolean "Checks if an error occured. This function checks if an error occured in a previous API function call. If an error flag is set, the function resets the flag and returns true. The function will solely report errors that originate from a violated precondition, like an invalid parameter that is passed to an API function. Errors that happen during the execution of a function, for example failure of initializing the engine due to a missing hardware feature, can be catched by checking the return value of the corresponding API function. More information about the error can be retrieved by checking the message queue, provided that the message level is set accordingly. Parameters: none Returns: true in there was an error, otherwise false ") ;; void h3dInit(); (defh3fun ("h3dInit" init) boolean "Initializes the engine. This function initializes the graphics engine and makes it ready for use. It has to be the first call to the engine except for getVersionString. In order to successfully initialize the engine the calling application must provide a valid OpenGL context. The function can be called several times on different rendering contexts in order to initialize them. Parameters: none Returns: true in case of success, otherwise false ") ;; void h3dRelease(); (defh3fun ("h3dRelease" release) void "Releases the engine. This function releases the engine and frees all objects and associated memory. It should be called when the application is destroyed. Parameters: none Returns: nothing ") ;; bool h3dRender( H3DNode cameraNode ); (defh3fun ("h3dRender" render) void "Main rendering function. This is the main function of the engine. It executes all the rendering, animation and other tasks. The function can be called several times per frame, for example in order to write to different output buffers. Parameters: cameraNode - camera node used for rendering scene Returns: nothing " (camera-node node)) ;; bool h3dFinalizeFrame(); (defh3fun ("h3dFinalizeFrame" finalize-frame) void "Marker for end of frame. This function tells the engine that the current frame is finished and that all subsequent rendering operations will be for the next frame. Parameters: none Returns: nothing ") ;; void h3dClear(); (defh3fun ("h3dClear" clear) void "Removes all resources and scene nodes. This function removes all nodes from the scene graph except the root node and releases all resources. Warning: All resource and node IDs are invalid after calling this function Parameters: none Returns: nothing ") ;; const char *h3dGetMessage( int *level, float *time ); (defh3fun ("h3dGetMessage" get-message) string "Gets the next message from the message queue. This function returns the next message string from the message queue and writes additional information o the specified variables. If no message is left over in the queue an empty string is returned. Parameters: level - pointer to variable for storing message level indicating importance (can be NULL) time - pointer to variable for storing time when message was added (can be NULL) Returns: message string or empty string if no message is in queue " (level (:pointer int)) (time (:pointer float))) ;; float h3dGetOption( H3DOptions::List param ); (defh3fun ("h3dGetOption" get-option) float "Gets an option parameter of the engine. This function gets a specified option parameter and returns its value. Parameters: parameter - option parameter Returns: current value of the specified option parameter " (parameter option)) ;; bool h3dSetOption( H3DOptions::List param, float value ); (defh3fun ("h3dSetOption" set-option) boolean "Sets an option parameter for the engine. This function sets a specified option parameter to a specified value. Parameters: parameter - option parameter value - value of the option parameter Returns: true if the option could be set to the specified value, otherwise false " (parameter option) (value float)) ;; float h3dGetStat( EngineStats::List param, bool reset ); (defh3fun ("h3dGetStat" get-statistics) float "Gets a statistic value of the engine. This function returns the value of the specified statistic. The reset flag makes it possible to reset the statistic value after reading. Parameters: parameter - statistic parameter reset - flag specifying whether statistic value should be reset Returns: current value of the specified statistic parameter " (parameter statistics) (reset boolean)) ;; void h3dShowOverlays( float* verts, int vertCount, ;; float colR, float colG, float colB, float colA, ;; H3DRes materialRes, int flags ); (defh3fun ("h3dShowOverlays" show-overlays) void "Displays overlays on the screen. This function displays one or more overlays with a specified material and color. An overlay is a screen-space quad that can be used to render 2D GUI elements. The overlay coordinate system has its origin (0, 0) at the top-left corner of the screen and its maximum (aspect, 1) at the bottom-right corner. As the x coordinate of the maximum corresponds to the aspect ratio of the viewport, the size of overlays can always be the same, even when different screen formats standard 4:3, widescreen 16:9, etc. are used. Texture coordinates are using a system where the coordinates (0, 0) correspond to the lower left corner of the image. Overlays are drawn in the order in which they are pushed using this function. Overlays with the same state will be batched together, so it can make sense to group overlays that have the same material, color and flags in order to achieve best performance. Note that the overlays have to be removed manually using the function h3dClearOverlays. Parameters: vertices - vertex data (x, y, u, v), interpreted as quads vertex-count - number of vertices (must be multiple of 4) col-r, col-g, col-b, col-a - color (and transparency) of overlays material-resource - material resource used for rendering flags - overlay flags (reserved for future use) Returns: nothing " (vertices (:pointer float)) (vertex-count int) (col-r float) (col-g float) (col-b float) (col-a float) (material-resource resource) (flags int)) ;; void h3dClearOverlays(); (defh3fun ("h3dClearOverlays" clear-overlays) void "Removes all overlays. This function removes all overlays that were added using showOverlay. Parameters: none Returns: nothing ") ;;;; --------------------------------------------------------------------------- ;;;; * Group: General resource management functions ;; int h3dGetResType( H3DRes res ); (defh3fun ("h3dGetResType" get-resource-type) resource-type "Returns the type of a resource. This function returns the type of a specified resource. If the resource handle is invalid, he function returns the resource type 'Unknown'. Parameters: resource - handle to the resource Returns: type of the resource " (resource resource)) ;; const char *h3dGetResName( H3DRes res ); (defh3fun ("h3dGetResName" get-resource-name) string "Returns the name of a resource. This function returns a pointer to the name of a specified resource. If the resource handle is invalid, the function returns an empty string. Important Note: The pointer is const and allows only read access to the data. Do never try to modify the data of the pointer since that can corrupt the engine's internal states!* Parameters: resource - handle to the resource Returns: name of the resource or empty string in case of failure " (resource resource)) ;; H3DRes h3dGetNextResource( int type, H3DRes start ); (defh3fun ("h3dGetNextResource" get-next-resource) resource "Returns the next resource of the specified type. This function searches the next resource of the specified type and returns its handle. The search begins after the specified start handle. If a further resource of the queried type does not exist, a zero handle is returned. The function can be used to iterate over all resources of a given type by using as start the return value of the previous iteration step. The first iteration step should start at 0 and iteration can be ended when the function returns 0. Parameters: type - type of resource to be searched (ResourceTypes::Undefined for all types) start - resource handle after which the search begins (can be 0 for beginning of resource list) Returns: handle to the found resource or 0 if it does not exist " (type resource-type) (start resource)) ;; H3DRes h3dFindResource( int type, const char *name ); (defh3fun ("h3dFindResource" find-resource) resource "Finds a resource and returns its handle. This function searches the resource of the specified type and name and returns its handle. If he resource is not available in the resource manager a zero handle is returned. Parameters: type - type of the resource name - name of the resource Returns: handle to the resource or 0 if not found " (type resource-type) (name string)) ;; H3DRes h3dAddResource( int type, const char *name, int flags ); (defh3fun ("h3dAddResource" add-resource) resource "Adds a resource. This function tries to add a resource of a specified type and name to the resource manager. If resource of the same type and name is already existing, the handle to the existing resource is returned nstead of creating a new one and the user reference count of the resource is increased. *Note: The name string may not contain a colon character (:)* Parameters: type - type of the resource name - name of the resource flags - flags used for creating the resource Returns: handle to the resource to be added or 0 in case of failure " (type resource-type) (name string) (flags resource-flags)) ;; H3DRes h3dCloneResource( H3DRes sourceRes, const char *name ); (defh3fun ("h3dCloneResource" clone-resource) resource "Duplicates a resource. This function duplicates a specified resource. In the cloning process a new resource with the specified name is added to the resource manager and filled with the data of the specified source resource. If the specified name for the new resource is already in use, the function fails and returns 0. If the name string is empty, a unique name for the resource is generated automatically. *Note: The name string may not contain a colon character (:)* Parameters: resource - handle to resource to be cloned name - name of new resource (can be empty for auto-naming) Returns: handle to the cloned resource or 0 in case of failure " (resource resource) (name string)) ;; int h3dRemoveResource( H3DRes res ); (defh3fun ("h3dRemoveResource" remove-resource) int "Removes a resource. This function decreases the user reference count of a specified resource. When the user reference count is zero and there are no internal references, the resource can be released and removed using the API fuction releaseUnusedResources. Parameters: resource - handle to the resource to be removed Returns: the number of references that the application is still holding after removal or -1 in case of an error " (resource resource)) ;; bool h3dIsResLoaded( H3DRes res ); (defh3fun ("h3dIsResLoaded" resource-loaded-p) boolean "Checks if a resource is loaded. This function checks if the specified resource has been successfully loaded. Parameters: resource - handle to the resource to be checked Returns: true if resource is loaded, otherwise or in case of failure false " (resource resource)) ;; bool h3dLoadResource( H3DRes res, const char *data, int size ); (defh3fun ("h3dLoadResource" load-resource) boolean "Loads a resource. This function loads data for a resource that was previously added to the resource manager. f data is a NULL-pointer the resource manager is told that the resource doesn't have any data e.g. the corresponding file was not found. In this case, the resource remains in the unloaded state but is no more returned when querying unloaded resources. When the specified resource is already loaded, the function returns false. Important Note: XML-data must be NULL-terminated* Parameters: resource - handle to the resource for which data will be loaded data - pointer to the data to be loaded size - size of the data block Returns: true in case of success, otherwise false " (resource resource) (data :pointer) (size int)) ;; void h3dUnloadResource( H3DRes res ); (defh3fun ("h3dUnloadResource" unload-resource) void "Unloads a resource. This function unloads a previously loaded resource and restores the default values t had before loading. The state is set back to unloaded which makes it possible to load he resource again. Parameters: resource - handle to resource to be unloaded Returns: nothing " (resource resource)) ;; int h3dGetResElemCount( H3DRes res, int elem ); (defh3fun ("h3dGetResElemCount" get-resource-element-count) int "Gets the number of elements in a resource. This function returns how many elements of the specified element type a specified resource has. Parameters: resource - handle to the resource to be accessed element - element type Returns: number of elements " (resource resource) (element resource-element)) ;; int h3dFindResElem( H3DRes res, int elem, int param, const char *value ); (defh3fun ("h3dFindResElem" find-resource-element) int "Finds a resource element with the specified property value. This function searches in a specified resource for the first element of the specified type that has the property with the specified name set to the specified search value. If such element is found, its index is returned, otherwise the function returns -1. All string comparisons done for the search are case-sensitive. Parameters: resource - handle to the resource to be accessed element - element type parameter - parameter name value - parameter value to be searched for Returns: index of element or -1 if element not found " (resource resource) (element resource-element) (parameter resource-parameter) (value string)) ;; int h3dGetResParamI( H3DRes res, int element, int elemIdx, int param ); (defh3fun ("h3dGetResParamI" get-resource-parameter-i) int "Gets a property of a resource element. This function returns a specified property of the specified resource element. The property must be of the type int. Parameters: resource - handle to the resource to be accessed element - element type element-index - index of element parameter - parameter to be accessed Returns: value of the parameter " (resource resource) (element resource-element) (element-index int) (parameter resource-parameter)) ;; void h3dSetResParamI( H3DRes res, int element, int elemIdx, int param, int value ); (defh3fun ("h3dSetResParamI" set-resource-parameter-i) void "Sets a property of a resource element. This function sets a specified property of the specified resource element to a specified value. The property must be of the type int. Parameters: resource - handle to the resource to be accessed element - element type element-index - index of element parameter - parameter to be modified value - new value for the specified parameter Returns: nothing " (resource resource) (element resource-element) (element-index int) (parameter resource-parameter) (value int)) ;; float h3dGetResParamF( H3DRes res, int elem, int elemIdx, int param, int compIdx ); (defh3fun ("h3dGetResParamF" get-resource-parameter-f) float "Gets a property of a resource element. This function returns a specified property of the specified resource element. The property must be of the type float. Parameters: resource - handle to the resource to be accessed element - element type element-index - index of element parameter - parameter to be accessed component-index - component of the parameter to be accessed Returns: value of the parameter " (resource resource) (element resource-element) (element-index int) (parameter resource-parameter) (component-index int)) ;; void h3dSetResParamF( H3DRes res, int elem, int elemIdx, int param, int compIdx, float value ); (defh3fun ("h3dSetResParamF" set-resource-parameter-f) void "Sets a property of a resource element. This function sets a specified property of the specified resource element to a specified value. The property must be of the type float. Parameters: resource - handle to the resource to be accessed element - element type element-index - index of element parameter - parameter to be accessed component-index - component of the parameter to be accessed value - new value for the specified parameter Returns: nothing " (resource resource) (element resource-element) (element-index int) (parameter resource-parameter) (component-index int) (value float)) ;; const char *h3dGetResParamStr( H3DRes res, int elem, int elemIdx, int param ); (defh3fun ("h3dGetResParamStr" get-resource-parameter-str) string "Gets a property of a resource element. This function returns a specified property of the specified resource element. The property must be of the type string (const char *). *Important Note: The pointer is const and allows only read access to the data. Do never try to modify the ata of the pointer since that can corrupt the engine's internal states!* Parameters: resource - handle to the resource to be accessed element - element type element-index - index of element parameter - parameter to be accessed Returns: value of the property or empty string if no such property exists " (resource resource) (element resource-element) (element-index int) (parameter resource-parameter)) ;; void h3dSetResParamStr( H3DRes res, int elem, int elemIdx, int param, const char *value ); (defh3fun ("h3dSetResParamStr" set-resource-parameter-str) void "Sets a property of a resource element. This function sets a specified property of the specified resource element to a specified value. The property must be of the type string (const char *). Parameters: resource - handle to the resource to be accessed element - element type element-index - index of element parameter - parameter to be accessed value - new value for the specified parameter Returns: true in case of success otherwise false " (resource resource) (element resource-element) (element-index int) (parameter resource-parameter) (value string)) ;; void *h3dMapResStream( H3DRes res, int elem, int elemIdx, int stream, bool read, bool write ); (defh3fun ("h3dMapResStream" map-resource-stream) :pointer "Maps the stream of a resource element. This function maps the specified stream of a specified resource element and returns a pointer to the stream data. The required access to the data can be specified with the read write parameters. If read is false, the pointer will usually not contain meaningful data. Not all resource streams can be mapped with both read and write access. If it is not possible to map the stream, the function will return a NULL pointer. A mapped stream should be unmapped again as soon as possible but always before subsequent API calls are made. It is only possible to map one stream per resource at a time. Parameters: resource - handle to the resource to be accessed element - element type element-index - index of element stream - stream to be mapped read - flag indicating whether read access is required write - flag indicating whether write access is required Returns: pointer to stream data or NULL if stream cannot be mapped " (resource resource) (element resource-element) (element-index int) (stream int) (read boolean) (write boolean)) ;; void h3dUnmapResStream( H3DRes res ); (defh3fun ("h3dUnmapResStream" unmap-resource-stream) void "Unmaps a previously mapped resource stream. This function unmaps a resource stream that has been mapped before. Parameters: resource - handle to the resource to be unmapped Returns: nothing " (resource resource)) ;; H3DRes h3dQueryUnloadedResource( int index ); (defh3fun ("h3dQueryUnloadedResource" query-unloaded-resource) resource "Returns handle to an unloaded resource. This function looks for a resource that is not yet loaded and returns its handle. If there are no unloaded resources or the zero based index specified is greater than the number of the currently unloaded resources, 0 is returned. Parameters: index - index of unloaded resource within the internal list of unloaded resources (starting with 0) Returns: handle to an unloaded resource or 0 " (index int)) ;; void h3dReleaseUnusedResources(); (defh3fun ("h3dReleaseUnusedResources" release-unused-resources) void "Frees resources that are no longer used. This function releases resources that are no longer used. Unused resources were either told to be released by the user calling removeResource or are no more referenced by any other engine objects. Parameters: none Returns: nothing ") ;;;; --------------------------------------------------------------------------- ;;;; * Group: Specific resource management functions ;; H3DRes h3dCreateTexture( const char *name, int width, int height, int fmt, int flags ); (defh3fun ("h3dCreateTexture" create-texture) resource "Adds a Texture2D resource. This function tries to create and add a Texture resource with the specified name to the resource manager. If a Texture resource with the same name is already existing, the function fails. The texture is initialized with the specified dimensions and the resource is declared as loaded. This function is especially useful to create dynamic textures (e.g. for displaying videos) or output buffers for render-to-texture. *Note: The name string may not contain a colon character (:)* Parameters: name - name of the resource width - width of the texture image height - height of the texture image format - texture format (see stream formats) flags - flags used for creating the resource Returns: handle to the created resource or 0 in case of failure " (name string) (width int) (height int) (format resource-format) (flags resource-flags)) ;; void h3dSetShaderPreambles( const char *vertPreamble, const char *fragPreamble ); (defh3fun ("h3dSetShaderPreambles" set-shader-preambles) void "Sets preambles of all Shader resources. This function defines a header that is inserted at the beginning of all shaders. The preamble is used when a shader is compiled, so changing it will not affect any shaders that are already compiled. The preamble is useful for setting platform-specific defines that can be employed for creating several shader code paths, e.g. for supporting different hardware capabilities. Parameters: vertPreamble - preamble text of vertex shaders (default: empty string) fragPreamble - preamble text of fragment shaders (default: empty string) Returns: nothing " (vert-preamble string) (frag-preamble string)) ;; bool h3dSetMaterialUniform( H3DRes materialRes, const char *name, float a, float b, float c, float d ); (defh3fun ("h3dSetMaterialUniform" set-material-uniform) boolean "Sets a shader uniform of a Material resource. This function sets the specified shader uniform of the specified material to the specified values. Parameters: material-resource - handle to the material resource to be accessed name - name of the uniform as defined in Material resource a, b, c, d - values of the four components Returns: true if uniform was found, otherwise false " (material-resource resource) (name string) (a float) (b float) (c float) (d float)) ;; void h3dResizePipelineBuffers( H3DRes pipeRes, int width, int height ); (defh3fun ("h3dResizePipelineBuffers" resize-pipeline-buffers) void "Changes the size of the render targets of a pipeline. This function sets the base width and height which affects render targets with relative (in percent) size specification. Changing the base size is usually desired after engine initialization and when the window is being resized. Note that in case several cameras use the same pipeline resource instance, the change will affect all cameras. Parameters: pipeline-resource - the pipeline resource instance to be changed width - base width in pixels used for render targets with relative size height - base height in pixels used for render targets with relative size Returns: nothing " (pipeline-resource resource) (width int) (height int)) ;; bool h3dGetPipelineRenderTargetData( H3DRes pipelineRes, const char *targetName, ;; int bufIndex, int *width, int *height, int *compCount, ;; float *dataBuffer, int bufferSize ); (defh3fun ("h3dGetRenderTargetData" get-render-target-data) boolean "Reads the pixel data of a pipeline render target buffer. This function reads the pixels of the specified buffer of the specified render target from the specified pipeline resource and stores it in the specified float array. To calculate the size required for the array this function can be called with a NULL pointer for dataBuffer and pointers to variables where the width, height and number of (color) components (e.g. 4 for RGBA or 1 for depth) will be stored. The function is not intended to be used for real-time scene rendering but rather as a tool for debugging. For more information about the render buffers please refer to the Pipeline documentation. Parameters: pipeline-resource - handle to pipeline resource target-name - unique name of render target to access buffer-index - index of buffer to be accessed width - pointer to variable where the width of the buffer will be stored (can be NULL) height - pointer to variable where the height of the buffer will be stored (can be NULL) component-count - pointer to variable where the number of components will be stored (can be NULL) data-buffer - pointer to float array where the pixel data will be stored (can be NULL) buffer-size - size of dataBuffer array in bytes Returns: true if render target could be found, otherwise false " (pipeline-resource resource) (target-name string) (buffer-index int) (width (:pointer int)) (height (:pointer int)) (component-count (:pointer int)) (data-buffer (:pointer float)) (buffer-size int)) ;;;; --------------------------------------------------------------------------- ;;;; * Group: General Scene Graph Functions ;; int h3dGetNodeType( H3DNode node ); (defh3fun ("h3dGetNodeType" get-node-type) node-type "Returns the type of a scene node. This function returns the type of a specified scene node. If the node handle is invalid, he function returns the node type 'Unknown'. Parameters: node - handle to the scene node Returns: type of the scene node " (node node)) ;; H3DNode h3dGetNodeParent( H3DNode node ); (defh3fun ("h3dGetNodeParent" get-node-parent) node "Returns the parent of a scene node. This function returns the handle to the parent node of a specified scene node. If the specified node handle is invalid or the root node, 0 is returned. Parameters: node - handle to the scene node Returns: handle to parent node or 0 in case of failure " (node node)) ;; bool h3dSetNodeParent( H3DNode node, H3DNode parent ); (defh3fun ("h3dSetNodeParent" set-node-parent) boolean "Relocates a node in the scene graph. This function relocates a scene node. It detaches the node from its current parent and attaches it to the specified new parent node. If the attachment to the new parent is not possible, the function returns false. Relocation is not possible for the RootNode. Parameters: node - handle to the scene node to be relocated parent - handle to the new parent node Returns: true in case of success, otherwise false " (node node) (parent node)) ;; H3DNode h3dGetNodeChild( H3DNode node, int index ); (defh3fun ("h3dGetNodeChild" get-node-child) node "Returns the handle to a child node. This function looks for the n-th (index) child node of a specified node and returns its handle. If the child doesn't exist, the function returns 0. Parameters: node - handle to the parent node index - index of the child node Returns: handle to the child node or 0 if child doesn't exist " (node node) (index int)) ;; H3DNode h3dAddNodes( H3DNode parent, H3DRes sceneGraphRes ); (defh3fun ("h3dAddNodes" add-nodes) node "Adds nodes from a SceneGraph resource to the scene. This function creates several new nodes as described in a SceneGraph resource and ttaches them to a specified parent node. If an invalid scenegraph resource is specified or the scenegraph resource is unloaded, the function returns 0. Parameters: parent - handle to parent node to which the root of the new nodes will be attached scene-graph-resource - handle to loaded SceneGraph resource Returns: handle to the root of the created nodes or 0 in case of failure " (parent node) (scene-graph-resource resource)) ;; void h3dRemoveNode( H3DNode node ); (defh3fun ("h3dRemoveNode" remove-node) void "Removes a node from the scene. This function removes the specified node and all of it's children from the scene. Parameters: node - handle to the node to be removed Returns: nothing " (node node)) ;; bool h3dCheckNodeTransFlag( H3DNode node, bool reset ); (defh3fun ("h3dCheckNodeTransFlag" check-node-transform-flag) boolean "Checks if a scene node has been transformed by the engine. This function checks if a scene node has been transformed by the engine since the last time the transformation flag was reset. Therefore, it stores a flag that is set to true when a setTransformation function is called explicitely by the application or when the node transformation has been updated by the animation system. The function also makes it possible to reset the transformation flag. Parameters: node - handle to the node to be accessed reset - flag indicating whether transformation flag shall be reset Returns: true if node has been transformed, otherwise false " (node node) (reset boolean)) ;; bool h3dGetNodeTransform( H3DNode node, float *tx, float *ty, float *tz, ;; float *rx, float *ry, float *rz, ;; float *sx, float *sy, float *sz ); (defh3fun ("h3dGetNodeTransform" get-node-transform) void "Gets the relative transformation of a node. This function gets the translation, rotation and scale of a specified scene node object. The coordinates are in local space and contain the transformation of the node relative to its parent. Parameters: node - handle to the node which will be accessed tx, ty, tz - pointers to variables where translation of the node will be stored (can be NULL) rx, ry, rz - pointers to variables where rotation of the node in Euler angles will be stored (can be NULL) sx, sy, sz - pointers to variables where scale of the node will be stored (can be NULL) Returns: nothing " (node node) (tx (:pointer float)) (ty (:pointer float)) (tz (:pointer float)) (rx (:pointer float)) (ry (:pointer float)) (rz (:pointer float)) (sx (:pointer float)) (sy (:pointer float)) (sz (:pointer float))) ;; bool h3dSetNodeTransform( H3DNode node, float tx, float ty, float tz, ;; float rx, float ry, float rz, ;; float sx, float sy, float sz ); (defh3fun ("h3dSetNodeTransform" set-node-transform) void "Sets the relative transformation of a node. This function sets the relative translation, rotation and scale of a specified scene node object. The coordinates are in local space and contain the transformation of the node relative to its parent. Parameters: node - handle to the node which will be modified tx, ty, tz - translation of the node rx, ry, rz - rotation of the node in Euler angles sx, sy, sz - scale of the node Returns: nothing " (node node) (tx float) (ty float) (tz float) (rx float) (ry float) (rz float) (sx float) (sy float) (sz float)) ;; void h3dGetNodeTransMats( H3DNode node, const float **relMat, const float **absMat ); (defh3fun ("h3dGetNodeTransMats" get-node-transform-matrices) void "Returns the transformation matrices of a node. This function stores a pointer to the relative and absolute transformation matrices f the specified node in the specified pointer varaibles. Parameters: node - handle to the scene node to be accessed relMat - pointer to a variable where the address of the relative transformation matrix will be stored (can be NULL if matrix is not required) absMat - pointer to a variable where the address of the absolute transformation matrix will be stored (can be NULL if matrix is not required) Returns: nothing " (node node) (rel-mat (:pointer float)) (abs-mat (:pointer float))) ;; void h3dSetNodeTransMat( H3DNode node, const float *mat4x4 ); (defh3fun ("h3dSetNodeTransMat" set-node-transform-matrix) void "Sets the relative transformation matrix of a node. This function sets the relative transformation matrix of the specified scene node. It is basically the ame as setNodeTransform but takes directly a matrix instead of individual transformation parameters. Parameters: node - handle to the node which will be modified mat4x4 - pointer to a 4x4 matrix in column major order Returns: nothing " (node node) (mat-4x4 (:pointer float))) ;; int h3dGetNodeParamI( H3DNode node, int param ); (defh3fun ("h3dGetNodeParamI" get-node-parameter-i) int "Gets a property of a scene node. This function returns a specified property of the specified node. The property must be of the type int or H3DRes. Parameters: node - handle to the node to be accessed parameter - parameter to be accessed Returns: value of the parameter " (node node) (parameter node-parameter)) ;; bool h3dSetNodeParamI( H3DNode node, int param, int value ); (defh3fun ("h3dSetNodeParamI" set-node-parameter-i) void "Sets a property of a scene node. This function sets a specified property of the specified node to a specified value. The property must be of the type int or H3DRes. Parameters: node - handle to the node to be modified parameter - parameter to be modified value - new value for the specified parameter Returns: nothing " (node node) (parameter node-parameter) (value int)) ;; float h3dGetNodeParamF( H3DNode node, int param, int compIdx ); (defh3fun ("h3dGetNodeParamF" get-node-parameter-f) float "Gets a property of a scene node. This function returns a specified property of the specified node. The property must be of the type float. Parameters: node - handle to the node to be accessed parameter - parameter to be accessed component-index - component of the parameter to be modified Returns: value of the parameter " (node node) (parameter node-parameter) (component-index int)) ;; void h3dSetNodeParamF( H3DNode node, int param, int compIdx, float value ); (defh3fun ("h3dSetNodeParamF" set-node-parameter-f) void "Sets a property of a scene node. This function sets a specified property of the specified node to a specified value. The property must be of the type float. Parameters: node - handle to the node to be modified parameter - parameter to be modified component-index - component of the parameter to be modified value - new value for the specified parameter Returns: nothing " (node node) (parameter node-parameter) (component-index int) (value float)) ;; const char *h3dGetNodeParamStr( H3DNode node, int param ); (defh3fun ("h3dGetNodeParamStr" get-node-parameter-str) string "Gets a property of a scene node. This function returns a specified property of the specified node. The property must be of the type string (const char *). *Important Note: The pointer is const and allows only read access to the data. Do never try to modify the ata of the pointer since that can corrupt the engine's internal states!* Parameters: node - handle to the node to be accessed parameter - parameter to be accessed Returns: value of the property or empty string if no such property exists " (node node) (parameter node-parameter)) ;; void h3dSetNodeParamstr( H3DNode node, int param, const char *value ); (defh3fun ("h3dSetNodeParamStr" set-node-parameter-str) void "Sets a property of a scene node. This function sets a specified property of the specified node to a specified value. The property must be of the type string (const char *). Parameters: node - handle to the node to be modified parameter - parameter to be modified value - new value for the specified parameter Returns: nothing " (node node) (parameter node-parameter) (value string)) ;; int h3dGetNodeFlags( H3DNode node ); (defh3fun ("h3dGetNodeFlags" get-node-flags) node-flags "Gets the scene node flags. This function returns a bit mask containing the set scene node flags. Parameters: node - handle to the node to be accessed Returns: flag bitmask " (node node)) ;; void h3dSetNodeFlags( H3DNode node, int flags, bool recursive ); (defh3fun ("h3dSetNodeFlags" set-node-flags) void "Sets the scene node flags. This function sets the flags of the specified scene node. Parameters: node - handle to the node to be modified flags - new flag bitmask recursive - specifies whether flags should be applied recursively to all child nodes Returns: nothing " (node node) (flags node-flags) (recursivep boolean)) ;; void h3dGetNodeAABB( H3DNode node, float *minX, float *minY, float *minZ, ;; float *maxX, float *maxY, float *maxZ ); (defh3fun ("h3dGetNodeAABB" get-node-aabb) void "Gets the bounding box of a scene node. This function stores the world coordinates of the axis aligned bounding box of a specified node in the specified variables. The bounding box is represented using the minimum and maximum coordinates on all three axes. Parameters: node - handle to the node which will be accessed min-x, min-y, min-z - pointers to variables where minimum coordinates will be stored max-x, max-y, max-z - pointers to variables where maximum coordinates will be stored Returns: nothing " (node node) (min-x (:pointer float)) (min-y (:pointer float)) (min-z (:pointer float)) (max-x (:pointer float)) (max-y (:pointer float)) (max-z (:pointer float))) ;; int h3dFindNodes( H3DNode startNode, const char *name, int type ); (defh3fun ("h3dFindNodes" find-nodes) int "Finds scene nodes with the specified properties. This function loops recursively over all children of startNode and adds them to an internal list of results if they match the specified name and type. The result list is cleared each time this function is called. The function returns the number of nodes which were found and added to the list. Parameters: start-node - handle to the node where the search begins name - name of nodes to be searched (empty string for all nodes) type - type of nodes to be searched (SceneNodeTypes::Undefined for all types) Returns: number of search results " (start-node node) (name string) (type node-type)) ;; H3DNode h3dGetNodeFindResult( int index ); (defh3fun ("h3dGetNodeFindResult" get-node-find-result) node "Gets a result from the findNodes query. This function returns the n-th (index) result of a previous findNodes query. The result is the handle to a scene node with the poperties specified at the findNodes query. If the index doesn't exist in the result list the function returns 0. Parameters: index - index of search result Returns: handle to scene node from findNodes query or 0 if result doesn't exist " (index int)) ;; int h3dCastRay( H3DNode node, float ox, float oy, float oz, ;; float dx, float dy, float dz, int numNearest ); (defh3fun ("h3dCastRay" cast-ray) int "Performs a recursive ray collision query. This function checks recursively if the specified ray intersects the specified node or one of its children. The function finds intersections relative to the ray origin and returns the number of intersecting scene odes. The ray is a line segment and is specified by a starting point (the origin) and a finite direction vector which also defines its length. Currently this function is limited to returning intersections with Meshes. Parameters: node - node at which intersection check is beginning ox, oy, oz - ray origin dx, dy, dz - ray direction vector also specifying ray length num-nearest - maximum number of intersection points to be stored (0 for all) Returns: number of intersections " (node node) (ox float) (oy float) (oz float) (dx float) (dy float) (dz float) (num-nearest int)) ;; bool h3dGetCastRayResult( int index, H3DNode *node, float *distance, float *intersection ); (defh3fun ("h3dGetCastRayResult" get-cast-ray-result) boolean "Returns a result of a previous castRay query. This functions is used to access the results of a previous castRay query. The index is used to access a specific result. The intersection data is copied to the specified variables. Parameters: index - index of result to be accessed (range: 0 to number of results returned by castRay) node - handle of intersected node distance - distance from ray origin to intersection point intersection - coordinates of intersection point (float[3] array) Returns: true if index was valid and data could be copied, otherwise false " (index int) (node (:pointer node)) (distance (:pointer float)) (intersection (:pointer float))) ;; int h3dCheckNodeVisibility( H3DNode node, H3DNode cameraNode, bool checkOcclusion, bool calcLod ); (defh3fun ("h3dCheckNodeVisibility" check-node-visibility) int "Checks if a node is visible. This function checks if a specified node is visible from the perspective of a specified camera. The function always checks if the node is in the camera's frustum. If checkOcclusion is true, the function will take into account the occlusion culling information from the previous frame (if occlusion culling is disabled the flag is ignored). The flag calcLod determines whether the detail level for the node should be returned in case it is visible. The function returns -1 if the node is not visible, otherwise 0 (base LOD level) or the computed LOD level. Parameters: node - node to be checked for visibility camera-node - camera node from which the visibility test is done occlusion-p - specifies if occlusion info from previous frame should be taken into account calc-lod - specifies if LOD level should be computed Returns: computed LOD level or -1 if node is not visible " (node node) (camera-node node) (occlusion-p boolean) (calc-lod boolean)) ;;;; --------------------------------------------------------------------------- ;;;; * Group: Group-specific scene graph functions ;; H3DNode h3dAddGroupNode( H3DNode parent, const char *name ); (defh3fun ("h3dAddGroupNode" add-group-node) node "Adds a Group node to the scene. This function creates a new Group node and attaches it to the specified parent node. Parameters: parent - handle to parent node to which the new node will be attached name - name of the node Returns: handle to the created node or 0 in case of failure " (parent node) (name string)) ;;;; --------------------------------------------------------------------------- ;;;; * Group: Model-specific scene graph functions ;; H3DNode h3dAddModelNode( H3DNode parent, const char *name, H3DRes geometryRes ); (defh3fun ("h3dAddModelNode" add-model-node) node "Adds a Model node to the scene. This function creates a new Model node and attaches it to the specified parent node. Parameters: parent - handle to parent node to which the new node will be attached name - name of the node geometry-resource - Geometry resource used by Model node Returns: handle to the created node or 0 in case of failure " (parent node) (name string) (geometry-resource resource)) ;; void h3dSetupModelAnimStage( H3DNode modelNode, int stage, H3DRes animationRes, ;; int layer, const char *startNode, bool additive); (defh3fun ("h3dSetupModelAnimStage" setup-model-animation-stage) void "Configures an animation stage of a Model node. This function is used to setup the specified animation stage (channel) of the specified Model node. The function is used for animation blending. There is a fixed number of stages (by default 16) on which different animations can be played. The start node determines the first node (Joint or Mesh) to which the animation is recursively applied. If the start node is an empty string, the animation affects all animatable nodes (Joints and Meshes) of the model. If a NULL is used for animationRes, the stage is cleared and the previous animation is removed. A simple way to do animation mixing is using additive animations. If a stage is configured to be additive the engine calculates the difference between the current frame and the first frame in the animation and adds this delta to the current transformation of the joints or meshes. Parameters: model-node - handle to the Model node to be modified stage - index of the animation stage to be configured animation-resource - handle to Animation resource (can be 0) layer - layer id start-node - name of first node to which animation shall be applied (or empty string) additive - flag indicating whether stage is additive Returns: nothing " (model-node node) (stage int) (animation-resource resource) (layer int) (start-node string) (additive boolean)) ;; void h3dSetModelAnimParams( H3DNode modelNode, int stage, float time, float weight ); (defh3fun ("h3dSetModelAnimParams" set-model-animation-parameters) void "Sets the parameters of an animation stage in a Model node. This function sets the current animation time and weight for a specified stage of the specified model. The time corresponds to the frames of the animation and the animation is looped if the time is higher than the maximum number of frames in the Animation resource. The weight is used for animation blending and determines how much influence the stage has compared to the other active stages. When the sum of the weights of all stages is more than one, the animations on the lower stages get priority. Parameters: model-node - handle to the Model node to be modified stage - index of the animation stage to be modified time - new animation time/frame weight - new blend weight Returns: nothing " (model-node node) (stage int) (time float) (weight float)) ;; bool h3dSetModelMorpher( H3DNode modelNode, const char *target, float weight ); (defh3fun ("h3dSetModelMorpher" set-model-morpher) boolean "Sets the weight of a morph target. This function sets the weight of a specified morph target. If the target parameter is an empty string the weight of all morph targets in the specified Model node is modified. If the specified morph target is not found the function returns false. Parameters: modelNode - handle to the Model node to be modified target - name of morph target weight - new weight for morph target Returns: true if morph target was found, otherwise false " (model-node node) (target string) (weight float)) ;;;; --------------------------------------------------------------------------- ;;;; * Group: Mesh-specific scene graph functions ;; H3DNode h3dAddMeshNode( H3DNode parent, const char *name, H3DRes materialRes, ;; int batchStart, int batchCount, ;; int vertRStart, int vertREnd ); (defh3fun ("h3dAddMeshNode" add-mesh-node) node "Adds a Mesh node to the scene. This function creates a new Mesh node and attaches it to the specified parent node. Parameters: parent-node - handle to parent node to which the new node will be attached name - name of the node material-resource - material resource used by Mesh node batch-start - first triangle index of mesh in Geometry resource of parent Model node batch-count - number of triangle indices used for drawing mesh vertex-rstart - first vertex in Geometry resource of parent Model node vertex-rend - last vertex in Geometry resource of parent Model node Returns: handle to the created node or 0 in case of failure " (parent-node node) (name string) (material-resource resource) (batch-start int) (batch-count int) (vertex-r-start int) (vertex-r-end int)) ;;;; --------------------------------------------------------------------------- ;;;; * Group: Joint-specific scene graph functions ;; H3DNode h3dAddJointNode( H3DNode parent, const char *name, int jointIndex ); (defh3fun ("h3dAddJointNode" add-joint-node) node "Adds a Joint node to the scene. This function creates a new Joint node and attaches it to the specified parent node. Parameters: parent-node - handle to parent node to which the new node will be attached name - name of the node joint-index - index of joint in Geometry resource of parent Model node Returns: handle to the created node or 0 in case of failure " (parent-node node) (name string) (joint-index int)) ;;;; --------------------------------------------------------------------------- ;;;; * Group: Light-specific scene graph functions ;; H3DNode h3dAddLightNode( H3DNode parent, const char *name, H3DRes materialRes, ;; const char *lightingContext, const char *shadowContext ); (defh3fun ("h3dAddLightNode" add-light-node) node "Adds a Light node to the scene. This function creates a new Light node and attaches it to the specified parent node. The direction vector of the untransformed light node is pointing along the the negative z-axis. The specified material resource can define uniforms and projective textures. Furthermore it can contain a shader for doing lighting calculations if deferred shading s used. If no material is required the parameter can be zero. The context names define which shader contexts are used when rendering shadow maps or doing light calculations for forward rendering configurations. Parameters: parent-node - handle to parent node to which the new node will be attached name - name of the node material-resource - material resource for light configuration or 0 if not used lighting-context - name of the shader context used for doing light calculations shadow-context - name of the shader context used for doing shadow map rendering Returns: handle to the created node or 0 in case of failure " (parent-node node) (name string) (material-resource resource) (lighting-context string) (shadow-context string)) ;;;; --------------------------------------------------------------------------- ;;;; * Group: Camera-specific scene graph functions ;; H3DNode h3dAddCameraNode( H3DNode parent, const char *name, H3DRes pipelineRes ); (defh3fun ("h3dAddCameraNode" add-camera-node) node "Adds a Camera node to the scene. This function creates a new Camera node and attaches it to the specified parent node. Parameters: parent-node - handle to parent node to which the new node will be attached name - name of the node pipeline-resource - pipeline resource used for rendering Returns: handle to the created node or 0 in case of failure " (parent-node node) (name string) (pipeline-resource resource)) ;; void h3dSetupCameraView( H3DNode cameraNode, float fov, float aspect, ;; float nearDist, float farDist ); (defh3fun ("h3dSetupCameraView" setup-camera-view) void "Sets the planes of a camera viewing frustum. This function calculates the view frustum planes of the specified camera node using the specified view arameters. Parameters: camera-node - handle to the Camera node which will be modified fov - field of view (FOV) angle aspect - aspect ratio near-distance - distance of near clipping plane far-distance - distance of far clipping plane Returns: nothing " (camera-node node) (fov float) (aspect float) (near-distance float) (far-distance float)) ;; void h3dGetCameraProjMat( H3DNode cameraNode, float *projMat ); (defh3fun ("h3dGetCameraProjMat" get-camera-projection-matrix) void "Gets the camera projection matrix. This function gets the camera projection matrix used for bringing the geometry to screen space and copies it to the specified array. Parameters: camera-node - handle to Camera node projection-matrix - pointer to float array with 16 elements Returns: nothing " (camera-node node) (projection-matrix (:pointer float))) ;;;; --------------------------------------------------------------------------- ;;;; * Group: Emitter-specific scene graph functions ;; H3DNode h3dAddEmitterNode( H3DNode parent, const char *name, ;; H3DRes materialRes, H3DRes effectRes, ;; int maxParticleCount, int respawnCount ); (defh3fun ("h3dAddEmitterNode" add-emitter-node) node "Adds a Emitter node to the scene. This function creates a new Emitter node and attaches it to the specified parent node. Parameters: parent-node - handle to parent node to which the new node will be attached name - name of the node material-resource - handle to Material resource used for rendering effect-resource - handle to Effect resource used for configuring particle properties max-particle-count - maximal number of particles living at the same time respawn-count - number of times a single particle is recreated after dying (-1 for infinite) Returns: handle to the created node or 0 in case of failure " (parent-node node) (name string) (material-resource resource) (effect-resource resource) (max-particle-count int) (respawn-count int)) ;; void h3dAdvanceEmitterTime( H3DNode emitterNode, float timeDelta ); (defh3fun ("h3dAdvanceEmitterTime" advance-emitter-time) void "Advances the time value of an Emitter node. This function advances the simulation time of a particle system and continues the particle simulation with timeDelta being the time elapsed since the last call of this function. The specified node must be an Emitter node. Parameters: emitter-node - handle to the Emitter node which will be modified time-delta - time delta in seconds Returns: true in case of success otherwise false " (emitter-node node) (time-delta float)) ;; bool h3dHasEmitterFinished( H3DNode emitterNode ); (defh3fun ("h3dHasEmitterFinished" emitter-finished-p) boolean "Checks if an Emitter node is still alive. This function checks if a particle system is still active and has living particles or will spawn new particles. The specified node must be an Emitter node. The function can be used to check when a not infinitely running emitter for an effect like an explosion can be removed from the scene. Parameters: emitter-node - handle to the Emitter node which is checked Returns: true if Emitter will no more emit any particles, otherwise or in case of failure false " (emitter-node node)) ;;;; ----------------------------------------------------------------------- ;;;; * Horde3D Utilities (defconstant +max-stat-mode+ 2 "Maximum stat mode number supported in show-frame-stats.") ;; void h3dutFreeMem( char **ptr ); (defh3ufun ("h3dutFreeMem" free-mem) void "Frees memory allocated by the Utility Library. This utility function frees the memory that was allocated by another function of the Utility Library. Parameters: ptr - address of a pointer that references to memory allocated by the Utility Library Returns: nothing " (ptr :pointer)) ;; bool h3dutDumpMessages(); (defh3ufun ("h3dutDumpMessages" dump-messages) boolean "Writes all messages in the queue to a log file. This utility function pops all messages from the message queue and writes them to a HTML formated log file 'EngineLog.html'. Parameters: none Returns: true in case of success, otherwise false ") ;;;; --------------------------------------------------------------------------- ;;;; * Group: OpenGL-related functions ;; bool h3dutInitOpenGL( int hDC ); (defh3ufun ("h3dutInitOpenGL" init-open-gl) boolean "Initializes OpenGL. This utility function initializes an OpenGL rendering context in a specified window component. *Currently this function is only available on Windows platforms.* Parameters: hDC - handle to device context for which OpenGL context shall be created Returns: true in case of success, otherwise false " (h-dc int)) ;; void h3dutReleaseOpenGL(); (defh3ufun ("h3dutReleaseOpenGL" release-open-gl) void "Releases OpenGL. This utility function destroys the previously created OpenGL rendering context. *Currently this function is only available on Windows platforms.* Parameters: none Returns: nothing ") ;; void h3dutSwapBuffers(); (defh3ufun ("h3dutSwapBuffers" swap-buffers) void "Displays the rendered image on the screen. This utility function displays the image rendered to the previously initialized OpenGL context on the screen by copying it from the backbuffer to the frontbuffer. *Currently this function is only available on Windows platforms.* Parameters: none Returns: nothing ") ;;;; --------------------------------------------------------------------------- ;;;; * Group: Resource management ;; const char *h3dutGetResourcePath( int type ); (defh3ufun ("h3dutGetResourcePath" get-resource-path) string "Returns the search path of a resource type. This function returns the search path of a specified resource type. Parameters: type - type of resource Returns: pointer to the search path string " (type resource-type)) ;; void h3dutSetResourcePath( int type, const char *path ); (defh3ufun ("h3dutSetResourcePath" set-resource-path) void "Sets the search path for a resource type. This function sets the search path for a specified resource type. Parameters: type - type of resource path - path where the resources can be found ((back-)slashes at end are removed) Returns: nothing " (type resource-type) (path string)) ;; bool h3dutLoadResourcesFromDisk( const char *contentDir ); (defh3ufun ("h3dutLoadResourcesFromDisk" load-resources-from-disk) boolean "Loads previously added resources from a data drive. This utility function loads previously added and still unloaded resources from the specified directories on a data drive. Several search paths can be specified using the pipe character (|) as separator. All resource names are directly converted to filenames and the function tries to find them in the specified directories using the given order of the search paths. Parameters: contentDir - directories where data is located on the drive ((back-)slashes at end are removed) Returns: false if at least one resource could not be loaded, otherwise true " (content-dir string)) ;; DLL H3DRes h3dutCreateGeometryRes( const char *name, int numVertices, int numTriangleIndices, ;; float *posData, unsigned int *indexData, short *normalData ;; short *tangentData, short *bitangentData, ;; float *texData1, float *texData2 ); (defh3ufun ("h3dutCreateGeometryRes" create-geometry-resource) resource "Creates a Geometry resource from specified vertex data. This utility function allocates and initializes a Geometry resource with the specified vertex attributes and indices. The optional tangent space data (normal, tangent, bitangent) is encoded as int16, where -1.0 maps to -32'767 and 1.0f to +32'767. Parameters: name - unique name of the new Geometry resource num-vertices - number of vertices num-triangle-indices - number of vertex indices position-data - vertex positions (xyz) index-data - indices defining triangles normal-data - normals xyz (optional, can be NULL) tangent-data - tangents xyz (optional, can be NULL) bitangent-data - bitangents xyz (required if tangents specified, otherwise NULL) texture-data-1 - first texture coordinate uv set (optional, can be NULL) texture-data-2 - second texture coordinate uv set (optional, can be NULL) Returns: handle to new Geometry resource or 0 in case of failure " (name string) (num-vertices int) (num-triangle-indices int) (position-data (:pointer :float)) (index-data (:pointer :ushort)) (normal-data (:pointer :short)) (tangent-data (:pointer :short)) (bitangent-data (:pointer :short)) (texture-data-1 (:pointer :float)) (texture-data-2 (:pointer :float))) ;; bool h3dutScreenshot( const char *filename ); (defh3ufun ("h3dutScreenshot" screenshot) boolean "Writes the content of the backbuffer to a tga file. This function reads back the content of the backbuffer and writes it to a tga file with the specified filename and path. Parameters: filename - filename and path of the output tga file Returns: true if the file could be written, otherwise false " (filename string)) ;; bool h3dutCreateTGAImage( const unsigned char *pixels, int width, int height, ;; int bpp, char **outData, int *outSize ); (defh3ufun ("h3dutCreateTGAImage" create-tga-image) boolean "Creates a TGA image in memory. This utility function allocates memory at the pointer outData and creates a TGA image from the specified pixel data. The dimensions of the image have to be specified as well as the bit depth. The created TGA-image-data can be used as Texture2D or TexureCube resource in the engine. *Note: The memory allocated by this routine has to freed manually using the freeMem function.* Parameters: pixels - pointer to pixel source data in BGR(A) format from which TGA-image is constructed; memory layout: pixel with position (x, y) in image (origin of image is upper left corner) has memory location (y * width + x) * (bpp / 8) in pixels-array width - width of source image height - height of source image bpp - color bit depth of source data (valid values: 24, 32) out-data - address of a pointer to which the address of the created memory block is written out-size - variable to which to size of the created memory block is written Returns: false if at least one resource could not be loaded, otherwise true " (pixels (:pointer :uchar)) (width int) (height int) (bpp int) (out-data :pointer) (out-size (:pointer int))) ;;;; --------------------------------------------------------------------------- ;;;; * Group: Scene graph ;; void h3dutPickRay( H3DNode cameraNode, float nwx, float nwy, ;; float *ox, float *oy, float *oz, float *dx, float *dy, float *dz ); (defh3ufun ("h3dutPickRay" pick-ray) void "* Calculates the ray originating at the specified camera and window coordinates This utility function takes normalized window coordinates (ranging from 0 to 1 with the origin being the bottom left corner of the window) and returns ray origin and direction for the given camera. The function is especially useful for selecting objects by clicking on them. Parameters: camera-node - camera used for picking nwx, nwy - normalized window coordinates ox, oy, oz - calculated ray origin dx, dy, dz - calculated ray direction Returns: nothing " (camera-node node) (nwx float) (nwy float) (ox (:pointer float)) (oy (:pointer float)) (oz (:pointer float)) (dx (:pointer float)) (dy (:pointer float)) (dz (:pointer float))) ;; H3DNode h3dutPickNode( H3DNode cameraNode, float nwx, float nwy ); (defh3ufun ("h3dutPickNode" pick-node) node "Returns the scene node which is at the specified window coordinates. This utility function takes normalized window coordinates (ranging from 0 to 1 with the origin being the bottom left corner of the window) and returns the scene node which is visible at that location. The function is especially useful for selecting objects by clicking on them. Currently picking is only working for Meshes. Parameters: camera-node - camera used for picking nwx, nwy - normalized window coordinates Returns: handle of picked node or 0 if no node was hit " (camera-node node) (nwx float) (nwy float)) ;;;; --------------------------------------------------------------------------- ;;;; * Group: Overlays ;; void h3dutShowText( const char *text, float x, float y, float size, ;; float colR, float colG, float colB, ;; H3DRes fontMaterialRes, int layer ); (defh3ufun ("h3dutShowText" show-text) void "Shows text on the screen using a font texture. This utility function uses overlays to display a text string at a specified position on the screen. The font texture of the specified font material has to be a regular 16x16 grid containing all ASCII characters in row-major order. The layer corresponds to the layer parameter of overlays. Parameters: text - text string to be displayed x, y - position of the lower left corner of the first character; for more details on coordinate system see overlay documentation size - size (scale) factor of the font col-r, col-g, col-b - font color font-material-resource - font material resource used for rendering Returns: nothing " (text string) (x float) (y float) (size float) (col-r float) (col-g float) (col-b float) (font-material-resource resource)) ;; void h3dutShowFrameStats( H3DRes fontMaterialRes, H3DRes panelMaterialRes, int mode ); (defh3ufun ("h3dutShowFrameStats" show-frame-statistics) void "Shows frame statistics on the screen. This utility function displays statistics for the current frame in the upper left corner of the screen. Since the statistic counters are reset after the call, it should be called exactly once per frame to obtain correct values. Parameters: font-material-resource - font material resource used for drawing text panel-material-resource - material resource used for drawing info box mode - display mode, specifying which data is shown (<= +max-stat-mode+) Returns: nothing " (font-material-resource resource) (panel-material-resource resource) (mode int)) ;;; bindings.lisp ends here
71,301
Common Lisp
.lisp
1,593
41.034526
116
0.719043
anwyn/cl-horde3d
15
0
0
EPL-1.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
20dfc86909ecd9c2daa9c28de5790418ba4dae4b3a2c00bdf2b7216d87a67e7c
10,620
[ -1 ]
10,621
sound-bindings.lisp
anwyn_cl-horde3d/src/sound-bindings.lisp
;;; sound-bindings.lisp --- bindings to the horde3d sound extension ;;; _ _ _ _ _ ;;; ___ ___ _ _ _ __ __| | | |__ (_)_ __ __| (_)_ __ __ _ ___ ;;; / __|/ _ \| | | | '_ \ / _` |_____| '_ \| | '_ \ / _` | | '_ \ / _` / __| ;;; \__ \ (_) | |_| | | | | (_| |_____| |_) | | | | | (_| | | | | | (_| \__ \ ;;; |___/\___/ \__,_|_| |_|\__,_| |_.__/|_|_| |_|\__,_|_|_| |_|\__, |___/ ;;; |___/ ;;; ;;; Copyright (C) 2009 Ole Arndt <[email protected]> ;;; (cl:defpackage #:horde3d-sound-cffi (:nicknames #:%h3d-sound) (:use #:cffi #:%h3d) (:import-from #:common-lisp #:in-package) (:export #:open-device #:close-device #:get-open-device #:query-device #:get-distance-model #:set-distance-model #:add-listener-node #:get-active-listener #:set-active-listener #:add-sound-node #:sound-playing-p #:play-sound #:pause-sound #:rewind-sound)) (in-package :horde3d-sound-cffi) (defcenum sound-resource-types "The available resource types. :sound - A sound resource " (:sound 200)) (defcenum sound-node-types "The available scene node types. :listener - Listener node :sound - Sound node " (:listener 201) (:sound 202)) (deftypedenum listener-node-parameters "The available Listener node parameters. :listener-master-gain - Amplitude multiplier (volume), this affects all sounds (default: 1.0) [type: float] :listener-doppler-factor - *currently has no effect* Exaggeration factor for doppler effect (default: 1.0) [type: float] :listener-speed-of-sound - *currently has no effect* Speed of sound in same units as velocities (default: 343.3) [type: float] " (:listener-master-gain 20000) :float :listener-doppler-factor :float :listener-speed-of-sound :float) (deftypedenum sound-node-parameters "The available Sound node parameters. :sound-resource - The resource used for audio playback [type: resource] :sound-gain - Amplitude multiplier (volume) (default: 1.0) [type: float] :sound-pitch - Pitch shift (value range: 0.5-2.0; default: 1.0) [type: float] :sound-offset - Position of the sound's playback in seconds [type: float] :sound-loop - Determines if the sound should loop after it reaches the end (Values: 0, 1) [type: int] :sound-max-distance - This is used for distance based attenuation calculations, for explanation on how this exactly is used in each distance model see the DistanceModels section. This will also clamp distances greater than this value if the InverseDistanceClamped, LinearDistanceClamped or ExponentDistanceClamped distance model is used. (default: MAX_FLOAT) [type: float] :sound-rolloff-factor - This is used for distance based attenuation calculations, for explanation on how this exactly is used in each distance model see the DistanceModels section. (default: 1.0) [type: float] :sound-reference-distance - This is used for distance based attenuation calculations, for explanation on how this exactly is used in each distance model see the DistanceModels section. This will also clamp distances below this value if the InverseDistanceClamped, LinearDistanceClamped or ExponentDistanceClamped distance model is used. (default: 1.0) [type: float] :sound-min-gain - This indicates the minimal gain guaranteed for the sound. At the end of processing of various attenuation factors such as distance based attenuation and the sound's Gain value, the effective gain calculated is compared to this value. If the effective gain is lower than this value, this value is applied. This happens before the listener's MasterGain is applied. (value range: 0.0-1.0; default: 0.0) [type: float] :sound-max-gain - This indicates the maximal gain permitted for the sound. At the end of processing of various attenuation factors such as distance based attenuation and the sound's Gain value, the effective gain calculated is compared to this value. If the effective gain is higher than this value, this value is applied. This happens before the listener's MasterGain is applied. (value range: 0.0-1.0; default: 1.0) [type: float] " (:sound-resource 21000) :resource :sound-gain :float :sound-pitch :float :sound-offset :float :sound-loop :int :sound-max-distance :float :sound-rolloff-factor :float :sound-reference-distance :float :sound-min-gain :float :sound-max-gain :float) (defcenum distance-model "The available distance models. The variables used in the calculations explained:: - Distance = the distance between the listener and sound node - Gain = the sound's volume after distance based attenuation - ReferenceDistance, RolloffFactor and MaxDistance = sound node parameters :none - No distance based attenuation will be applied. :inverse-distance - Distance based attenuation will be calculated using the following formula: Gain = ReferenceDistance / (ReferenceDistance + RolloffFactor * (Distance-ReferenceDistance)); ReferenceDistance indicates the distance which the listener will experience the sound's Gain value. RolloffFactor can used to increase or decrease the range of a sound by increasing or decreasing the attenuation, respectivly. :inverse-distance-clamped - This is the same as InverseDistance but it clamps the Distance before calculating the effective Gain: Distance = max(Distance, ReferenceDistance); Distance = min(Distance, MaxDistance); (default distance model) :linear-distance - This models a linear drop-off in gain as distance increases between the sound and listener. Distance based attenuation will be calculated using the following formula: Gain = (1-RolloffFactor * (Distance-ReferenceDistance) / (MaxDistance-ReferenceDistance)); :linear-distance-clamped - This is the same as LinearDistance but it clamps the Distance before calculating the effective Gain: Distance = max(Distance, ReferenceDistance); Distance = min(Distance, MaxDistance); :exponent-distance - This models an exponential drop-off in gain as distance increases between the sound and listener. Distance based attenuation will be calculated using the following formula: Gain = (Distance / ReferenceDistance) ^ (-RolloffFactor); where the ^ operation raises it's first operand to the power of it's second operand. :exponent-distance-clamped - This is the same as ExponentDistance but it clamps the Distance before calculating the effective Gain: Distance = max(Distance, ReferenceDistance); Distance = min(Distance, MaxDistance); " :none :inverse-distance :inverse-distance-clamped :linear-distance :linear-distance-clamped :exponent-distance :exponent-distance-clamped) ;;;; Group: Sound Extension ;;; Basic functions (defh3fun ("h3dOpenDevice" open-device) boolean "Opens a sound device for playback. This function opens and initializes a sound device for playback. This needs to be called before any sound resources or nodes can be created or used. It will fail if another device is already open. Parameters: device - name of the device to open (use NULL for default device) Returns: true in case of success, otherwise false " (device string)) (defh3fun ("h3dCloseDevice" close-device) void "Closes the currently open sound device. This function closes the currently open sound device. Parameters: none Returns: nothing ") (defh3fun ("h3dGetOpenDevice" get-open-device) string "Gets the name of the currently open sound device. This function returns the name of the currently open sound device. Parameters: none Returns: name of the open device or NULL is none is open. ") (defh3fun ("h3dQueryDevice" query-device) string "Returns the name of a sound device. This function returns the name of a sound device from an internal list. If the index specified is greater than the number of the available sound devices, NULL is returned. Parameters: index - index of sound device within the internal list (starting with 0) Returns: name of a sound device or NULL " (index int)) (defh3fun ("h3dGetDistanceModel" get-distance-model) distance-model "Gets the active distance model. This function return the distance model used for calculating distance based attenuation. Parameters: none Returns: currently active distance model ") (defh3fun ("h3dSetDistanceModel" set-distance-model) boolean "Sets the active distance model. This function sets the distance model used for calculating distance based attenuation. Parameters: model - distance model to use Returns: true if the distance model could be set, otherwise false " (model distance-model)) ;;;; Group: Listener-specific scene graph functions ;;; NodeHandle addListenerNode( NodeHandle parent, const char *name ); (defh3fun ("h3dAddListenerNode" add-listener-node) node "Adds a Listener node to the scene. This function creates a new Listener node and attaches it to the specified parent node. Parameters: parent - handle to parent node to which the new node will be attached name - name of the node Returns: handle to the created node or 0 in case of failure " (parent node) (name string)) ;;; NodeHandle getActiveListener(); (defh3fun ("h3dGetActiveListener" get-active-listener) node "Returns the handle of the active Listener node. This function returns the handle of the currently active Listener node. Parameters: none Returns: handle to active Listener node or 0 if there is no active Listener node ") ;;; bool setActiveListener( NodeHandle listenerNode ); (defh3fun ("h3dSetActiveListener" set-active-listener) boolean "Sets the active Listener node. This function sets the currently active Listener node. This node will act as the ears and all 3D sound calculations will be based on this node's position and orientation. Parameters: listener-node - handle to the Listener node. Returns: true in case of success, otherwise false " (listener-node node)) ;;;; Group: Sound-specific scene graph functions ;;; NodeHandle addSoundNode( NodeHandle parent, const char *name, ResHandle soundRes ); (defh3fun ("h3dAddSoundNode" add-sound-node) node "Adds a Sound node to the scene. This function creates a new Sound node and attaches it to the specified parent node. Parameters: parent - handle to parent node to which the new node will be attached name - name of the node sound-resource - handle to Sound resource which will be used for playback Returns: handle to the created node or 0 in case of failure " (parent node) (name string) (sound-resource resource)) ;;; bool isSoundPlaying( NodeHandle soundNode ); (defh3fun ("h3dIsSoundPlaying" sound-playing-p) boolean "Checks if an Sound node is playing. This function returns whether the Sound node is currently playing or not. Parameters: sound-node - handle to the Sound node Returns: true if the Sound node is currently playing, otherwise false " (sound-node node)) ;;; void playSound( NodeHandle soundNode ); (defh3fun ("h3dPlaySound" play-sound) void "Starts the audio playback of a Sound node. This function will start the audio playback of a Sound node. Parameters: sound-node - handle to the Sound node Returns: nothing " (sound-node node)) ;;; void pauseSound( NodeHandle soundNode ); (defh3fun ("h3dPauseSound" pause-sound) void "Pauses the playback of a Sound node. This function will pause the playback of a Sound node. Parameters: sound-node - handle to the Sound node Returns: nothing " (sound-node node)) ;;; void rewindSound( NodeHandle soundNode ); (defh3fun ("h3dRewindSound" rewind-sound) void "Rewinds the playback of a Sound node. This function will rewind the playback of a Sound node. If the Sound node is playing while being rewinded it will continue to play from it's rewinded position. Parameters: sound-node - handle to the Sound node Returns: nothing " (sound-node node)) ;;; sound-bindings.lisp ends here
13,205
Common Lisp
.lisp
267
43.037453
156
0.680184
anwyn/cl-horde3d
15
0
0
EPL-1.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
fb68ed02da2d4c1e13ddfe9a72fcb0d8def3b631c8c0458ee10f9e3ed9a8b3b8
10,621
[ -1 ]
10,622
bindings-package.lisp
anwyn_cl-horde3d/src/bindings-package.lisp
;;; bindings-package.lisp --- package definition and exported symbols ;;; ;;; Copyright (C) 2009 Ole Arndt <[email protected]> ;;; (in-package :cl-user) (defpackage #:horde3d-cffi (:nicknames #:%h3d) (:use #:common-lisp #:cffi) (:shadow #:float #:boolean #:string) (:export ;; libraries #:horde3d #:horde3d-utils ;; defines #:enum-type #:notice-enum-type #:deftypedenum #:defh3fun ;; conditions #:no-such-enum-type ;; constants #:+root-node+ ;; types #:resource #:node #:boolean #:float #:string #:int #:void ;; enums #:option #:statistics #:resource-type #:resource-flags #:resource-format #:resource-parameter #:resource-element #:node-type #:node-parameter ;; basic functions #:get-version-string #:check-extension #:get-error #:init #:release #:setup-viewport #:render #:finalize-frame #:clear ;; General functions #:get-message #:get-option #:set-option #:get-statistics ;; Overlays #:show-overlays #:clear-overlays ;; Resource management #:get-resource-type #:get-resource-name #:get-next-resource #:find-resource #:add-resource #:clone-resource #:remove-resource #:resource-loaded-p #:load-resource #:unload-resource #:get-resource-element-count #:find-resource-element #:get-resource-parameter-i #:set-resource-parameter-i #:get-resource-parameter-f #:set-resource-parameter-f #:get-resource-parameter-str #:set-resource-parameter-str #:map-resource-stream #:unmap-resource-stream #:query-unloaded-resource #:release-unused-resources ;; Specific resource management functions #:create-texture #:set-shader-preambles #:set-material-uniform #:resize-pipeline-buffers #:get-render-target-data ;; General scene graph functions #:get-node-type #:get-node-parent #:set-node-parent #:get-node-child #:add-nodes #:remove-node #:set-node-activation #:check-node-transform-flag #:get-node-transform #:set-node-transform #:get-node-transform-matrices #:set-node-transform-matrix #:get-node-parameter-i #:set-node-parameter-i #:get-node-parameter-f #:set-node-parameter-f #:get-node-parameter-str #:set-node-parameter-str #:get-node-flags #:set-node-flags #:get-node-aabb #:find-nodes #:get-node-find-result #:cast-ray #:get-cast-ray-result #:check-node-visibility ;; Group-specific scene graph functions #:add-group-node ;; Model-specific scene graph functions #:add-model-node #:setup-model-animation-stage #:set-model-animation-parameters #:set-model-morpher ;; Mesh-specific scene graph functions #:add-mesh-node ;; Joint-specific scene graph functions #:add-joint-node ;; Light-specific scene graph functions #:add-light-node ;; Camera-specific scene graph functions #:add-camera-node #:setup-camera-view #:get-camera-projection-matrix ;; Emitter-specific scene graph functions #:add-emitter-node #:advance-emitter-time #:emitter-finished-p ;; Horde utils #:free-mem #:dump-messages #:init-open-gl #:release-open-gl #:swap-buffers #:get-resource-path #:set-resource-path #:load-resources-from-disk #:screenshot #:create-tga-image #:create-geometry-resource #:pick-ray #:pick-node #:show-text #:show-frame-statistics)) ;;; binding-package.lisp ends here
3,517
Common Lisp
.lisp
152
19.118421
69
0.683248
anwyn/cl-horde3d
15
0
0
EPL-1.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
37e4551c0abeff04c6a19cd062c9e1550c75d562e76875c9f7a417fabb817dcc
10,622
[ -1 ]
10,623
enums.lisp
anwyn_cl-horde3d/src/enums.lisp
;;; enums.lisp --- horde3d enums ;;; ___ _ __ _ _ _ __ ___ ___ ;;; / _ \ '_ \| | | | '_ ` _ \/ __| ;;; | __/ | | | |_| | | | | | \__ \ ;;; \___|_| |_|\__,_|_| |_| |_|___/ ;;; ;;; Copyright (C) 2009 Ole Arndt <[email protected]> ;;; (in-package :horde3d-cffi) ;;;; --------------------------------------------------------------------------- ;;;; * Group: Enumerations (defcenum option "The available engine option parameters. :max-log-level - Defines the maximum log level; only messages which are smaller or equal to this value (hence more important) are published in the message queue. (Default: 4) :max-num-messages - Defines the maximum number of messages that can be stored in the message queue (Default: 512) :trilinear-filtering - Enables or disables trilinear filtering for textures; only affects textures that are loaded after setting the option. (Values: 0, 1; Default: 1) :max-anisotropy - Sets the quality for anisotropic filtering; only affects textures that are loaded after setting the option. (Values: 1, 2, 4, 8; Default: 1) :texture-compression - Enables or disables texture compression; only affects textures that are loaded after setting the option. (Values: 0, 1; Default: 0) :load-textures - Enables or disables loading of texture images; option can be used to minimize loading times for testing. (Values: 0, 1; Default: 1) :fast-animation - Disables or enables inter-frame interpolation for animations. (Values: 0, 1; Default: 1) :shadowmap-size - Sets the size of the shadow map buffer (Values: 128, 256, 512, 1024, 2048; Default: 1024) :sample-count - Maximum number of samples used for multisampled render targets; only affects pipelines that are loaded after setting the option. (Values: 0, 2, 4, 8, 16; Default: 0) :wireframe-mode - Enables or disables wireframe rendering :debug-view-mode - Enables or disables debug view where geometry is rendered in wireframe without shaders and lights are visualized using their screen space bounding box. (Values: 0, 1; Default: 0) :dump-failed-shaders - Enables or disables storing of shader code that failed to compile in a text file; this can be useful in combination with the line numbers given back by the shader compiler. (Values: 0, 1; Default: 0) :gather-time-statistics - Enables or disables gathering of time stats that are useful for profiling (Values: 0, 1; Default: 1) " (:max-log-level 1) :max-num-messages :trilinear-filtering :max-anisotropy :texture-compression :load-textures :fast-animation :shadow-map-size :sample-count :wireframe-mode :debug-view-mode :dump-failed-shaders :gather-time-statistics) (defcenum statistics "The available engine statistic parameters. :triangle-count - Number of triangles that were pushed to the renderer :batch-count - Number of batches (draw calls) :light-pass-count - Number of lighting passes :frame-time - Time in ms between two finalizeFrame calls :animation-time - CPU time in ms spent for animation :geo-update-time - CPU time in ms spent for software skinning and morphing :particle-sim-time - CPU time in ms spent for particle simulation and updates :fwd-lights-gpu-time - GPU time in ms spent for forward lighting passes :def-lights-gpu-time - GPU time in ms spent for drawing deferred light volumes :shadows-gpu-time - GPU time in ms spent for generating shadow maps :particle-gpu-time - GPU time in ms spent for drawing particles :texture-vmem - Estimated amount of video memory used by textures (in Mb) :geometry-vmem - Estimated amount of video memory used by geometry (in Mb) " (:triangle-count 100) :batch-count :light-pass-count :frame-time :animation-time :geo-update-time :particle-sim-time :fwd-lights-gpu-time :def-lights-gpu-time :shadows-gpu-time :particle-gpu-time :texture-vmem :geometry-vmem) ;;;; --------------------------------------------------------------------------- ;;;; Resource types (defcenum resource-types "Enum: resource-type - The available resource types. :undefined - An undefined resource, returned by getResourceType in case of error :scene-graph - Scene graph subtree stored in XML format :geometry - Geometrical data containing bones, vertices and triangles :animation - Animation data :material - Material script :code - Text block containing shader source code :shader - Shader program :texture-2d - Two-dimensional texture map :texture-cube - Cube map texture :effect - Particle configuration :pipeline - Rendering pipeline " (:undefined 0) :scene-graph :geometry :animation :material :code :shader :texture :particle-effect :pipeline) (defctype resource-type (multi-enum :enums (resource-types #+horde3d-terrain-extension terrain-resource-types #+horde3d-sound-extension sound-resource-types)) "All resource types.") ;;;; ---------------------------------------------------------------------------- ;;;; Resource flags & formats (defbitfield resource-flags "Enum: resource-flags - The available flags used when adding a resource. :no-query - Excludes resource from being listed by queryUnloadedResource function. :no-texture-compression - Disables texture compression for Texture2D or TextureCube resource. :no-texture-mipmaps - Disables generation of mipmaps for textures. :texture-cubemap - Sets Texture resource to be a cubemap. :texture-dynamic - Enables more efficient updates of Texture resource streams. :texture-renderable - Makes Texture resource usable as render target. :texture-srgb - Indicates that Texture resource is in sRGB color space and should be converted to linear space when being sampled. " (:no-query #x0001) :no-texture-compression :no-texture-mipmaps :texture-cubemap :texture-dynamic :texture-renderable :texture-srgb) (defcenum resource-format "The available resource stream formats. :unknown - Unknown format :texture-bgra8 - 8-bit BGRA texture :texture-dxt1 - DXT1 compressed texture :texture-dxt3 - DXT3 compressed texture :texture-dxt5 - DXT5 compressed texture :texture-rgba16f - Half float RGBA texture :texture-rgba32f - Float RGBA texture " :unknown :texture-bgra8 :texture-dxt1 :texture-dxt3 :texture-dxt5 :texture-rgba16f :texture-rgba32f) ;;;; ---------------------------------------------------------------------------- ;;;; Resource parameters ;;; Geometry resources (defcenum geometry-resource-elements "The available Geometry resource accessors. :geometry-element - Base element " (:geometry-element 200)) (deftypedenum geometry-resource-parameters "The available Geometry resource accessors. :geometry-index-count - Number of indices [read-only] :geometry-vertex-count - Number of vertices [read-only] :geometry-indices-16 - Flag indicating whether index data is 16 or 32 bit [read-only] :geometry-index-stream - Triangle index data (uint16 or uint32, depending on flag) :geometry-vertex-position-stream - Vertex position data (float x, y, z) :geometry-vertex-tangent-stream - Vertex tangent frame (TBN) data (float tx, ty, tz, bx, by, bz, nx, ny, nz) :geometry-vertex-static-stream - Vertex static attribute data (float u0, v0, float4 jointIndices, float4 jointWeights, float u1, v1) " (:geometry-index-count 201) :int :geometry-vertex-count :int :geometry-indices-16 :int :geometry-index-stream :int :geometry-vertex-position-stream :int :geometry-vertex-tangent-stream :int :geometry-vertex-static-stream :int) ;;; Animation resources (defcenum animation-resource-elements "The available Animation resource element accessors. :entity-element - Stored animation entities (joints and meshes) " (:animation-entity 300)) (deftypedenum animation-resource-parameters "The available Animation resource accessors. :entity-frame-count - Number of frames stored for a specific entity [read-only] " (:animation-entity-frame-count 301) :int) ;;; Material resources (defcenum material-resource-elements "The available Material resource element accessors. :material-element - Base element :material-sampler-element - Sampler element :material-uniform-element - Uniform element " (:material-element 400) :material-sampler-element :material-uniform-element) (deftypedenum material-resource-parameters "The available Material resource accessors. :material-class - Material class :material-link - Material resource that is linked to this material :material-shader-resource - Shader resource :material-sampler-name - Name of sampler (string) [read-only] :material-sampler-texture-resource - Texture resource bound to sampler :material-uniform-name - Name of uniform [read-only] :material-uniform-value - Value of uniform (a, b, c, d) " (:material-class 403) :string :material-link :resource :material-shader-resource :resource :material-sampler-name :string :material-sampler-texture-resource :resource :material-uniform-name :string :material-uniform-value :float) ;;; Shader resources (defcenum shader-resource-elements "The available Shader resource element accessors. :shader-context-element - Context element :shader-sampler-element - Sampler element :shader-uniform-element - Uniform element " (:shader-context-element 600) :shader-sampler-element :shader-uniform-element) (deftypedenum shader-resource-parameters "The available Shader resource accessors. :shader-context-name - Name of context [read-only] :shader-sampler-name - Name of sampler [read-only] :shader-uniform-name - Name of uniform [read-only] :shader-uniform-size - Size (number of components) of uniform [read-only] :shader-uniform-default-value - Default value of uniform (a, b, c, d) " (:shader-context-name 603) :string :shader-sampler-name :string :shader-uniform-name :string :shader-uniform-size :int :shader-uniform-default-value :float) ;;; Texture resources (defcenum texture-resource-elements "The available Texture resource element accessors. :texture-element - Base element :texture-image-element - Subresources of the texture. A texture consists, depending on the type, of a number of equally sized slices which again can have a fixed number of mipmaps. Each image element represents the base image of a slice or a single mipmap level of the corresponding slice. " (:texture-element 700) :texture-image-element) (deftypedenum texture-resource-parameters "The available Texture resource accessors. :texture-format - Texture format [read-only] :texture-slice-count - Number of slices (1 for 2D texture and 6 for cubemap) [read-only] :texture-image-width - Image width [read-only] :texture-image-height - Image height [read-only] :texture-image-pixel-stream - Pixel data of an image. The data layout matches the layout specified by the texture format with the exception that half-float is converted to float. The first element in the data array corresponds to the lower left corner. " :texture-format :int :texture-slice-count :int :texture-image-width :int :texture-image-height :int :texture-image-pixel-stream :int) ;;; Particle effect resources (defcenum particle-effect-resource-elements "The available ParticleEffect resource element accessors. :particle-element - General particle configuration " (:particle-element 800)) (deftypedenum particle-effect-resource-parameters "The available ParticleEffect resource accessors. :particle-channel-move-velocity - Velocity channel :particle-channel-rot-velocity - Angular velocity channel :particle-channel-size - Size channel :particle-channel-color-red - Red color component channel :particle-channel-color-green - Green color component channel :particle-channel-color-blue - Blue color component channel :particle-channel-color-alpha - Alpha channel :particle-life-min - Minimum value of random life time (in seconds) :particle-life-max - Maximum value of random life time (in seconds) :particle-channel-start-min - Minimum for selecting initial random value of channel :particle-channel-start-max - Maximum for selecting initial random value of channel :particle-channel-end-rate - Remaining percentage of initial value when particle is dying :particle-channel-drag - Drag force channel (?) " (:particle-channel-move-velocity 801) :float :particle-channel-rot-velocity :float :particle-channel-size :float :particle-channel-color-red :float :particle-channel-color-green :float :particle-channel-color-blue :float :particle-channel-color-alpha :float :particle-life-min :float :particle-life-max :float :particle-channel-start-min :float :particle-channel-start-max :float :particle-channel-end-rate :float :particle-channel-drag :float) ;;; Pipeline resources (defcenum pipeline-resource-elements "The available Pipeline resource element accessors. :pipeline-stage-element - Pipeline stage " (:pipeline-stage-element 900)) (deftypedenum pipeline-resource-parameters "The available Pipeline resource accessors. :pipeline-stage-name - Name of stage [read-only] :pipeline-stage-activation - Flag indicating whether stage is active " (:pipeline-stage-name 901) :string :pipeline-stage-activation :int) (defctype resource-parameter (multi-enum :enums (geometry-resource-parameters animation-resource-parameters material-resource-parameters shader-resource-parameters texture-resource-parameters particle-effect-resource-parameters pipeline-resource-parameters #+horde3d-terrain-extension terrain-resource-parameters #+horde3d-sound-extension sound-resource-parameters)) "Parameters for all resources.") (defctype resource-element (multi-enum :enums (geometry-resource-elements animation-resource-elements material-resource-elements shader-resource-elements texture-resource-elements particle-effect-resource-elements pipeline-resource-elements #+horde3d-terrain-extension terrain-resource-elements #+horde3d-sound-extension sound-resource-elements)) "All resource parameters that denote a resource element.") ;;;; ---------------------------------------------------------------------------- ;;;; Node types (defcenum node-types "The available scene node types. :undefined - An undefined node type, returned by get-node-type in case of error :group - Group of different scene nodes :model - 3D model with optional skeleton :mesh - Subgroup of a model with triangles of one material :joint - Joint for skeletal animation :light - Light source :camera - Camera giving view on scene :emitter - Particle system emitter " (:undefined 0) :group :model :mesh :joint :light :camera :emitter) (defctype node-type (multi-enum :enums (node-types #+horde3d-terrain-extension terrain-node-types #+horde3d-sound-extension sound-node-types)) "The type of a Horde3D node.") (defbitfield node-flags "The available scene node flags. :no-draw - Excludes scene node from all rendering :no-cast-shadow - Excludes scene node from list of shadow casters :no-ray-query - Excludes scene node from ray intersection queries :inactive - Deactivates scene node so that it is completely ignored (combination of all flags above) " (:no-draw #x0001) :no-cast-shadow :no-ray-query :inactive) ;;; ---------------------------------------------------------------------------- ;;; Node parameters (deftypedenum node-parameters "The available scene node parameters: :node-name - Name of the scene node [type: string] :node-attachment - Optional application-specific meta data for a node encapsulated in an 'Attachment' XML string [type: string] " (:node-name 1) :string :node-attachment :string) (deftypedenum model-node-parameters "The available Model node parameters: :model-geometry-resource - Geometry resource used for the model [type: resource] :model-software-skinning - Enables or disables software skinning (default: 0) [type: int] :model-lod-dist-1 - Distance to camera from which on LOD1 is used (default: infinite) [type: float] (must be a positive value larger than 0.0) :model-lod-dist-2 - Distance to camera from which on LOD2 is used (may not be smaller than LodDist1) (default: infinite) [type: float] :model-lod-dist-3 - Distance to camera from which on LOD3 is used (may not be smaller than LodDist2) (default: infinite) [type: float] :model-lod-dist-4 - Distance to camera from which on LOD4 is used (may not be smaller than LodDist3) (default: infinite) [type: float] " (:model-geometry-resource 200) :resource :model-software-skinning :int :model-lod-dist-1 :float :model-lod-dist-2 :float :model-lod-dist-3 :float :model-lod-dist-4 :float) (deftypedenum mesh-node-parameters "The available Mesh node parameters. :mesh-material-resource - Material resource used for the mesh :mesh-batch-start - First triangle index of mesh in Geometry resource of parent Model node [read-only] :mesh-batch-count - Number of triangle indices used for drawing mesh [read-only] :mesh-vertex-rstart - First vertex in Geometry resource of parent Model node [read-only] :mesh-vertex-rend - Last vertex in Geometry resource of parent Model node [read-only] :mesh-lod-level - LOD level of Mesh; the mesh is only rendered if its LOD level corresponds to the model's current LOD level which is calculated based on the LOD distances (default: 0) " (:mesh-material-resource 300) :resource :mesh-batch-start :int :mesh-batch-count :int :mesh-vertex-rstart :int :mesh-vertex-rend :int :mesh-lod-level :int) (deftypedenum joint-node-parameters "The available Joint node parameters. :joint-index - Index of joint in Geometry resource of parent Model node [read-only] " ( :joint-index 400) :int) (deftypedenum light-node-parameters "The available Light node parameters. :light-material-resource - Material resource used for the light :light-radius - Radius of influence (default: 100.0) :light-fov - Field of view (FOV) angle (default: 90.0) :light-color - Diffuse color RGB (default: 1.0, 1.0, 1.0) :light-color-multiplier - Diffuse color multiplier for altering intensity, mainly useful for HDR (default: 1.0) :light-shadow-map-count - Number of shadow maps used for light source (values: 0, 1, 2, 3, 4; default: 0)] :light-shadow-split-lambda - Constant determining segmentation of view frustum for Parallel Split Shadow Maps (default: 0.5) :light-shadow-map-bias - Bias value for shadow mapping to reduce shadow acne (default: 0.005) :light-lighting-context - Name of shader context used for computing lighting :light-shadow-context - Name of shader context used for generating shadow map " (:light-material-resource 500) :resource :light-radius :float :light-fov :float :light-color :float :light-color-multiplier :float :light-shadow-map-count :int :light-shadow-split-lambda :float :light-shadow-map-bias :float :light-lighting-context :string :light-shadow-context :string) (deftypedenum camera-node-parameters "The available Camera node parameters. :camera-pipeline-resource - Pipeline resource used for rendering :camera-out-texture-resource - 2D Texture resource used as output buffer (can be 0 to use main framebuffer) (default: 0) :camera-out-buffer-index - Index of the output buffer for stereo rendering (values: 0 for left eye, 1 for right eye) (default: 0) :camera-left-plane - Coordinate of left plane relative to near plane center (default: -0.055228457) :camera-right-plane - Coordinate of right plane relative to near plane center (default: 0.055228457) :camera-bottom-plane - Coordinate of bottom plane relative to near plane center (default: -0.041421354f) :camera-top-plane - Coordinate of top plane relative to near plane center (default: 0.041421354f) :camera-near-plane - Distance of near clipping plane (default: 0.1) :camera-far-plane - Distance of far clipping plane (default: 1000) :camera-viewport-x - Position x-coordinate of the lower left corner of the viewport rectangle (default: 0) :camera-viewport-y - Position y-coordinate of the lower left corner of the viewport rectangle (default: 0) :camera-viewport-width - Width of the viewport rectangle (default: 320) :camera-viewport-height - Height of the viewport rectangle (default: 240) :camera-ortho - Flag for setting up an orthographic frustum instead of a perspective one (default: 0) :camera-occlussion-culling - Flag for enabling occlusion culling (default: 0) " (:camera-pipeline-resource 600) :resource :camera-out-texture-resource :resource :camera-out-buffer-index :int :camera-left-plane :float :camera-right-plane :float :camera-bottom-plane :float :camera-top-plane :float :camera-near-plane :float :camera-far-plane :float :camera-viewport-x :int :camera-viewport-y :int :camera-viewport-width :int :camera-viewport-height :int :camera-ortho :int :camera-occlussion-culling :int) (deftypedenum emitter-node-parameters "The available Emitter node parameters. :emitter-material-resource - Material resource used for rendering :emitter-particle-effect-resource - ParticleEffect resource which configures particle properties :emitter-max-count - Maximal number of particles living at the same time :emitter-respawn-count - Number of times a single particle is recreated after dying (-1 for infinite) :emitter-delay - Time in seconds before emitter begins creating particles (default: 0.0) :emitter-emission-rate - Maximal number of particles to be created per second (default: 0.0) :emitter-spread-angle - Angle of cone for random emission direction (default: 0.0) :emitter-force - Force vector XYZ applied to particles (default: 0.0, 0.0, 0.0) " (:emitter-material-resource 700) :resource :emitter-particle-effect-resource :resource :emitter-max-count :int :emitter-respawn-count :int :emitter-delay :float :emitter-emission-rate :float :emitter-spread-angle :float :emitter-force :float) (defctype node-parameter (multi-enum :enums (node-parameters model-node-parameters mesh-node-parameters joint-node-parameters light-node-parameters camera-node-parameters emitter-node-parameters #+horde3d-terrain-extension terrain-node-parameters #+horde3d-sound-extension listener-node-parameters #+horde3d-sound-extension sound-node-parameters)) "The type of a Horde3D node.") ;;; enums.lisp ends here
24,749
Common Lisp
.lisp
507
43.712032
134
0.681417
anwyn/cl-horde3d
15
0
0
EPL-1.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
1f9c870c511d2a2a18969a0329cb874ca28a6413c4832386d91601331587b6bb
10,623
[ -1 ]
10,624
terrain.lisp
anwyn_cl-horde3d/src/terrain.lisp
;;; terrain.lisp --- bindings to the horde3d terrain extension ;;; _ _ ;;; | |_ ___ _ __ _ __ __ _(_)_ __ ;;; | __/ _ \ '__| '__/ _` | | '_ \ ;;; | || __/ | | | | (_| | | | | | ;;; \__\___|_| |_| \__,_|_|_| |_| ;;; ;;; Copyright (C) 2009 Ole Arndt <[email protected]> (in-package :horde3d) ;;;; Terrain Extension (import-export %h3d-terrain:add-terrain-node %h3d-terrain:create-geometry-resource) ;;; terrain.lisp ends here
475
Common Lisp
.lisp
13
33.923077
62
0.451754
anwyn/cl-horde3d
15
0
0
EPL-1.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
eae5aaceb4daa903ad41faa9573fcb9faa88d406593e12925aa18b86fa273717
10,624
[ -1 ]
10,625
libraries.lisp
anwyn_cl-horde3d/src/libraries.lisp
;;; libraries.lisp --- library definitions ;;; _ _ _ _ ;;; | (_) |__ _ __ __ _ _ __(_) ___ ___ ;;; | | | '_ \| '__/ _` | '__| |/ _ \/ __| ;;; | | | |_) | | | (_| | | | | __/\__ \ ;;; |_|_|_.__/|_| \__,_|_| |_|\___||___/ ;;; ;;; Copyright (C) 2009 Ole Arndt <[email protected]> ;;; (in-package :horde3d-cffi) (define-foreign-library horde3d (:darwin (:framework "Horde3D")) (:windows "Horde3D.dll" :calling-convention :stdcall) (:unix (:or "libHorde3D.so" "libHorde3D.so.1"))) (define-foreign-library horde3d-utils (:darwin (:framework "Horde3DUtils")) (:windows "Horde3DUtils.dll" :calling-convention :stdcall) (:unix (:or "libHorde3DUtils.so" "libHorde3DUtils.so.1"))) (use-foreign-library horde3d-utils) (use-foreign-library horde3d) ;;; libraries.lisp ends here
812
Common Lisp
.lisp
21
36.809524
60
0.550318
anwyn/cl-horde3d
15
0
0
EPL-1.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
1daf58e9cacb4d6edfedd4b4d294accad64cff79a8db5ce9905330d43feab03a
10,625
[ -1 ]
10,626
horde3d-examples.asd
anwyn_cl-horde3d/horde3d-examples.asd
;;; -*- lisp -*- (defsystem :horde3d-examples :description "The Horde3d examples ported to Common Lisp." :long-description "The Horde3d examples ported to Common Lisp. Run (horde3d-examples:knight) and (horde3d-examples:chicago)." :version "0.2" :author "Ole Arndt <[email protected]>" :maintainer "Ole Arndt <[email protected]>" :licence "EPL 1.0" :depends-on (:horde3d :lispbuilder-sdl) :components ((:static-file "horde3d-examples.asd") (:module "examples" :components ((:file "package") (:file "examples" :depends-on ("package")) (:file "knight" :depends-on ("examples")) (:file "chicago" :depends-on ("examples"))))))
802
Common Lisp
.asd
16
38.5
84
0.574713
anwyn/cl-horde3d
15
0
0
EPL-1.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
cd4203284cc4ae073d706e0b08274b388eabbbd8e27eb523930ea2e66a67a3bf
10,626
[ -1 ]
10,627
horde3d.asd
anwyn_cl-horde3d/horde3d.asd
;;; -*- lisp -*- ;;; If Horde3d has been compiled with the sound or terrain extensions ;;; you can enable the respective bindings by pushing ;;; :horde3d-terrain-extension or :horde3d-terrain-extension to *features* ;;; before loading the system. ;;; ;; (push :horde3d-terrain-extension cl:*features*) ;; (push :horde3d-sound-extension cl:*features*) (defsystem :horde3d :description "CFFI bindings for the Horde3D rendering engine." :long-description "CFFI bindings for the Horde3D rendering engine." :version "0.2" :author "Ole Arndt <[email protected]>" :maintainer "Ole Arndt <[email protected]>" :licence "EPL 1.0" :depends-on (:cffi) :in-order-to ((test-op (load-op :horde3d-test))) :perform (test-op :after (op c) (funcall (intern (string '#:horde3d-tests) '#:horde3d-test))) :components ((:doc-file "README.org") (:static-file "horde3d.asd") (:module "src" :components ((:file "bindings-package") (:file "libraries" :depends-on ("bindings-package")) (:file "types" :depends-on ("libraries")) #+horde3d-terrain-extension (:file "terrain-bindings" :depends-on ("types")) #+horde3d-sound-extension (:file "sound-bindings" :depends-on ("types")) (:file "enums" :depends-on ("types" #+horde3d-terrain-extension "terrain-bindings" #+horde3d-sound-extension "sound-bindings")) (:file "bindings" :depends-on ("enums")) ;; lispification (:file "package" :depends-on ("bindings-package")) (:file "horde3d" :depends-on ("package" "bindings")) #+horde3d-terrain-extension (:file "terrain" :depends-on ("horde3d")) #+horde3d-sound-extension (:file "sound" :depends-on ("horde3d")))))) (defsystem :horde3d-test :components ((:module "test" :components ((:file "suite") (:file "horde3d" :depends-on ("suite"))))) :depends-on (:horde3d :stefil)) (defmethod operation-done-p ((o test-op) (c (eql (find-system :horde3d)))) (values nil))
2,169
Common Lisp
.asd
51
34.980392
81
0.61211
anwyn/cl-horde3d
15
0
0
EPL-1.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
cc7b62f29b85061f67877c98a1a94740e1d274e20dd2379d0d251e637f4010f4
10,627
[ -1 ]
10,661
columna.lisp
Z-Shang_Columna/columna.lisp
;;;; -*- coding:utf-8 -*- (in-package :cl-user) (defpackage :columna (:use :cl) (:export ;;DB-OPs: #:set-db-path #:create-db #:create-table #:create-col #:create-with-schema #:insert #:lookup #:update #:del #:get-pos #:take #:mapcol ;;File System IO #:write-data-to-file #:load-data-from-file #:load-data-from-file-to-db #:with-db-file ;;Reader-Macro: #:read-db-pos #:enable-reader-macro #:disable-reader-macro ;;Utils: #:make-selector #:_v #:_i)) (in-package :columna) (eval-when (:compile-toplevel :load-toplevel :execute) (ql:quickload :bordeaux-threads)) (defparameter *dbs* (make-hash-table)) (defparameter *lock* (bt:make-recursive-lock)) (defparameter *default-db-path* #P"~/.columna/") (defun set-db-path (path) (setf *default-db-path* path)) (defmacro with-lock (&body body) `(bt:with-recursive-lock-held (*lock*) ,@body)) (defun first-nil (arr) (loop :for i :from 0 :to (1- (length arr)) :when (null (aref arr i)) :return i :finally (return -1))) (defun lookup-table (name table) (if (listp name) (mapcar #'(lambda (n) (list 'quote (lookup-table n table))) name) (loop :for i :from 0 :to (1- (length table)) :when (equal name (getf (aref table i) :name)) :return (getf (aref table i) :data) :finally (return 'DNE)))) (defstruct db (name nil :type symbol) (tables nil :type list)) (defstruct selector (pred nil :type function) (col nil :type (or symbol list))) (defun create-db (name) (with-lock (if (symbolp name) (unless (gethash name *dbs*) (setf (gethash name *dbs*) (make-db :name name :tables nil))) (warn "Invalid name of type: ~A, must be a symbol" (type-of name))))) (defun create-table (name size db) (with-lock (if (symbolp name) (if (and (> size 0) (integerp size)) (unless (getf (db-tables db) name) (setf (getf (db-tables db) name) (make-array size :initial-element nil))) (warn "Invalid size of table: ~A, must be a positive integer" size)) (warn "Invalid name of type: ~A, must be a symbol" (type-of name))))) (defun create-col (name table &optional &key pred) (with-lock (if (symbolp name) (unless (< (first-nil table) 0) (setf (aref table (first-nil table)) (list :name name :data (list) :pred (if pred pred #'(lambda (x) (declare (ignore x)) t))))) (warn "Invalid name of type: ~A, must be a symbol" (type-of name))))) (defun insert (values table) (cond ((listp values) (with-lock (if (= (length values) (length table)) (let ((types (loop :for i :from 0 :to (1- (length table)) :collect (funcall (getf (aref table i) :pred) (nth i values))))) (if (loop :for i :from 0 :to (1- (length types)) :when (not (nth i types)) :do (warn "Type: ~A of values at: ~A doesn't match the predicate of column" (type-of (nth i values)) i) :always (nth i types)) (loop :for i :from 0 :to (1- (length table)) :do (setf (getf (aref table i) :data) (cons (nth i values) (getf (aref table i) :data)))))) (warn "Values doesn't match table size: ~A" (length table))))))) (defun get-pos (&key db (table nil) (col nil) (pos nil)) (let ((d (gethash db *dbs*))) (if d (if table (let ((tbl (getf (db-tables d) table))) (if tbl (if col (let ((c (lookup-table col tbl))) (if (listp c) (if pos (if (integerp pos) (if (< pos (length c)) (nth pos c) (warn "Position: ~A is out of range" pos)) (warn "Invalid position: ~A" pos)) c) (warn "Column: ~A doesn't exist in ~A.~A" col db table))) tbl) (warn "Table: ~A doesn't exist in DB: ~A" table db))) d) (warn "DB: ~A doesn't exist" db)))) (defun mapcam (f n lst) (if (null lst) nil (if (not (zerop (mod (length lst) n))) (error "Then length of list: ~A is not a multiple of number: ~A" (length lst) n) (cons (apply f (subseq lst 0 n)) (mapcam f n (nthcdr n lst)))))) (defmacro create-with-schema (db &body body) `(if (oddp (length ',body)) (warn "Invalid number of arguments: ~A" (length ',body)) (progn (create-db ',db) (mapcam #'(lambda (tbl cols) (create-table tbl (length cols) (get-pos :db ',db)) (mapcar #'(lambda (c) (if (consp c) (create-col (car c) (get-pos :db ',db :table tbl) :pred (eval (cadr c))) (create-col c (get-pos :db ',db :table tbl)))) cols)) 2 ',body)))) (defun del (p table) (typecase p (integer (with-lock (let ((l (1- (length table)))) (loop :for i :from 0 :to l :do (setf (getf (aref table i) :data) (remove-if (constantly t) (getf (aref table i) :data) :start p :count 1)))))) (selector (let ((pivot (lookup-table (selector-col p) table))) (if (equal pivot 'DNE) (error "Invalid selector with pivot column: ~A" (selector-col p)) (with-lock (let* ((l (1- (length pivot))) (r (loop :for i :from 0 :to l :when (not (funcall (selector-pred p) (nth i pivot))) :collect (loop :for j :from 0 :to (1- (length table)) :collect (nth i (getf (aref table j) :data))))) (res (loop :for i :from 0 :to (1- (length (car r))) :collect (mapcar #'(lambda (l) (nth i l)) r)))) (loop :for i :from 0 :to (1- (length table)) :do (setf (getf (aref table i) :data) (nth i res)))))))))) (defun lookup (p table) (typecase p (list (if (loop :for i :in p :thereis (not (integerp i))) (error "Invalid argument, [integer] or selector only") (with-lock (loop :for i :in p :collect (loop :for j :from 0 :to (1- (length table)) :collect (nth i (getf (aref table j) :data))))))) (selector (if (listp (selector-col p)) (let ((pivots (lookup-table (selector-col p) table))) (if (loop :for piv :in pivots :thereis (equalp piv 'DNE)) (error "Invalid selector with pivot columns: ~A" (selector-col p)) (if (> (length (remove-duplicates (mapcar #'length pivots))) 1) (error "The pivot columns' lengths don't match") (let ((marks (eval `(mapcar ,(selector-pred p) ,@pivots)))) (with-lock (loop :for i :from 0 :to (1- (length marks)) :when (nth i marks) :collect (loop :for j :from 0 :to (1- (length table)) :collect (nth i (getf (aref table j) :data))))))))) (let ((pivot (lookup-table (selector-col p) table))) (if (equal pivot 'DNE) (error "Invalid selector with pivot column: ~A" (selector-col p)) (with-lock (loop :for i :from 0 :to (1- (length pivot)) :when (funcall (selector-pred p) (nth i pivot)) :collect (loop :for j :from 0 :to (1- (length table)) :collect (nth i (getf (aref table j) :data))))))))))) ;;N could be a function that takes the index and the current value (defun update (p n table) (when (listp n) (if (not (= (length n) (length table))) (error "Invalid number of arguments, need: ~A, given: ~A" (length table) (length n)))) (typecase p (list (if (loop :for i :in p :thereis (not (integerp i))) (error "Invalid argument, [integer] or selector only") (with-lock (loop :for i :in p :do (loop :for j :from 0 :to (1- (length table)) :do (if (listp n) (if (functionp (nth j n)) (setf (nth i (getf (aref table j) :data)) (funcall (nth j n) i (nth i (getf (aref table j) :data)))) (setf (nth i (getf (aref table j) :data)) (nth j n))) (if (functionp n) (setf (nth i (getf (aref table j) :data)) (funcall n i (nth i (getf (aref table j) :data)))) (setf (nth i (getf (aref table j) :data)) n)))))))) (selector (if (listp (selector-col p)) (let ((pivots (lookup-table (selector-col p) table))) (if (loop :for piv :in pivots :thereis (equalp piv 'DNE)) (error "Invalid argument, [integer] or selector only") (if (> (length (remove-duplicates (mapcar #'length pivots))) 1) (error "The pivot columns' lengths don't match") (let ((marks (eval `(mapcar ,(selector-pred p) ,@pivots)))) (with-lock (loop :for i :from 0 :to (1- (length marks)) :when (nth i marks) :do (loop :for j :from 0 :to (1- (length table)) :do (if (listp n) (if (functionp (nth j n)) (setf (nth i (getf (aref table j) :data)) (funcall (nth j n) i (nth i (getf (aref table j) :data)))) (setf (nth i (getf (aref table j) :data)) (nth j n))) (if (functionp n) (setf (nth i (getf (aref table j) :data)) (funcall n i (nth i (getf (aref table j) :data)))) (setf (nth i (getf (aref table j) :data)) n)))))))))) (let ((pivot (lookup-table (selector-col p) table))) (if (equal pivot 'DNE) (error "Invalid argument, [integer] or selector only") (with-lock (loop :for i :from 0 :to (1- (length pivot)) :when (funcall (selector-pred p) (nth i pivot)) :do (loop :for j :from 0 :to (1- (length table)) :do (if (listp n) (if (functionp (nth j n)) (setf (nth i (getf (aref table j) :data)) (funcall (nth j n) i (nth i (getf (aref table j) :data)))) (setf (nth i (getf (aref table j) :data)) (nth j n))) (if (functionp n) (setf (nth i (getf (aref table j) :data)) (funcall n i (nth i (getf (aref table j) :data)))) (setf (nth i (getf (aref table j) :data)) n)))))))))))) (defun take (n table) (when (not (integerp n)) (error "~A is not an integer!" n)) (lookup (loop :for n :from 0 :to (1- n) :collect n) table)) ;; Map a function over a table (defun mapcol (fn tbl) (with-lock (let ((table (loop :for p :from 0 :to (1- (length tbl)) :collect (cons 'list (getf (aref tbl p) :data))))) (eval `(mapcar ,fn ,@table))))) (defun _v (i v) (declare (ignore i)) v) (defun _i (i v) (declare (ignore v)) i) (defun write-data-to-file (db-name file-path) (let ((db (gethash db-name *dbs*))) (if (null db) (error "DB: ~A Doesn't exist!" db-name) (with-lock (progn (ensure-directories-exist file-path) (with-open-file (file (merge-pathnames (make-pathname :name (write-to-string db-name)) file-path) :direction :output :if-exists :supersede :if-does-not-exist :create) (let ((tbls (mapcam #'(lambda (x y) (cons x y)) 2 (db-tables db)))) (loop for tbl in tbls do (format file "~A~%" (write-to-string (list :n (car tbl) :v (loop for c being the elements of (cdr tbl) collect (getf c :data))))))))))))) (defun load-data-from-file-to-db (file-path db &key (override nil)) (with-open-file (file file-path :direction :input :if-does-not-exist nil) (if (null file) (error "DB File: ~A Doesn't exist!" file-path) (with-lock (when file (loop :for line = (read-line file nil) :while line :do (let* ((data (read-from-string line)) (tbl-name (getf data :n)) (values (getf data :v)) (tbl (getf (db-tables db) tbl-name))) (loop :for i :from 0 :to (1- (length values)) :do (if override (setf (getf (aref tbl i) :data) (nth i values)) (setf (getf (aref tbl i) :data) (append (nth i values) (getf (aref tbl i) :data))))))))))))
15,218
Common Lisp
.lisp
319
30.310345
128
0.433519
Z-Shang/Columna
10
1
0
AGPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
66fb1ccd640c5a7c20412abae338b68587aa09ce1ed21c3b44a1dcd5f021d154
10,661
[ -1 ]
10,662
reader-macro.lisp
Z-Shang_Columna/reader-macro.lisp
;;;; -*- coding:utf-8 -*- (in-package :columna) (defvar *prev-readtable* nil) (defun read-db-pos (stream char) (declare (ignore char)) (let ((sym (read-delimited-list #\] stream))) (case (length sym) (0 (warn "Invalid DB Pos")) (1 `(get-pos :DB ',(first sym))) (2 `(get-pos :DB ',(first sym) :TABLE ',(second sym))) (3 `(get-pos :DB ',(first sym) :TABLE ',(second sym) :COL ',(third sym))) (4 `(get-pos :DB ',(first sym) :TABLE ',(second sym) :COL ',(third sym) :POS ,(fourth sym))) (t (warn "DB Position Too Long"))))) (defun read-selector (stream char) (declare (ignore char)) (let* ((col (read stream nil nil nil)) (pred (read stream nil nil nil))) `(make-selector :pred ,pred :col ',col))) (defmacro enable-reader-macro () '(eval-when (:compile-toplevel :load-toplevel :execute) (push *readtable* *prev-readtable*) (setq *readtable* (copy-readtable)) (set-macro-character #\$ #'read-selector) (set-macro-character #\[ #'read-db-pos) (set-macro-character #\] (get-macro-character #\))))) (defmacro disable-reader-macro () '(eval-when (:compile-toplevel :load-toplevel :execute) (when *prev-readtable* (setq *readtable* (pop *prev-readtable*))))) (push *readtable* *prev-readtable*) (setq *readtable* (copy-readtable)) (set-macro-character #\[ #'columna:read-db-pos) (set-macro-character #\] (get-macro-character #\)))
1,423
Common Lisp
.lisp
33
39.030303
98
0.631236
Z-Shang/Columna
10
1
0
AGPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
cc45e8c6f36d71e73096caf5c906731a976b5ebd0fd548cacbb84ff74c716a62
10,662
[ -1 ]
10,663
columna.asd
Z-Shang_Columna/columna.asd
(in-package :cl-user) (defpackage :columna-asd (:use :asdf :cl)) (in-package :columna-asd) (defsystem :columna :name "Columna" :description "A lightweight columnar database" :version "0.0.1" :author "Z.Shang <[email protected]>" :license "GPL3" :components ((:file "columna") (:file "reader-macro" :depends-on ("columna"))))
362
Common Lisp
.asd
12
26.5
63
0.674352
Z-Shang/Columna
10
1
0
AGPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
d18a552ab5ecb0c372e78ab1281a97357aa72efc95368ffe17fe797c44a1b1ee
10,663
[ -1 ]
10,682
plurals-0.lisp
rotatef_gettext/plurals-0.lisp
;;;; gettext for Common Lisp ;;;; ;;;; Copyright (C) 2013 Thomas Bakketun <[email protected]> ;;;; ;;;; This library is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU Lesser General Public License as published ;;;; by the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this library. If not, see <http://www.gnu.org/licenses/>. (in-package #:gettext) (defun op2 (a b c) (list b a c))
858
Common Lisp
.lisp
19
43.947368
78
0.714456
rotatef/gettext
11
0
2
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
2614b928aba0d5aff071c1121adf493c4f9cc9e6c7905fd0ef35c897d41c8642
10,682
[ -1 ]
10,683
plurals.lisp
rotatef_gettext/plurals.lisp
;;;; gettext for Common Lisp ;;;; ;;;; Copyright (C) 2013 Thomas Bakketun <[email protected]> ;;;; ;;;; This library is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU Lesser General Public License as published ;;;; by the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this library. If not, see <http://www.gnu.org/licenses/>. (in-package #:gettext) (defun parse-plurals-form (string) (let (pluralsp npluralsp) (unless (when string (let ((plural (search "plural=" string)) (nplurals (search "nplurals=" string))) (when (and plural nplurals) ;; First get the number (incf nplurals 9) (loop while (< nplurals (length string)) while (member (char string nplurals) '(#\Page #\Newline #\Return #\Tab #\Vt)) do (incf nplurals)) (when (char<= #\0 (char string nplurals) #\9) (setf pluralsp (ignore-errors (parse-integer string :start nplurals :junk-allowed t))) (when pluralsp (incf plural 7) (setf npluralsp (subseq string plural))) t)))) ;; By default we are using the Germanic form: singular form only ;; for `one', the plural form otherwise. Yes, this is also what ;; English is using since English is a Germanic language. (setf pluralsp 2 npluralsp "(n != 1)")) (values pluralsp npluralsp))) (defun digitp (c) (member c '(#\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 #\0))) (defun lexer (stream) (flet ((next-is (char) (eql char (peek-char nil stream nil)))) (loop for c = (peek-char nil stream nil) while (member c '(#\Space #\Tab)) do (read-char stream)) (let ((c (read-char stream nil nil))) (if (digitp c) (let ((buffer (make-array 10 :element-type 'character :fill-pointer 0))) (do ((c c (read-char stream nil nil))) ((or (null c) (not (digitp c))) (unless (null c) (unread-char c stream)) (values 'int (parse-integer buffer))) (vector-push-extend c buffer))) (case c (#\= (if (next-is #\=) (progn (read-char stream) (values '== '==)) (values '= '=))) (#\! (if (next-is #\=) (progn (read-char stream) (values '!= '!=)) (values '! '!))) (#\& (cond ((next-is #\&) (read-char stream) (values '&& '&&)) (t (error "Syntax error: ~S" (read-char stream))))) (#\| (cond ((next-is #\|) (read-char stream) (values '\|\| '\|\|)) (t (error "Syntax error: ~S" (read-char stream))))) (#\< (if (next-is #\=) (progn (read-char stream) (values '<= '<=)) (values '< '<))) (#\> (if (next-is #\=) (progn (read-char stream) (values '>= '>=)) (values '> '>))) ((#\* #\/ #\% #\+ %\- #\n #\? #\: #\( #\)) (let ((v (intern (string (char-upcase c)) #.*package*))) (values v v))) ((#\; #\Newline nil) nil) (otherwise (error "Syntax error: ~S" (read-char stream)))))))) (yacc:define-parser *plural-expression-parser* (:start-symbol expression) (:terminals (? \: \|\| && == != < > <= >= + - = * / % ! int n |(| |)|)) (:precedence ((:right !) (:left * / %) (:left + -) (:left < > <= >=) (:left == !=) (:left &&) (:left \|\|) (:right ? \:))) (expression (expression \|\| expression #'op2) (expression && expression #'op2) (expression == expression #'op2) (expression != expression #'op2) (expression < expression #'op2) (expression > expression #'op2) (expression <= expression #'op2) (expression >= expression #'op2) (expression + expression #'op2) (expression - expression #'op2) (expression * expression #'op2) (expression / expression #'op2) (expression % expression #'op2) (expression ? alternation #'op2) (! expression) int n (|(| expression |)| #'(lambda (a b c) (declare (ignore a c)) b)) ) (alternation (expression \: expression (lambda (a b c) (declare (ignore b)) (list a c))))) (defun parse-plural (string) (with-input-from-string (in string) (yacc:parse-with-lexer (lambda () (lexer in)) *plural-expression-parser*))) (defun transform (expr) `(lambda (n) (declare (ignorable n)) (flet ((nz (x) (if (member x '(0 nil)) 0 1))) (declare (ignorable (function nz))) (macrolet ((? (test (then else)) `(if (plusp (nz ,test)) ,then ,else))) ,(sublis '((\|\| . (lambda (x y) (nz (or (plusp (nz x)) (plusp (nz y)))))) (&& . (lambda (x y) (nz (and (plusp (nz x)) (plusp (nz y)))))) (% . mod) (/ . truncate) (== . =) (! . (lambda (x) (if (nz x) 0 1))) (!= . (lambda (x y) (nz (/= x y)))) (< . (lambda (x y) (nz (< x y)))) (> . (lambda (x y) (nz (> x y)))) (<= . (lambda (x y) (nz (<= x y)))) (>= . (lambda (x y) (nz (>= x y))))) expr))))) (defun compile-plural (expr) (compile nil (transform expr))) ;(funcall (compile-plural (parse-plural "(n+3)+n*!n%5?2:n")) ; 5) ;(transform (parse-plural "(n+3)+n*!n%5?2:n"))1 ;(funcall (compile-plural (parse-plural "n != 1")) 1) ;(funcall (compile nil `(lambda (n) ,(compile-plural (parse-plural "n != 1")))) ; 1) ;(funcall ; (compile-plural ; (parse-plural "(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2)") ; ) ; 4)
6,696
Common Lisp
.lisp
162
30.666667
106
0.477301
rotatef/gettext
11
0
2
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
437d30547da1b60abf0c6597cec0a38b5822fea9a8cfc9bcf06e8856860d0725
10,683
[ -1 ]
10,684
gettext.lisp
rotatef_gettext/gettext.lisp
;;;; gettext for Common Lisp ;;;; ;;;; Copyright (C) 2013 Thomas Bakketun <[email protected]> ;;;; ;;;; This library is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU Lesser General Public License as published ;;;; by the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this library. If not, see <http://www.gnu.org/licenses/>. (in-package #:gettext) (deftype lc-category () '(member :LC_ADDRESS :LC_ALL :LC_COLLATE :LC_CTYPE :LC_IDENTIFICATION :LC_MEASUREMENT :LC_MESSAGES :LC_MONETARY :LC_NAME :LC_NUMERIC :LC_PAPER :LC_TELEPHONE :LC_TIME)) (defvar *current-locale* nil) (defvar *textdomaindirs* (make-hash-table :test #'equal)) (defvar *textdomain* nil) (defun textdomaindir (domain) (check-type domain string) (gethash domain *textdomaindirs*)) (defun (setf textdomaindir) (directory domain) (check-type domain string) (setf (gethash domain *textdomaindirs*) (pathname directory))) (defun textdomain () *textdomain*) (defun (setf textdomain) (domain) (check-type domain string) (setf *textdomain* domain)) (defun catalog-pathname (key) (destructuring-bind (locale category domain) key (check-type locale string) (check-type category lc-category) (check-type domain string) (let ((basedir (gethash domain *textdomaindirs*))) (when basedir (probe-file (merge-pathnames (make-pathname :directory `(:relative ,locale ,(symbol-name category)) :name domain :type "mo") basedir)))))) (defun decode-catalog-pathname (pathname) (check-type pathname pathname) (assert (<= 3 (length (pathname-directory pathname))) () "The pathname ~S has to few directory components to be a valid catalog pathname." pathname) (list (car (last (pathname-directory pathname) 2)) (intern (car (last (pathname-directory pathname))) :keyword) (pathname-name pathname))) (defun read-mo (pathname) (let ((original-lengths+offsets) (translation-lengths+offsets)) (with-open-file (in pathname :element-type '(unsigned-byte 32)) (let ((swap-endianess #'identity) (magic (read-byte in))) (case magic (#x950412de) (#xde120495 (setf swap-endianess (lambda (x) (dpb (ldb (byte 8 0) x) (byte 8 24) (dpb (ldb (byte 8 8) x) (byte 8 16) (dpb (ldb (byte 8 16) x) (byte 8 8) (ldb (byte 8 24) x))))))) (otherwise (error "Wrong magic in MO file ~S = ~X" pathname magic))) (let ((revision (funcall swap-endianess (read-byte in))) (num-strings (funcall swap-endianess (read-byte in))) (offset-original (funcall swap-endianess (read-byte in))) (offset-translation (funcall swap-endianess (read-byte in)))) (assert (= revision 0)) (flet ((read-lengths+offsets (offset) (let ((lengths+offsets (make-array (* 2 num-strings) :element-type '(unsigned-byte 32)))) (file-position in (/ offset 4)) (read-sequence lengths+offsets in) (map-into lengths+offsets swap-endianess lengths+offsets) lengths+offsets))) (setf original-lengths+offsets (read-lengths+offsets offset-original)) (setf translation-lengths+offsets (read-lengths+offsets offset-translation)))))) (with-open-file (in pathname :element-type '(unsigned-byte 8)) (flet ((read-strings (lengths+offsets) (loop for i from 0 below (length lengths+offsets) by 2 collect (let ((bytes (make-array (aref lengths+offsets i) :element-type '(unsigned-byte 8)))) (file-position in (aref lengths+offsets (1+ i))) (read-sequence bytes in) (flex:octets-to-string bytes :external-format :utf-8))))) (let ((originals (read-strings original-lengths+offsets)) (translations (read-strings translation-lengths+offsets)) (table (make-hash-table :test 'equal))) (loop for original in originals for translation in translations do (setf (gethash (first (null-split original)) table) (null-split translation))) table))))) (defun null-split (string) (split-sequence:split-sequence (code-char 0) string)) (defun parse-headers (string) (with-input-from-string (in string) (loop for line = (read-line in nil nil) while line for split = (position #\: line) collect (cons (intern (string-upcase (subseq line 0 split)) :keyword) (string-trim " " (subseq line (1+ split))))))) (defstruct catalog key headers nplurals plurals-function messages) (defvar *catalog-cache* (make-hash-table :test 'equal)) (defun construct-catalog (key messages) (let ((headers (parse-headers (first (gethash "" messages))))) (remhash "" messages) (multiple-value-bind (nplurals plural-expr) (parse-plurals-form (cdr (assoc :plural-forms headers))) (make-catalog :key key :headers headers :nplurals nplurals :plurals-function (compile-plural (parse-plural plural-expr)) :messages messages)))) (defun define-catalog (key &optional messages) (unless messages (let ((pathname (catalog-pathname key))) (when pathname (setf messages (read-mo pathname))))) (setf (gethash key *catalog-cache*) (when messages (construct-catalog key messages)))) (defmacro preload-catalogs (textdomaindir) (check-type textdomaindir pathname) `(progn ,@(loop for file in (directory (merge-pathnames "*/*/*.mo" textdomaindir)) collect `(define-catalog ',(decode-catalog-pathname file) ,(read-mo file))))) (defun get-catalog (locale category domain) (let ((key (list (or locale *current-locale*) (or category :lc_messages) (or domain (textdomain))))) (unless (member nil key) (multiple-value-bind (catalog found) (gethash key *catalog-cache*) (if found catalog (define-catalog key)))))) (defun catalog-meta* (&optional domain catergory locale) (let ((catalog (get-catalog locale catergory domain))) (when catalog (catalog-headers catalog)))) (defun lookup (msgid domain category locale) (let ((catalog (get-catalog locale category domain))) (when catalog (gethash msgid (catalog-messages catalog))))) (defun gettext* (msgid &optional domain category locale) (or (first (lookup msgid domain category locale)) msgid)) (defun ngettext* (msgid1 msgid2 n &optional domain category locale) (let* ((catalog (get-catalog locale category domain)) (translation (and catalog (lookup msgid1 domain category locale)))) (if translation (elt translation (funcall (catalog-plurals-function catalog) n)) (if (= 1 n) msgid1 msgid2)))) (defun gettext-noop (msgid) msgid) (defmacro setup-gettext (package default-domain) (setf package (find-package package)) (check-type default-domain string) `(progn (defun ,(intern "GETTEXT" package) (msgid &optional domain category locale) (gettext* msgid (or domain ,default-domain) category locale)) (defun ,(intern "_" package) (msgid &optional domain category locale) (gettext* msgid (or domain ,default-domain) category locale)) (defun ,(intern "NGETTEXT" package) (msgid1 msgid2 n &optional domain category locale) (ngettext* msgid1 msgid2 n (or domain ,default-domain) category locale)) (defun ,(intern "N_" package) (msgid) msgid) (defun ,(intern "CATALOG-META" package) (&optional domain category locale) (catalog-meta* (or domain ,default-domain) category locale))))
8,724
Common Lisp
.lisp
197
35.482234
97
0.622986
rotatef/gettext
11
0
2
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
ff0d6e55f4313596d1e9e5c334514114708aa8baa994cebb77234d7313bda21d
10,684
[ -1 ]
10,685
packages.lisp
rotatef_gettext/packages.lisp
;;;; gettext for Common Lisp ;;;; ;;;; Copyright (C) 2013 Thomas Bakketun <[email protected]> ;;;; ;;;; This library is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU Lesser General Public License as published ;;;; by the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this library. If not, see <http://www.gnu.org/licenses/>. (defpackage #:gettext (:use #:common-lisp) (:export #:gettext* #:ngettext* #:gettext-noop #:textdomain #:textdomaindir #:lc-category #:preload-catalogs #:setup-gettext #:*current-locale* #:catalog-meta*))
1,039
Common Lisp
.lisp
29
33.586207
78
0.704365
rotatef/gettext
11
0
2
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
3182aeff57f104d6b34083a7ed548f2a45744dd0cf499b3ba47ca13c690cad42
10,685
[ -1 ]
10,686
package.lisp
rotatef_gettext/gettext-example/package.lisp
;;;; gettext for Common Lisp ;;;; ;;;; Copyright (C) 2013 Thomas Bakketun <[email protected]> ;;;; ;;;; This library is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU Lesser General Public License as published ;;;; by the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this library. If not, see <http://www.gnu.org/licenses/>. (defpackage #:example (:use #:common-lisp #:gettext) (:export #:run)) (gettext:setup-gettext #:example "gettext-example")
926
Common Lisp
.lisp
20
45
78
0.719027
rotatef/gettext
11
0
2
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
b84d0ead335a577310a399e0318119e640e24475484fb3217d891ebc831cf2e3
10,686
[ -1 ]
10,687
example.lisp
rotatef_gettext/gettext-example/example.lisp
;;;; gettext for Common Lisp ;;;; ;;;; Copyright (C) 2013 Thomas Bakketun <[email protected]> ;;;; ;;;; This library is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU Lesser General Public License as published ;;;; by the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this library. If not, see <http://www.gnu.org/licenses/>. (in-package #:example) ;(setf (textdomaindir "gettext-example") (asdf:system-relative-pathname :gettext-example "locale/")) ;(setf (textdomain) "gettext-example") (preload-catalogs #.(asdf:system-relative-pathname :gettext-example "locale/")) (defun print-texts () (write-line (_ "This is an example gettext program.")) (write-line (_ "This text is not translated.")) (dotimes (i 33) (format t (ngettext "I see one dog.~%" "I see ~D dogs.~%" i) i))) (defun run () (print-texts) (dolist (*current-locale* '("en" "nn" "pl")) (format t "~&~%*current-locale* = ~A~%" *current-locale*) (print-texts) (format t "~&Metadata:~%~S" (catalog-meta))))
1,470
Common Lisp
.lisp
31
45.419355
100
0.691074
rotatef/gettext
11
0
2
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
c082d91ca0ad1c6d620c025ae606977935827df543867c5796296b856882741c
10,687
[ -1 ]
10,688
package.lisp
rotatef_gettext/gettext-tests/package.lisp
;;;; gettext for Common Lisp ;;;; ;;;; Copyright (C) 2013 Thomas Bakketun <[email protected]> ;;;; ;;;; This library is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU Lesser General Public License as published ;;;; by the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this library. If not, see <http://www.gnu.org/licenses/>. (defpackage #:gettext-tests (:use #:common-lisp #:gettext #:stefil) (:export))
882
Common Lisp
.lisp
19
45.157895
78
0.716937
rotatef/gettext
11
0
2
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
441b8003419af7959362a39614e2dc5962a7d84122cc01a9ba41183c8eeda73d
10,688
[ -1 ]
10,689
tests.lisp
rotatef_gettext/gettext-tests/tests.lisp
;;;; gettext for Common Lisp ;;;; ;;;; Copyright (C) 2013 Thomas Bakketun <[email protected]> ;;;; ;;;; This library is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU Lesser General Public License as published ;;;; by the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this library. If not, see <http://www.gnu.org/licenses/>. (in-package #:gettext-tests) (in-root-suite) (defsuite gettext-tests) (in-suite gettext-tests) (deftest test-setup () (let* ((package-name (gensym "test")) (package (make-package package-name :use '(#:common-lisp #:gettext)))) (eval `(gettext:setup-gettext ,package-name "gettext-tests")) (dolist (sym '("GETTEXT" "_" "NGETTEXT")) (is (fboundp (find-symbol sym package)))))) (deftest test-plurals () (dolist (test '((nil (1) (0 2)) ("" (1) (0 2)) ("... junk ..." (1) (0 2)) ("nplurals=1; plural=0;" (0 1 3 100)) ("nplurals=2; plural=(n != 1);" (1) (0 2)) ("nplurals=2; plural=(n > 1);" (0 1) (2 3)) ("nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n != 0 ? 1 : 2);" (1 21 31) (11 211) (0)) ("nplurals=3; plural=n==1 ? 0 : n==2 ? 1 : 2;" (1) (2) (0 3 4)) ("nplurals=3; plural=n==1 ? 0 : (n==0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2;" (1) (0 2 3 19 101 102 119) (20 21 120)) ("nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);" (1 21 31) (2 9 22) (10 20)) ("nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);" (1 21 31) (2 3 4 22) (10 19)) ("nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;" (1) (2 3 4) (5 6)) ("nplurals=3; plural=(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);" (1) (2 3 4 22) (5 9 25)) ("nplurals=4; plural=(n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n%100==4 ? 2 : 3);" (1 101) (2 102) (3 4 103 104) (5 105)))) (multiple-value-bind (nplurals expr) (gettext::parse-plurals-form (car test)) (is (= nplurals (length (cdr test)))) (let ((plural (gettext::compile-plural (gettext::parse-plural expr)))) (loop for expect from 0 for test-n in (cdr test) do (dolist (n test-n) (is (= (funcall plural n) expect))))))))
2,890
Common Lisp
.lisp
49
50.959184
153
0.534015
rotatef/gettext
11
0
2
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
08723eb910335aa7161b9c223e282f1dd2841b8eae640a559ab34aeb4b159a43
10,689
[ -1 ]
10,690
gettext.asd
rotatef_gettext/gettext.asd
;;;; gettext for Common Lisp ;;;; ;;;; Copyright (C) 2013 Thomas Bakketun <[email protected]> ;;;; ;;;; This library is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU Lesser General Public License as published ;;;; by the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this library. If not, see <http://www.gnu.org/licenses/>. (defsystem #:gettext :name "gettext" :description "An pure Common Lisp implementation of gettext runtime. gettext is an internationalization and localization (i18n) system commonly used for writing multilingual programs on Unix-like computer operating systems." :licence "GNU Lesser General Public Licence 3.0" :author "Thomas Bakketun <[email protected]>" :depends-on (:split-sequence :yacc :flexi-streams) :serial t :components ((:file "packages") (:file "plurals-0") (:file "plurals") (:file "gettext"))) (defmethod perform ((o test-op) (c (eql (find-system '#:gettext)))) (operate 'load-op '#:gettext-tests) (funcall (find-symbol (string :gettext-tests) :gettext-tests)))
1,579
Common Lisp
.asd
31
46.870968
228
0.69793
rotatef/gettext
11
0
2
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
6f204f117f8390af50b03a5f04cea710873bcc0cbe82e377e808aa211b920e81
10,690
[ -1 ]
10,691
gettext-example.asd
rotatef_gettext/gettext-example/gettext-example.asd
;;;; gettext for Common Lisp ;;;; ;;;; Copyright (C) 2013 Thomas Bakketun <[email protected]> ;;;; ;;;; This library is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU Lesser General Public License as published ;;;; by the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this library. If not, see <http://www.gnu.org/licenses/>. (defsystem #:gettext-example :name "gettext-example" :licence "GNU Lesser General Public Licence 3.0" :depends-on (:gettext) :serial t :components ((:file "package") (:file "example")))
1,022
Common Lisp
.asd
23
41.782609
78
0.699399
rotatef/gettext
11
0
2
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
7030db542caf44053229c0ea99f3dad65391e94766dd95a523f44ec7450898b6
10,691
[ -1 ]
10,692
gettext-tests.asd
rotatef_gettext/gettext-tests/gettext-tests.asd
;;;; gettext for Common Lisp ;;;; ;;;; Copyright (C) 2013 Thomas Bakketun <[email protected]> ;;;; ;;;; This library is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU Lesser General Public License as published ;;;; by the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this library. If not, see <http://www.gnu.org/licenses/>. (defsystem #:gettext-tests :name "gettext-tests" :licence "GNU Lesser General Public Licence 3.0" :depends-on (:gettext :stefil) :serial t :components ((:file "package") (:file "tests")))
1,024
Common Lisp
.asd
23
41.869565
78
0.698
rotatef/gettext
11
0
2
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
329d0c1f1443d08ed6db7637edfc5a7b5f179e57406db342f1efc4864f9a420d
10,692
[ -1 ]
10,699
update-translations.sh
rotatef_gettext/gettext-example/update-translations.sh
#!/bin/sh cd $(dirname $0) PACKAGE=$(basename $PWD) mkdir -p translation # Extract text for translation from source xgettext --package-name=$PACKAGE -c --from-code UTF-8 -k_ -kN_ -o translation/$PACKAGE.pot *.lisp # When using preload-catalog the contents it's neccary to recompile the files with # the preload-catalog in order to get the updated texts. touch example.lisp # To create a new translation (e.g. for the locale nn) # cd translation # msginit -l nn # Update existing translation cd translation for po in *.po ; do msgmerge -U $po $PACKAGE.pot done # Transform .po files into into binary .mo files read by Lisp for po in *.po ; do mkdir -p ../locale/$(basename $po .po)/LC_MESSAGES msgfmt -o ../locale/$(basename $po .po)/LC_MESSAGES/$PACKAGE.mo $po done
786
Common Lisp
.l
22
33.818182
97
0.738095
rotatef/gettext
11
0
2
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
a70a35da89df0b4fc6bedb0a875829dd82e7806283cd3f17548ec71b5c4e61fc
10,699
[ -1 ]
10,702
gettext-example.mo
rotatef_gettext/gettext-example/locale/pl/LC_MESSAGES/gettext-example.mo
Þ•4L`!a#ƒ­§5U%‹I see one dog.~%I see ~D dogs.~%This is an example gettext program.Project-Id-Version: gettext-example Report-Msgid-Bugs-To: POT-Creation-Date: 2013-04-09 16:14+0200 PO-Revision-Date: 2013-04-09 16:08+0200 Last-Translator: Thomas Bakketun <[email protected]> Language-Team: Polish Language: pl MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=3; plural=(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2); WidzÄ™ ~D psa.~%WidzÄ™ ~D psy.~%WidzÄ™, ~D psów.~%Jest to program, gettext przykÅ‚adem.
689
Common Lisp
.l
12
56.416667
202
0.625369
rotatef/gettext
11
0
2
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
58a92dd0229f5126d37d2fd4501999af1627fb54b968e7d4181c7093fed4a8c1
10,702
[ -1 ]
10,703
gettext-example.mo
rotatef_gettext/gettext-example/locale/nn/LC_MESSAGES/gettext-example.mo
Þ•4L`!a#ƒ~§&&%MI see one dog.~%I see ~D dogs.~%This is an example gettext program.Project-Id-Version: gettext-example Report-Msgid-Bugs-To: POT-Creation-Date: 2013-04-09 16:14+0200 PO-Revision-Date: 2013-03-21 16:10+0100 Last-Translator: Thomas Bakketun <[email protected]> Language-Team: Norwegian Nynorsk Language: nn MIME-Version: 1.0 Content-Type: text/plain; charset=ASCII Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=2; plural=(n != 1); Eg ser ein hund.~%Eg ser ~D hundar.~%Dette er eit gettext eksempelprogram.
627
Common Lisp
.l
12
51.25
202
0.662338
rotatef/gettext
11
0
2
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
47631824c3be24e83efd08ca5b61ddf7019a962a22ad86d002852bcfb48db479
10,703
[ -1 ]
10,704
pl.po
rotatef_gettext/gettext-example/translation/pl.po
# Polish translations for gettext-example package. # Copyright (C) 2013 THE gettext-example'S COPYRIGHT HOLDER # This file is distributed under the same license as the gettext-example package. # Thomas Bakketun <[email protected]>, 2013. # msgid "" msgstr "" "Project-Id-Version: gettext-example\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2013-04-09 16:14+0200\n" "PO-Revision-Date: 2013-04-09 16:08+0200\n" "Last-Translator: Thomas Bakketun <[email protected]>\n" "Language-Team: Polish\n" "Language: pl\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=3; plural=(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 " "|| n%100>=20) ? 1 : 2);\n" #: example.lisp:9 msgid "This is an example gettext program." msgstr "Jest to program, gettext przykładem." #: example.lisp:10 msgid "This text is not translated." msgstr "" #: example.lisp:12 #, lisp-format msgid "I see one dog.~%" msgid_plural "I see ~D dogs.~%" msgstr[0] "Widzę ~D psa.~%" msgstr[1] "Widzę ~D psy.~%" msgstr[2] "Widzę, ~D psów.~%"
1,104
Common Lisp
.l
32
33.25
81
0.718985
rotatef/gettext
11
0
2
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
11f52e8e7b252abd908a68ba0f1c2ffedd966148ee73ea3540b60245ac083b2d
10,704
[ -1 ]
10,705
gettext-example.pot
rotatef_gettext/gettext-example/translation/gettext-example.pot
# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: gettext-example\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2013-04-09 16:14+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <[email protected]>\n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=CHARSET\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n" #: example.lisp:9 msgid "This is an example gettext program." msgstr "" #: example.lisp:10 msgid "This text is not translated." msgstr "" #: example.lisp:12 #, lisp-format msgid "I see one dog.~%" msgid_plural "I see ~D dogs.~%" msgstr[0] "" msgstr[1] ""
895
Common Lisp
.l
31
27.774194
73
0.739837
rotatef/gettext
11
0
2
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
a28ced170a30a81a6d69e5df0bf8e60a37e6de7ca370e29f32e5ad6adc49df60
10,705
[ -1 ]
10,722
package.lisp
Jobhdez_Yotta/src/package.lisp
(defpackage #:yotta (:use #:common-lisp #:alexa #:yacc #:alexandria #:trivia) (:export #:token-generator #:make-lisp-interlan #:lex-line #:*linear-algebra-grammar* #:parse-with-lexer #:program #:make-program #:plus #:make-plus #:minus #:make-minus #:mul #:make-mul #:vec #:make-vec #:matrix #:make-matrix #:num #:make-num #:var #:make-var #:assignment #:make-assignment #:defvarlisp #:make-defvarlisp #:vectorlisp #:make-vectorlisp #:matrixlisp #:make-matrixlisp #:numlisp #:make-numlisp #:looplisp #:make-looplisp #:vectorsum #:make-vectorsum #:vectorminus #:make-vectorminus #:matrixsum #:make-matrixsum #:matrixminus #:make-matrixminus #:setflisp #:make-setflisp #:setqlisp #:make-setqlisp #:areflisp #:make-areflisp #:sumlisp #:make-sumlisp #:minuslisp #:make-minuslisp #:prognlisp #:make-prognlisp #:letexpressionlisp #:make-letexpression #:dotproduct #:make-dotproduct #:fakevecmul #:make-fakevecmul #:matrixmul #:make-matrixmul #:incflisp #:make-incflisp #:mullisp #:make-mullisp)) (defpackage #:yotta-var (:use))
1,288
Common Lisp
.lisp
73
12.986301
30
0.613674
Jobhdez/Yotta
16
0
0
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
248be60b84f15dc1c7fa6209aab48808bef0c92a46e78433f05f95ed71a69d2d
10,722
[ -1 ]
10,723
yotta.lisp
Jobhdez_Yotta/src/yotta.lisp
(in-package #:yotta) ;;;; Compiler ;;; This is just a quick `compile` function to actually compile a linear ;;; algebra expression; nevertheless, it is not very robust as it does not ;;; check for the validity of the linear algebra expression. this will be ;;; fixed in the near future. But the parser should give an error message if an invalid ;;; expr Is entered. (defun compile-yotta-expr (expr) "Compiles a linear algebra expression into Common Lisp." (let* ((tokens (token-generator (lex-line expr))) (parse-tree (parse-with-lexer tokens *linear-algebra-grammar*)) (intermediate-representation (make-lisp-interlan parse-tree)) (lisp-code (generate-lisp intermediate-representation))) lisp-code))
719
Common Lisp
.lisp
14
49.071429
88
0.754986
Jobhdez/Yotta
16
0
0
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
9a8011763bd6fe2d848bc5d9662b554dd182acd7ee3dcd8a01aeb2016417c1cd
10,723
[ -1 ]
10,724
performance-tests.lisp
Jobhdez_Yotta/src/performance/performance-tests.lisp
(in-package #:yotta) (defun normal-sum (v v2) (defvar v3 (make-array (array-dimension v 0))) (loop for i from 0 to (- (array-dimension v 0) 1) do (setf (aref v3 i) (+ (aref v i) (aref v2 i))))) (defun normal-sum-declare (v v2) (declare (optimize (speed 3) (safety 0))) (declare (type array v v2)) (defvar v3 (make-array (array-dimension v 0))) (loop for i from 0 to (- (array-dimension v 0) 1) do (setf (aref v3 i) (+ (aref v i) (aref v2 i))))) (defun unrolled-sum (v v2) (defvar v3 (make-array (array-dimension v 0))) (loop for i from 0 to (- (array-dimension v 0) 1) by 2 do (progn (setf (aref v3 i) (+ (aref v i) (aref v2 i))) (setf (aref v3 (+ i 1)) (+ (aref v (+ i 1)) (aref v2 (+ i 1))))))) (defun unrolled-sum-declare (v v2) (declare (optimize (speed 3) (safety 0))) (declare (type array v v2)) (defvar v3 (make-array (array-dimension v 0))) (loop for i from 0 to (- (array-dimension v 0) 1) by 2 do (progn (setf (aref v3 i) (+ (aref v i) (aref v2 i))) (setf (aref v3 (+ i 1)) (+ (aref v (+ i 1)) (aref v2 (+ i 1))))))) (defvar vt (make-array 1000)) (defvar elements (loop for i from 1 to 1000 collect i)) (defvar testv (make-array 1000 :initial-contents elements))
1,236
Common Lisp
.lisp
27
42.481481
70
0.612635
Jobhdez/Yotta
16
0
0
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
ca9418bceabd3f4c29530831ad0462fc1d38d4934706fa904cf37ef2301fb008
10,724
[ -1 ]
10,725
ast.lisp
Jobhdez_Yotta/src/parser/ast.lisp
(in-package #:yotta) (defstruct program "A PROGRAM ast node." expressions) (defstruct plus "A PLUS ast node." left-exp right-exp) (defstruct minus "A MINUS ast node." left-exp right-exp) (defstruct mul "A MULTIPLICATION ast node." left-exp right-exp) (defstruct vec "A VECTOR ast node." entries) (defstruct matrix "A MATRIX ast node." entries) (defstruct num "A NUMBER ast node." num) (defstruct var "A VARAIABLE ast node." var) (defstruct assignment "An ASSIGNMENT ast node." variable exp)
538
Common Lisp
.lisp
28
16.535714
30
0.733467
Jobhdez/Yotta
16
0
0
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
ecd0a220b0a0f06177a13994268118d0b8a9ac1aeb1b742d44ea39d61b12543e
10,725
[ -1 ]
10,726
parser.lisp
Jobhdez_Yotta/src/parser/parser.lisp
(in-package #:yotta) (eval-when (:compile-toplevel :load-toplevel :execute) (defun build-program (expressions) (make-program :expressions expressions)) (defun build-plus (left-exp plus-tok right-exp) (declare (ignore plus-tok)) (make-plus :left-exp left-exp :right-exp right-exp)) (defun build-minus (left-exp minus-tok right-exp) (declare (ignore minus-tok)) (make-minus :left-exp left-exp :right-exp right-exp)) (defun build-mul (left-exp mul-tok right-exp) (declare (ignore mul-tok)) (make-mul :left-exp left-exp :right-exp right-exp)) (defun build-vec (left-bracket entries right-bracket) (declare (ignore left-bracket right-bracket)) (make-vec :entries (flatten entries))) (defun build-matrix (left-bracket entries right-bracket) (declare (ignore left-bracket right-bracket)) (make-matrix :entries (flatten entries))) (defun build-num (num) (make-num :num num)) (defun build-var (var) (make-var :var var)) (defun build-assignment (var assignment exp) (declare (ignore assignment)) (make-assignment :variable var :exp exp)) (define-parser *linear-algebra-grammar* (:start-symbol program) (:terminals (:number :variable :plus :minus :mul :left-bracket :right-bracket :assignment)) (program (expressions #'build-program)) (expressions expression (expression expressions)) (expression vector-exp matrix-exp assignment variable (expression :plus expression #'build-plus) (expression :minus expression #'build-minus) (expression :mul expression #'build-mul)) (vector-exp (:left-bracket :right-bracket) (:left-bracket entries :right-bracket #'build-vec)) (matrix-exp (:left-bracket :right-bracket) (:left-bracket vectors :right-bracket #'build-matrix)) (vectors vector-exp (vector-exp vectors)) (entries scalar-exp (scalar-exp entries)) (scalar-exp (:number #'build-num)) (variable (:variable #'build-var)) (assignment (:variable :assignment expression #'build-assignment))))
2,150
Common Lisp
.lisp
64
28.296875
95
0.680676
Jobhdez/Yotta
16
0
0
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
4ae0ad0b382983328406256849bfba38de1aa1abac30e737cadee8c918acf70f
10,726
[ -1 ]
10,727
parsefile.lisp
Jobhdez_Yotta/src/parser/parsefile.lisp
(in-package #:yotta) (defun parse-file (filename) "Given the name of a file parse the file." (let* ((file-string (read-file-into-string filename)) (tokens (lex-line file-string)) (ast (parse-with-lexer (token-generator tokens) *linear-algebra-grammar*))) ast))
283
Common Lisp
.lisp
8
31.625
55
0.702602
Jobhdez/Yotta
16
0
0
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
884d0f213d5a69986e6ef4ceeaf1f1c86a7c66a1cea9e0cc8315b4575cec0326
10,727
[ -1 ]
10,728
generatelisp.lisp
Jobhdez_Yotta/src/backends/lisp/generatelisp.lisp
(in-package #:yotta) (defun generate-lisp (ast) "Generates lisp code from LispIL ast." (if (listp ast) (let ((node (car ast))) (generate node)))) (defun generate (node) "Generates lisp code from ast node." (match node ((defvarlisp :var v :exp e) (gen-defvar v e)) ((vectorlisp :dimension dim :elements els) (let ((members (mapcar #'generate els))) (gen-vec dim members))) ((matrixlisp :dimension dim :matrix m) (let ((members (mapcar #'generate m))) (gen-matrix dim members))) ((numlisp :n n) n) ((vectorsum :i i :n n :exp e :leftexp lexp :rightexp rexp) (gen-sum-vectors (generate lexp) (generate rexp))) ((vectorminus :i i :n n :exp e :leftexp lexp :rightexp rexp) (gen-minus-vectors (generate lexp) (generate rexp))) ((matrixsum :i i :n n :exp e :leftexp lexp :rightexp rexp) (gen-sum-matrix (generate lexp) (generate rexp))) ((matrixminus :i i :n n :exp e :leftexp lexp :rightexp rexp) (gen-minus-matrix (generate lexp) (generate rexp))) ((dotproduct :expression exp :vector1 v :vector2 v2) (gen-dot-product (generate v) (generate v2))) ;((matrixmul :i i ; :n n ;:exp e ;:leftexp lexp ;:rightexp rexp) ;(gen-matrix-mul (generate lexp) ; (generate rexp))) (_ (error "The expression: ~S is not a valid EXP." node)))) (defun gen-defvar (var exp) "Lisp based ast node for DEFVAR." `(defvar ,var ,exp)) (defun gen-vec (dimension elements) "Lisp based ast node for VECTOR." `(make-array ,dimension ,elements)) (defun gen-matrix (dimension elements) "Matrix generated code." `(make-array ,dimension :initial-contents ,elements)) (defun gen-sum-vectors (vec vec2) "Lisp based ast node for MAKE-SUM-VECTORS." `(progn (setq newa (make-array ,(length vec))) (dotimes (i ,(length vec)) (setf (aref newa i) (+ (aref ,vec i) (aref ,vec2 i)))) newa)) (defun gen-minus-vectors (vec vec2) "Lisp based ast node for MAKE-MINUS-VECTOR." `(progn (setq newa (make-array ,(length vec))) (dotimes (i ,(length vec)) (setf (aref newa i) (- (aref ,vec i) (aref ,vec2 i)))) newa)) (defun gen-sum-matrix (m1 m2) `(progn (setq newa (make-array (list (array-dimension ,m1 0) (array-dimension ,m1 1)))) (dotimes (i (array-dimension ,m1 0)) (dotimes (j (array-dimension ,m1 1)) (setf (aref newa i j) (+ (aref ,m1 i j) (aref ,m2 i j))))) newa)) (defun gen-minus-matrix (m1 m2) `(progn (setq newa (make-array ((array-dimension ,m1 0) (array-dimension ,m1 1)))) (dotimes (i (array-dimension ,m1 0)) (dotimes (j (array-dimension ,m1 1)) (setf (aref newa i j) (- (aref ,m1 i j) (aref ,m2 i j))))) newa)) (defun gen-dot-product (v v2) `(progn (setq fakemulvec (make-array (array-dimension ,v 0))) (dotimes (i (array-dimension ,v 0)) (setf (aref fakesumvec i) (* (aref ,v i) (aref ,v2 i)))) (setq sum 0) (dotimes (i (array-dimension fakemulvec 0)) (setq sum (+ sum (aref fakemulvec i)))) sum))
3,238
Common Lisp
.lisp
106
25.018868
89
0.60045
Jobhdez/Yotta
16
0
0
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
d9fb13fac251ee1317de5d99246463fd871988b017b333a0c6e091e3f267034e
10,728
[ -1 ]
10,729
ast.lisp
Jobhdez_Yotta/src/backends/lisp/ast.lisp
(in-package #:yotta) """ These are the nodes for the `lispIL` abstrax syntax tree -- i.e., intermediate language which transoforms the parse tree, a high level intermediate language. """ ;;-------------------------------------------------------- ;;; lispIL ast nodes: ;;-------------------------------------------------------- (defstruct defvarlisp "DEFVARLISP node." var exp) (defstruct vectorlisp "VECTORLISP node." dimension elements) (defstruct matrixlisp "MATRIXLISP node." dimension matrix) (defstruct numlisp "NUMLISP node." n) (defstruct looplisp "LOOPLISP node." i n exp) (defstruct (vectorsum (:include looplisp)) "VECTORSUM node." leftexp rightexp) (defstruct (vectorminus (:include looplisp)) "VECTOR-MINUS node." leftexp rightexp) (defstruct (matrixsum (:include looplisp)) "MATRIXSUM node." leftexp rightexp) (defstruct (matrixminus (:include looplisp)) "MATRIXMINUS node." leftexp rightexp) (defstruct (matrixmul (:include looplisp)) "MATRIXMINUS node." leftexp rightexp) (defstruct prognlisp "PROGNLISP node." expressions) (defstruct setqlisp "SETQLISP node." var exp) (defstruct setflisp "SETFLISP node." var exp) (defstruct lengthlisp "LENGTHLISP node." exp) (defstruct areflisp "AREFLISP node." array i) (defstruct sumlisp "(primitive) SUMLISP node." leftexp rightexp) (defstruct minuslisp "(primitive) MINUSLISP node." leftexp rightexp) (defstruct mullisp leftexp rightexp) (defstruct dotproduct "DOTPRODUCT node." expression vector1 vector2) (defstruct letexpression "LETEXPRESSION node." id expr body) (defstruct fakevecmul "FAKEVECMUL node." vec vec2) (defstruct incflisp id exp) ;;todo: matrixmul, crossproduct, dotproduct
1,803
Common Lisp
.lisp
95
16.336842
93
0.708333
Jobhdez/Yotta
16
0
0
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
3cd92e4b9a97edb862146b8f9073c7ab079a5e22ae0a7788a7b85895e01b03d6
10,729
[ -1 ]
10,730
lispIL.lisp
Jobhdez_Yotta/src/backends/lisp/lispIL.lisp
(in-package #:yotta) (defun make-lisp-interlan (parse-tree) "given a parse tree create a lisp based intermediate language." (match parse-tree ((program :expressions exps) (mapcar #'make-lisp-ast (flatten exps))) (_ (error "Not valid expression.")))) (defun make-lisp-ast (expression-node) "given an parse tree node create a lisp abstract syntax tree node (ie., intermediate language." (match expression-node ((assignment :variable a :exp b) (make-defvarlisp :var a :exp (make-lisp-ast b))) ((vec :entries a) (make-vectorlisp :dimension (length a) :elements (mapcar #'make-lisp-ast a))) ((matrix :entries exps) (let ((n (length (flatten exps))) (n2 (length (vec-entries (car (flatten exps)))))) (make-matrixlisp :dimension (list n n2) :matrix (mapcar #'make-lisp-ast (flatten exps))))) ((num :num n) (make-numlisp :n n)) ((plus :left-exp lexp :right-exp rexp) (cond ((and (vec-p lexp) (vec-p rexp)) (make-vectorsum :i (quote yotta-var::i) :n (length (vec-entries lexp)) :exp (make-setflisp :var (make-areflisp :array (quote yotta-var::newarray) :i (quote yotta-var::i)) :exp (make-sumlisp :leftexp (make-areflisp :array (make-lisp-ast lexp) :i (quote yotta-var::i)) :rightexp (make-areflisp :array (make-lisp-ast rexp) :i (quote yotta-var::i)))) :leftexp (make-lisp-ast lexp) :rightexp (make-lisp-ast rexp))) ((and (matrix-p lexp) (matrix-p rexp)) (make-matrixsum :i (quote yotta-var::i) :n (length (matrix-entries lexp)) :exp (make-looplisp :i (quote yotta-var::j) :n (length (vec-entries (car (matrix-entries lexp)))) :exp (make-setflisp :var (make-areflisp :array (quote yotta-var::newarray) :i (list (quote yotta-var::i) (quote yotta-var::j))) :exp (make-sumlisp :leftexp (make-areflisp :array (make-lisp-ast lexp) :i (list (quote yotta-var::i) (quote yotta-var::j))) :rightexp (make-areflisp :array (make-lisp-ast rexp) :i (list (quote yotta-var::i) (quote yotta-var::j)))))) :leftexp (make-lisp-ast lexp) :rightexp (make-lisp-ast rexp))) (t (error "The Expression ~S is not a valid SUM." (list '+ lexp rexp))))) ((minus :left-exp lexp :right-exp rexp) (cond ((and (vec-p lexp) (vec-p rexp)) (make-vectorminus :i (quote yotta-var::i) :n (length (vec-entries lexp)) :exp (make-setflisp :var (make-areflisp :array (quote yotta-var::newarray) :i (quote yotta-var::i)) :exp (make-minuslisp :leftexp (make-areflisp :array (make-lisp-ast lexp) :i (quote yotta-var::i)) :rightexp (make-areflisp :array (make-lisp-ast rexp) :i (quote yotta-var::i)))) :leftexp (make-lisp-ast lexp) :rightexp (make-lisp-ast rexp))) ((and (matrix-p lexp) (matrix-p rexp)) (make-matrixminus :i (quote yotta-var::i) :n (length (matrix-entries lexp)) :exp (make-looplisp :i (quote yotta-var::j) :n (length (vec-entries (car (matrix-entries lexp)))) :exp (make-setflisp :var (make-areflisp :array (quote yotta-var::newarray) :i (list (quote yotta-var::i) (quote yotta-var::j))) :exp (make-minuslisp :leftexp (make-areflisp :array (make-lisp-ast lexp) :i (list (quote yotta-var::i) (quote yotta-var::j))) :rightexp (make-areflisp :array (make-lisp-ast rexp) :i (list (quote yotta-var::i) (quote yotta-var::j)))))) :leftexp (make-lisp-ast lexp) :rightexp (make-lisp-ast rexp))) (t (error "The Expression ~S is not a valid SUM." (list '- lexp rexp))))) ((mul :left-exp lexp :right-exp rexp) (cond ((and (vec-p lexp) (vec-p rexp)) (make-dotproduct :expression (make-letexpression :id (quote yotta-var::vec) :expr (make-fakevecmul :vec (make-lisp-ast lexp) :vec2 (make-lisp-ast rexp)) :body (make-prognlisp :expressions (list (make-setqlisp :var (quote yotta-var::sum) :exp 0) (make-looplisp :i (quote yotta-var::i) :n (length (vec-entries lexp)) :exp (make-setqlisp :var (quote yotta-var::sum) :exp (make-sumlisp :leftexp (quote yotta-var::sum) :rightexp (make-areflisp :array (quote yotta-var::vec) :i (quote yotta-var::i))))) (quote yotta-var::sum)))) :vector1 (make-lisp-ast lexp) :vector2 (make-lisp-ast rexp))) ((and (matrix-p lexp) (matrix-p rexp)) (make-matrixmul :i (quote yotta-var::i) :n (length (flatten (matrix-entries lexp))) :exp (make-looplisp :i (quote yotta-var::j) :n (length (vec-entries (car (flatten (matrix-entries rexp))))) :exp (make-letexpression :id (quote yotta-var::cur) :expr 0 :body (list (make-looplisp :i (quote yotta-var::k) :n (length (vec-entries (car (flatten (matrix-entries lexp))))) :exp (make-incflisp :id (quote yotta-var::cur) :exp (make-mullisp :leftexp (make-areflisp :array (make-lisp-ast lexp) :i (list (quote yotta-var::i) (quote yotta-var::k))) :rightexp (make-areflisp :array (make-lisp-ast rexp) :i (list (quote yotta-var::k) (quote yotta-var::j)))))) (make-setflisp :var (make-areflisp :array (quote yotta-var::rez) :i (list (quote yotta-var::i) (quote yotta-var::j))) :exp (quote yotta-var::cur))))) :leftexp (make-lisp-ast lexp) :rightexp (make-lisp-ast rexp))) (t (error "~S is not valid MUL." (list '* lexp rexp))))) (_ (error "Not a valid expression node."))))
6,450
Common Lisp
.lisp
154
30.75974
97
0.538265
Jobhdez/Yotta
16
0
0
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
765b33d3cd50c2ed917aff2535f0bce4cf758a70f450deea2d7a8f359ee29f14
10,730
[ -1 ]
10,731
c-intermediate-language.lisp
Jobhdez_Yotta/src/backends/c/c-intermediate-language.lisp
(in-package #:yotta) ;;; this the c intermediate language; it consumes the parse tree. (defun make-c-interlan (parse-tree) "Makes the C INTERMEDIATE LANGUAGE given the parse tree." (match parse-tree ((program :expressions exps) (if (listp exps) (mapcar #'make-c-ast exps) (make-c-ast exps))))) (defun make-c-ast (parse-tree) "Makes the C ast." (match parse-tree ((assignment :variable var :exp e) (make-c-assignment :type (quote yotta-var::int) :var-name (generate-name e) :exp (make-c-ast e))) ((vec :entries v) (make-c-vector :type (quote yotta-var::int) :length (length v) :elements (mapcar #'make-c-ast v) :name (generate-name "vec"))) ((num :num n) (make-c-number :type (quote yotta-var::int) :n n)) ((matrix :entries m) (make-c-matrix :type (quote yotta-var::int) :length (list (length m) (length (vec-entries (car m)))) :elements (mapcar #'make-c-ast m) :name (generate-name "matrix"))) ((plus :left-exp lexp :right-exp rexp) (cond ((and (vec-p lexp) (vec-p rexp)) (make-c-vector-addition :left-exp (make-c-ast lexp) :right-exp (make-c-ast rexp) :i (quote yotta-var::i) :n (length (vec-entries lexp)) :fn-name (generate-name "vectorsum") :type (quote yotta-var::int))) ((and (matrix-p lexp) (matrix-p rexp)) (make-c-matrix-addition :left-exp (make-c-ast lexp) :right-exp (make-c-ast rexp) :dimension (list (length (matrix-entries lexp)) (length (vec-entries (car (matrix-entries lexp))))))))) ((minus :left-exp lexp :right-exp rexp) (cond ((and (vec-p lexp) (vec-p rexp)) (make-c-vector-subtraction :left-exp (make-c-ast lexp) :right-exp (make-c-ast rexp) :i (quote yotta-var::i) :n (length (vec-entries lexp)) :fn-name (generate-name "vectorsub") :type (quote yotta-var::int))) ((and (matrix-p lexp) (matrix-p rexp)) (make-c-matrix-subtraction :left-exp (make-c-ast lexp) :right-exp (make-c-ast rexp) :dimension (list (length (matrix-entries lexp)) (length (vec-entries (car (matrix-entries lexp))))))))) (_ (error "Only vecs right now.")))) (defun generate-name (exp) "Consumes a node or a string and creates a name." (match exp ((guard x (stringp x)) (*gensym* x)) ((vec :entries v) (*gensym* "vec")) ((matrix :entries m) (*gensym* "matrix")) (_ (error "Not a valid expression.")))) (defvar gensym-count 0) (defun *gensym* (string-name) (progn (setf gensym-count (+ gensym-count 1)) (concatenate 'string string-name (write-to-string gensym-count))))
2,747
Common Lisp
.lisp
77
29.649351
65
0.611889
Jobhdez/Yotta
16
0
0
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
18ee54b2e0b6df75313d844d4af604d6c3eaab72c7032d93d781dcafea8cf65e
10,731
[ -1 ]
10,732
ast.lisp
Jobhdez_Yotta/src/backends/c/ast.lisp
(in-package #:yotta) ;;;; ast nodes for the c intermediate language (defstruct c-assignment type var-name exp) (defstruct c-vector type length elements name) (defstruct c-number type n) (defstruct c-matrix type length elements name) (defstruct c-vector-addition left-exp right-exp i n fn-name type) (defstruct c-vector-subtraction left-exp right-exp i n fn-name type) (defstruct c-matrix-addition left-exp right-exp dimension) (defstruct c-matrix-subtraction left-exp right-exp dimension)
560
Common Lisp
.lisp
41
10.926829
46
0.752941
Jobhdez/Yotta
16
0
0
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
271b2466adf9a93e56766cd8f7b30ddf137f1a7203d6ac4ca6020ce8ce195b08
10,732
[ -1 ]
10,733
lexer.lisp
Jobhdez_Yotta/src/lexer/lexer.lisp
(in-package #:yotta) (deftype token () `(cons keyword t)) (defun tok (type &optional val) (cons type val)) (alexa:define-string-lexer linear-algebra-lexer "Make a lexical analyzer for linear algebra expressions." ((:num "\\d+") (:name "[A-Za-z][A-Za-z0-9_]*")) ("{{NAME}}" (return (tok :variable (intern (string-upcase $@) "YOTTA-VAR")))) ("{{NUM}}" (return (tok :number (parse-integer $@)))) ("\\+" (return (tok :plus (intern $@ 'keyword)))) ("\\-" (return (tok :minus (intern $@ 'keyword)))) ("\\*" (return (tok :mul (intern $@ 'keyword)))) ("\\[" (return (tok :left-bracket))) ("\\]" (return (tok :right-bracket))) ("\\=" (return (tok :assignment))) ("\\s+" nil)) (defun token-generator (toks) "Make a lexer that is compatible with CL-YACC." (lambda () (if (null toks) (values nil nil) (let ((tok (pop toks))) (values (token-type tok) (token-value tok)))))) (defun token-type (tok) "returns the type the token TOK." (car tok)) (defun token-value (tok) "Returns the value of the token TOK." (cdr tok)) (defun lex-line (string) "Make a list of tokens given the expression represented as a string." (loop :with lexer := (linear-algebra-lexer string) :for tok := (funcall lexer) :while tok :collect tok))
1,335
Common Lisp
.lisp
38
32.210526
80
0.600155
Jobhdez/Yotta
16
0
0
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
1a7b9eec4092d018af2a007a29bc2cbd6e94771aac147c177d60b0fa5648bd33
10,733
[ -1 ]
10,734
package.lisp
Jobhdez_Yotta/tests/package.lisp
(fiasco:define-test-package #:yotta-tests (:documentation "Tests for Yotta.") (:use #:cl #:yotta) (:export #:run-yotta-tests))
136
Common Lisp
.lisp
5
24.4
41
0.671756
Jobhdez/Yotta
16
0
0
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
5d958929ac1ca60a69c42a3679fa00c52cd6b786ab7dd8cf18035527db17d486
10,734
[ -1 ]
10,735
lisp-IL-tests.lisp
Jobhdez_Yotta/tests/lisp-IL-tests.lisp
(in-package #:yotta-tests) (deftest test-lispIL-vec () (is (equalp (yotta:make-lisp-interlan (yotta:parse-with-lexer (yotta:token-generator (yotta:lex-line "[3 4 5]")) yotta:*linear-algebra-grammar*)) (list (yotta:MAKE-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:MAKE-NUMLISP :N 3) (yotta:MAKE-NUMLISP :N 4) (yotta:MAKE-NUMLISP :N 5))))))) (deftest test-lispIL-matrix () (is (equalp (yotta:make-lisp-interlan (yotta:parse-with-lexer (yotta:token-generator (yotta:lex-line "[[4 5 6] [5 6 7]]")) yotta:*linear-algebra-grammar*)) (list (yotta:make-matrixlisp :dimension (list 2 3) :matrix (list (yotta:MAKE-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:MAKE-NUMLISP :N 4) (yotta:MAKE-NUMLISP :N 5) (yotta:MAKE-NUMLISP :N 6))) (yotta:MAKE-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:MAKE-NUMLISP :N 5) (yotta:MAKE-NUMLISP :N 6) (yotta:MAKE-NUMLISP :N 7))))))))) (deftest test-lispIL-vecsum () (is (equalp (yotta:make-lisp-interlan (yotta:parse-with-lexer (yotta:token-generator (yotta:lex-line "[4 5 6] + [5 6 7]")) yotta:*linear-algebra-grammar*)) (list (yotta:MAKE-VECTORSUM :I (quote yotta-var::I) :N 3 :EXP (yotta:MAKE-SETFLISP :VAR (yotta:MAKE-AREFLISP :ARRAY (quote yotta-var::NEWARRAY) :I (quote yotta-var::I)) :EXP (yotta:MAKE-SUMLISP :LEFTEXP (yotta:MAKE-AREFLISP :ARRAY (yotta:MAKE-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:MAKE-NUMLISP :N 4) (yotta:MAKE-NUMLISP :N 5) (yotta:MAKE-NUMLISP :N 6))) :I (quote yotta-var::I)) :RIGHTEXP (yotta:MAKE-AREFLISP :ARRAY (yotta:MAKE-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:MAKE-NUMLISP :N 5) (yotta:MAKE-NUMLISP :N 6) (yotta:MAKE-NUMLISP :N 7))) :I (quote yotta-var::I)))) :LEFTEXP (yotta:MAKE-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:MAKE-NUMLISP :N 4) (yotta:MAKE-NUMLISP :N 5) (yotta:MAKE-NUMLISP :N 6))) :RIGHTEXP (yotta:MAKE-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:MAKE-NUMLISP :N 5) (yotta:MAKE-NUMLISP :N 6) (yotta:MAKE-NUMLISP :N 7)))))))) (deftest test-lispIL-vecminus () (is (equalp (yotta:make-lisp-interlan (yotta:parse-with-lexer (yotta:token-generator (yotta:lex-line "[4 5 6] - [5 6 7]")) yotta:*linear-algebra-grammar*)) (list (yotta:MAKE-VECTORMINUS :I (quote yotta-var::I) :N 3 :EXP (yotta:MAKE-SETFLISP :VAR (yotta:MAKE-AREFLISP :ARRAY (quote yotta-var::NEWARRAY) :I (quote yotta-var::I)) :EXP (yotta:MAKE-MINUSLISP :LEFTEXP (yotta:MAKE-AREFLISP :ARRAY (yotta:MAKE-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:MAKE-NUMLISP :N 4) (yotta:MAKE-NUMLISP :N 5) (yotta:MAKE-NUMLISP :N 6))) :I (quote yotta-var::I)) :RIGHTEXP (yotta:MAKE-AREFLISP :ARRAY (yotta:MAKE-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:MAKE-NUMLISP :N 5) (yotta:MAKE-NUMLISP :N 6) (yotta:MAKE-NUMLISP :N 7))) :I (quote yotta-var::I)))) :LEFTEXP (yotta:MAKE-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:MAKE-NUMLISP :N 4) (yotta:MAKE-NUMLISP :N 5) (yotta:MAKE-NUMLISP :N 6))) :RIGHTEXP (yotta:MAKE-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:MAKE-NUMLISP :N 5) (yotta:MAKE-NUMLISP :N 6) (yotta:MAKE-NUMLISP :N 7)))))))) (deftest test-lispIL-matrix-sum () (is (equalp (yotta:make-lisp-interlan (yotta:parse-with-lexer (yotta:token-generator (yotta:lex-line "[[3 4 5] [6 7 8]] + [[9 10 11] [12 13 14]]")) yotta:*linear-algebra-grammar*)) (list (yotta:make-MATRIXSUM :I (quote YOTTA-VAR::I) :N 2 :EXP (yotta:make-LOOPLISP :I (quote YOTTA-VAR::J) :N 3 :EXP (yotta:make-SETFLISP :VAR (yotta:make-AREFLISP :ARRAY (quote YOTTA-VAR::NEWARRAY) :I (list (quote YOTTA-VAR::I) (quote YOTTA-VAR::J))) :EXP (yotta:make-SUMLISP :LEFTEXP (yotta:make-AREFLISP :ARRAY (yotta:make-MATRIXLISP :DIMENSION (list 2 3) :MATRIX (list (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 3) (yotta:make-NUMLISP :N 4) (yotta:make-NUMLISP :N 5))) (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 6) (yotta:make-NUMLISP :N 7) (yotta:make-NUMLISP :N 8))))) :I (list (quote YOTTA-VAR::I) (quote YOTTA-VAR::J))) :RIGHTEXP (yotta:make-AREFLISP :ARRAY (yotta:make-MATRIXLISP :DIMENSION (list 2 3) :MATRIX (list (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 9) (yotta:make-NUMLISP :N 10) (yotta:make-NUMLISP :N 11))) (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 12) (yotta:make-NUMLISP :N 13) (yotta:make-NUMLISP :N 14))))) :I (list (quote YOTTA-VAR::I) (quote YOTTA-VAR::J)))))) :LEFTEXP (yotta:make-MATRIXLISP :DIMENSION (list 2 3) :MATRIX (list (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 3) (yotta:make-NUMLISP :N 4) (yotta:make-NUMLISP :N 5))) (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 6) (yotta:make-NUMLISP :N 7) (yotta:make-NUMLISP :N 8))))) :RIGHTEXP (yotta:make-MATRIXLISP :DIMENSION (list 2 3) :MATRIX (list (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 9) (yotta:make-NUMLISP :N 10) (yotta:make-NUMLISP :N 11))) (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 12) (yotta:make-NUMLISP :N 13) (yotta:make-NUMLISP :N 14)))))))))) (deftest test-lispIL-matrix-minus () (is (equalp (yotta:make-lisp-interlan (yotta:parse-with-lexer (yotta:token-generator (yotta:lex-line "[[3 4 5] [6 7 8]] - [[9 10 11] [12 13 14]]")) yotta:*linear-algebra-grammar*)) (list (yotta:make-MATRIXMINUS :I (quote YOTTA-VAR::I) :N 2 :EXP (yotta:make-LOOPLISP :I (quote YOTTA-VAR::J) :N 3 :EXP (yotta:make-SETFLISP :VAR (yotta:make-AREFLISP :ARRAY (quote YOTTA-VAR::NEWARRAY) :I (list (quote YOTTA-VAR::I) (quote YOTTA-VAR::J))) :EXP (yotta:make-MINUSLISP :LEFTEXP (yotta:make-AREFLISP :ARRAY (yotta:make-MATRIXLISP :DIMENSION (list 2 3) :MATRIX (list (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 3) (yotta:make-NUMLISP :N 4) (yotta:make-NUMLISP :N 5))) (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 6) (yotta:make-NUMLISP :N 7) (yotta:make-NUMLISP :N 8))))) :I (list (quote YOTTA-VAR::I) (quote YOTTA-VAR::J))) :RIGHTEXP (yotta:make-AREFLISP :ARRAY (yotta:make-MATRIXLISP :DIMENSION (list 2 3) :MATRIX (list (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 9) (yotta:make-NUMLISP :N 10) (yotta:make-NUMLISP :N 11))) (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 12) (yotta:make-NUMLISP :N 13) (yotta:make-NUMLISP :N 14))))) :I (list (quote YOTTA-VAR::I) (quote YOTTA-VAR::J)))))) :LEFTEXP (yotta:make-MATRIXLISP :DIMENSION (list 2 3) :MATRIX (list (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 3) (yotta:make-NUMLISP :N 4) (yotta:make-NUMLISP :N 5))) (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 6) (yotta:make-NUMLISP :N 7) (yotta:make-NUMLISP :N 8))))) :RIGHTEXP (yotta:make-MATRIXLISP :DIMENSION (list 2 3) :MATRIX (list (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 9) (yotta:make-NUMLISP :N 10) (yotta:make-NUMLISP :N 11))) (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 12) (yotta:make-NUMLISP :N 13) (yotta:make-NUMLISP :N 14)))))))))) (deftest test-lispIL-dotproduct () (is (equalp (yotta:make-lisp-interlan (yotta:parse-with-lexer (yotta:token-generator (yotta:lex-line "[4 5 6] * [4 5 6]")) yotta:*linear-algebra-grammar*)) (list (yotta:make-DOTPRODUCT :EXPRESSION (yotta:make-LETEXPRESSION :ID (quote YOTTA-VAR::VEC) :EXPR (yotta:make-FAKEVECMUL :VEC (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 4) (yotta:make-NUMLISP :N 5) (yotta:make-NUMLISP :N 6))) :VEC2 (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 4) (yotta:make-NUMLISP :N 5) (yotta:make-NUMLISP :N 6)))) :BODY (yotta:make-PROGNLISP :EXPRESSIONS (list (yotta:make-SETQLISP :VAR (quote YOTTA-VAR::SUM) :EXP 0) (yotta:make-LOOPLISP :I (quote YOTTA-VAR::I) :N 3 :EXP (yotta:make-SETQLISP :VAR (quote YOTTA-VAR::SUM) :EXP (yotta:make-SUMLISP :LEFTEXP (quote YOTTA-VAR::SUM) :RIGHTEXP (yotta:make-AREFLISP :ARRAY (quote YOTTA-VAR::VEC) :I (quote YOTTA-VAR::I))))) (quote YOTTA-VAR::SUM)))) :VECTOR1 (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 4) (yotta:make-NUMLISP :N 5) (yotta:make-NUMLISP :N 6))) :VECTOR2 (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 4) (yotta:make-NUMLISP :N 5) (yotta:make-NUMLISP :N 6)))))))) (deftest test-lispIL-matrixproduct () (is (equalp (yotta:make-lisp-interlan (yotta:parse-with-lexer (yotta:token-generator (yotta:lex-line "[[4 5 6] [6 7 8]] * [[56 6] [7 8] [8 9]]")) yotta:*linear-algebra-grammar*)) (list (yotta:make-MATRIXMUL :I (quote YOTTA-VAR::I) :N 2 :EXP (yotta:make-LOOPLISP :I (quote YOTTA-VAR::J) :N 2 :EXP (yotta:make-LETEXPRESSION :ID (quote YOTTA-VAR::CUR) :EXPR 0 :BODY (list (yotta:make-LOOPLISP :I (quote YOTTA-VAR::K) :N 3 :EXP (yotta:make-INCFLISP :ID (quote YOTTA-VAR::CUR) :EXP (yotta:make-MULLISP :LEFTEXP (yotta:make-AREFLISP :ARRAY (yotta:make-MATRIXLISP :DIMENSION (list 2 3) :MATRIX (list (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 4) (yotta:make-NUMLISP :N 5) (yotta:make-NUMLISP :N 6))) (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 6) (yotta:make-NUMLISP :N 7) (yotta:make-NUMLISP :N 8))))) :I (list (quote YOTTA-VAR::I) (quote YOTTA-VAR::K))) :RIGHTEXP (yotta:make-AREFLISP :ARRAY (yotta:make-MATRIXLISP :DIMENSION (list 3 2) :MATRIX (list (yotta:make-VECTORLISP :DIMENSION 2 :ELEMENTS (list (yotta:make-NUMLISP :N 56) (yotta:make-NUMLISP :N 6))) (yotta:make-VECTORLISP :DIMENSION 2 :ELEMENTS (list (yotta:make-NUMLISP :N 7) (yotta:make-NUMLISP :N 8))) (yotta:make-VECTORLISP :DIMENSION 2 :ELEMENTS (list (yotta:make-NUMLISP :N 8) (yotta:make-NUMLISP :N 9))))) :I (list (quote YOTTA-VAR::K) (quote YOTTA-VAR::J)))))) (yotta:make-SETFLISP :VAR (yotta:make-AREFLISP :ARRAY(quote YOTTA-VAR::REZ) :I (list (quote YOTTA-VAR::I) (quote YOTTA-VAR::J))) :EXP (quote yotta-var::cur))))) :LEFTEXP (yotta:make-MATRIXLISP :DIMENSION (list 2 3) :MATRIX (list (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 4) (yotta:make-NUMLISP :N 5) (yotta:make-NUMLISP :N 6))) (yotta:make-VECTORLISP :DIMENSION 3 :ELEMENTS (list (yotta:make-NUMLISP :N 6) (yotta:make-NUMLISP :N 7) (yotta:make-NUMLISP :N 8))))) :RIGHTEXP (yotta:make-MATRIXLISP :DIMENSION (list 3 2) :MATRIX (list (yotta:make-VECTORLISP :DIMENSION 2 :ELEMENTS (list (yotta:make-NUMLISP :N 56) (yotta:make-NUMLISP :N 6))) (yotta:make-VECTORLISP :DIMENSION 2 :ELEMENTS (list (yotta:make-NUMLISP :N 7) (yotta:make-NUMLISP :N 8))) (yotta:make-VECTORLISP :DIMENSION 2 :ELEMENTS (list (yotta:make-NUMLISP :N 8) (yotta:make-NUMLISP :N 9))))))))))
27,273
Common Lisp
.lisp
411
24.768856
116
0.281011
Jobhdez/Yotta
16
0
0
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
c6e0b2a9af48618951957ad87571756fec4325979898d19298a09deae1cadec6
10,735
[ -1 ]
10,736
parsing-tests.lisp
Jobhdez_Yotta/tests/parsing-tests.lisp
(in-package #:yotta-tests) (deftest test-parse-vec () (is (equalp (yotta:parse-with-lexer (yotta:token-generator (yotta:lex-line "[3 4 5]")) yotta:*linear-algebra-grammar*) (yotta:make-program :expressions (yotta:make-vec :entries (list (yotta:make-num :num 3) (yotta:make-num :num 4) (yotta:make-num :num 5))))))) (deftest test-parse-matrix () (is (equalp (yotta:parse-with-lexer (yotta:token-generator (yotta:lex-line "[[3 4 5] [5 6 7]]")) yotta:*linear-algebra-grammar*) (yotta:MAKE-PROGRAM :EXPRESSIONS (yotta:MAKE-MATRIX :ENTRIES (list (yotta:MAKE-VEC :ENTRIES (list (yotta:MAKE-NUM :NUM 3) (yotta:MAKE-NUM :NUM 4) (yotta:MAKE-NUM :NUM 5))) (yotta:MAKE-VEC :ENTRIES (list (yotta:MAKE-NUM :NUM 5) (yotta:MAKE-NUM :NUM 6) (yotta:MAKE-NUM :NUM 7))))))))) (deftest test-parse-vector-sum () (is (equalp (yotta:parse-with-lexer (yotta:token-generator (yotta:lex-line "[3 4 5] + [4 5 6]")) yotta:*linear-algebra-grammar*) (yotta:MAKE-PROGRAM :EXPRESSIONS (yotta:MAKE-PLUS :LEFT-EXP (yotta:MAKE-VEC :ENTRIES (list (yotta:MAKE-NUM :NUM 3) (yotta:MAKE-NUM :NUM 4) (yotta:MAKE-NUM :NUM 5))) :RIGHT-EXP (yotta:MAKE-VEC :ENTRIES (list (yotta:MAKE-NUM :NUM 4) (yotta:MAKE-NUM :NUM 5) (yotta:MAKE-NUM :NUM 6)))))))) (deftest test-parse-vector-minus () (is (equalp (yotta:parse-with-lexer (yotta:token-generator (yotta:lex-line "[3 4 5] - [4 5 6]")) yotta:*linear-algebra-grammar*) (yotta:MAKE-PROGRAM :EXPRESSIONS (yotta:MAKE-MINUS :LEFT-EXP (yotta:MAKE-VEC :ENTRIES (list (yotta:MAKE-NUM :NUM 3) (yotta:MAKE-NUM :NUM 4) (yotta:MAKE-NUM :NUM 5))) :RIGHT-EXP (yotta:MAKE-VEC :ENTRIES (list (yotta:MAKE-NUM :NUM 4) (yotta:MAKE-NUM :NUM 5) (yotta:MAKE-NUM :NUM 6)))))))) (deftest test-parse-matrix-sum () (is (equalp (yotta:parse-with-lexer (yotta:token-generator (yotta:lex-line "[[3 4 5] [4 5 6]] + [[4 5 6] [6 7 8]]")) yotta:*linear-algebra-grammar*) (yotta:MAKE-PROGRAM :EXPRESSIONS (yotta:MAKE-PLUS :LEFT-EXP (yotta:MAKE-MATRIX :ENTRIES (list (yotta:MAKE-VEC :ENTRIES (list (yotta:MAKE-NUM :NUM 3) (yotta:MAKE-NUM :NUM 4) (yotta:MAKE-NUM :NUM 5))) (yotta:MAKE-VEC :ENTRIES (list (yotta:MAKE-NUM :NUM 4) (yotta:MAKE-NUM :NUM 5) (yotta:MAKE-NUM :NUM 6))))) :RIGHT-EXP (yotta:MAKE-MATRIX :ENTRIES (list (yotta:MAKE-VEC :ENTRIES (list (yotta:MAKE-NUM :NUM 4) (yotta:MAKE-NUM :NUM 5) (yotta:MAKE-NUM :NUM 6))) (yotta:MAKE-VEC :ENTRIES (list (yotta:MAKE-NUM :NUM 6) (yotta:MAKE-NUM :NUM 7) (yotta:MAKE-NUM :NUM 8)))))))))) (deftest test-parse-matrix-minus () (is (equalp (yotta:parse-with-lexer (yotta:token-generator (yotta:lex-line "[[3 4 5] [4 5 6]] - [[4 5 6] [6 7 8]]")) yotta:*linear-algebra-grammar*) (yotta:MAKE-PROGRAM :EXPRESSIONS (yotta:MAKE-MINUS :LEFT-EXP (yotta:MAKE-MATRIX :ENTRIES (list (yotta:MAKE-VEC :ENTRIES (list (yotta:MAKE-NUM :NUM 3) (yotta:MAKE-NUM :NUM 4) (yotta:MAKE-NUM :NUM 5))) (yotta:MAKE-VEC :ENTRIES (list (yotta:MAKE-NUM :NUM 4) (yotta:MAKE-NUM :NUM 5) (yotta:MAKE-NUM :NUM 6))))) :RIGHT-EXP (yotta:MAKE-MATRIX :ENTRIES (list (yotta:MAKE-VEC :ENTRIES (list (yotta:MAKE-NUM :NUM 4) (yotta:MAKE-NUM :NUM 5) (yotta:MAKE-NUM :NUM 6))) (yotta:MAKE-VEC :ENTRIES (list (yotta:MAKE-NUM :NUM 6) (yotta:MAKE-NUM :NUM 7) (yotta:MAKE-NUM :NUM 8)))))))))) (deftest test-parse-assignment () (is (equalp (yotta:parse-with-lexer (yotta:token-generator (yotta:lex-line "x = [[4 5 6] [5 6 7]]")) yotta:*linear-algebra-grammar*) (yotta:MAKE-PROGRAM :EXPRESSIONS (yotta:MAKE-ASSIGNMENT :VARIABLE (quote yotta-var::x) :EXP (yotta:MAKE-MATRIX :ENTRIES (list (yotta:MAKE-VEC :ENTRIES (list (yotta:MAKE-NUM :NUM 4) (yotta:MAKE-NUM :NUM 5) (yotta:MAKE-NUM :NUM 6))) (yotta:MAKE-VEC :ENTRIES (list (yotta:MAKE-NUM :NUM 5) (yotta:MAKE-NUM :NUM 6) (yotta:MAKE-NUM :NUM 7))))))))))
5,302
Common Lisp
.lisp
116
30.663793
90
0.495017
Jobhdez/Yotta
16
0
0
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
4cb4569f76559c7ef91b0e221e00087cea8a7c6eb58873bf3cbed971a20ef83c
10,736
[ -1 ]
10,737
utilities.lisp
Jobhdez_Yotta/tests/utilities.lisp
(in-package #:yotta-tests) (defun run-yotta-tests () (run-package-tests :packages '(:yotta-tests) :interactive t))
124
Common Lisp
.lisp
5
22
28
0.694915
Jobhdez/Yotta
16
0
0
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
fa78742cce7185a79d0c6d0b3e7f4a43f959517a07acd4c0758a48155cec827a
10,737
[ -1 ]
10,738
yotta.asd
Jobhdez_Yotta/yotta.asd
(asdf:defsystem #:yotta :description "A Linear Algebra compiler." :author "Job Hernandez <[email protected]>" :in-order-to ((asdf:test-op (asdf:test-op #:yotta/tests))) :depends-on (#:alexa #:yacc #:alexandria #:trivia) :serial t :pathname "src/" :components ((:file "package") (:module "lexer" :components ((:file "lexer"))) (:module "parser" :components ((:file "ast") (:file "parser") (:file "parsefile"))) (:module "backends" :components ((:module "lisp" :components ((:file "lispIL") (:file "ast") (:file "generatelisp"))) (:module "c" :components ((:file "ast") (:file "c-intermediate-language") (:file "compile-to-c"))))) (:file "yotta") (:module "performance" :components ((:file "performance-tests"))))) (asdf:defsystem #:yotta/tests :description "Tests for Yotta." :author "Job Hernandez <[email protected]>" :depends-on (#:yotta #:fiasco) :perform (asdf:test-op (o s) (unless (symbol-call :yotta-tests :run-yotta-tests) (error "Tests failed."))) :pathname "tests/" :serial t :components ((:file "package") (:file "parsing-tests") (:file "lisp-IL-tests") (:file "utilities")))
1,296
Common Lisp
.asd
41
25.609756
62
0.587719
Jobhdez/Yotta
16
0
0
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
f8281a389cc716a69cc09a75885e059206637db60100e232cfee9ddae0232a5f
10,738
[ -1 ]
10,770
make-shake-executable.lisp
Th30n_cl-shake/make-shake-executable.lisp
(require 'asdf) (defvar *sdl2-library-path* nil "path to SDL2.dll") (let* ((dst-dir (uiop:merge-pathnames* (format nil "./shake-~A-~A/" (if (uiop:os-windows-p) "win" "linux") (string-downcase (uiop:architecture))))) (built-exe (format nil "shake/shake-command~A" (if (uiop:os-windows-p) ".exe" ""))) (dst-exe (uiop:merge-pathnames* (format nil "shake~A" (if (uiop:os-windows-p) ".exe" "")) dst-dir))) (format t "Building...~%") (uiop:delete-directory-tree dst-dir :if-does-not-exist :ignore :validate t) (uiop:ensure-all-directories-exist (list dst-dir)) (uiop:run-program '("sbcl" "--eval" "(progn (asdf:load-system :shiva :force t) (ql:quickload \"swank\") (asdf:make :shake/executable))" "--quit")) (uiop:rename-file-overwriting-target built-exe dst-exe) (format t "Created: ~A~%" dst-exe) (labels ((copy-file (data-path dst-path) (uiop:copy-file data-path (uiop:merge-pathnames* dst-path dst-dir)) (format t "Copied: ~A~%" (uiop:merge-pathnames* dst-path dst-dir))) (map-file (map-path) (copy-file map-path (file-namestring map-path))) (model-file (model-path) (copy-file model-path (file-namestring model-path))) (data-dir (dir-path &optional dst-name) (let ((dir-path (uiop:ensure-directory-pathname dir-path)) (dir-name (uiop:ensure-directory-pathname (if dst-name dst-name (car (last (pathname-directory (uiop:ensure-directory-pathname dir-path)))))))) (uiop:ensure-all-directories-exist (list (uiop:merge-pathnames* dir-name dst-dir))) (dolist (f (uiop:directory-files dir-path)) (let ((dst (uiop:merge-pathnames* (uiop:merge-pathnames* (file-namestring f) dir-name) dst-dir))) (uiop:copy-file f dst) (format t "Copied: ~A~%" dst))) (dolist (subdir (uiop:subdirectories dir-path)) (data-dir subdir (uiop:merge-pathnames* (car (last (pathname-directory subdir))) dir-name)))))) (when (uiop:os-windows-p) (copy-file *sdl2-library-path* "SDL2.dll")) (map-file "./shake/test.bsp") (data-dir "./shake/share") (data-dir "./shake/shaders") (model-file "./enemy.obj") (model-file "./shotgun.obj")))
2,552
Common Lisp
.lisp
42
46.619048
148
0.555423
Th30n/cl-shake
10
1
1
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
0e78e3ff9401e5a68b3f2b802bcb257cb1748a8b16d7deebcfc2c4d08622bdff
10,770
[ -1 ]
10,771
shiva-test.lisp
Th30n_cl-shake/shiva/shiva-test.lisp
;;;; Copyright (C) 2016 Teon Banek ;;;; ;;;; This program is free software; you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation; either version 2 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License along ;;;; with this program; if not, write to the Free Software Foundation, Inc., ;;;; 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. (in-package #:cl-user) (defpackage #:shiva-test (:use #:cl #:prove #:shiva)) (in-package #:shiva-test) (plan nil) (subtest "Testing v-" (is (v- (v 5 3) (v 4 7)) (v 1 -4) :test #'v=) (is-type (v- (v 3 4) (v 4 4)) '(vector shiva-float 2))) (subtest "Testing vdot" (is (vdot (v 3 5) (v 4 2)) (shiva-float 22.0)) (is (vdot (v 2 4) (v 8 -4)) (shiva-float 0.0))) (subtest "Testing m*" (is (m* (mat '(1 2 3) '(4 5 6)) (mat '(5 6) '(7 8) '(9 10))) (mat '(46 52) '(109 124)) :test #'equalp) (is-type (m* (mat '(1 2) '(3 4)) (mat '(1 0) '(0 1))) '(mat 2))) (subtest "Testing transforms" (is (vtransform (translation :x 2 :z -2) (v 3 5 0 1)) (v 5 5 -2 1) :test #'v=) (is (vtransform (translation :y 3) (v 4 5 6 0)) (v 4 5 6 0) :test #'v=) (is (vtransform (scale :x 5) (v 2 3 4 1)) (v 10 3 4 1) :test #'v=) (is (vtransform (scale :y 3 :z 4) (v 1 2 3 0)) (v 1 6 12 0) :test #'v=) (is (vtransform (rotation (v 0 0 1) (/ pi 2)) (v 1 0 0 1)) (v 0 1 0 1) :test #'v=) (is (vtransform (rotation (v 0 0 1) (- pi)) (v 1 0 0 1)) (v -1 0 0 1) :test #'v=) (let ((scale (scale :x 2)) (translation (translation :x 1 :y 3))) (is (vtransform (m* scale translation) (v 1 2 3 1)) (v 4 5 3 1) :test #'v=) (is (vtransform (m* translation scale) (v 1 2 3 1)) (v 3 5 3 1) :test #'v=) (is (vtransform (m* translation scale) (v 1 2 3 0)) (vtransform (m* scale translation) (v 1 2 3 0)) :test #'v=))) (subtest "Testing projections" (let ((ortho (ortho -1.0 2.0 -3.0 4.0 -5.0 6.0)) (persp (perspective (* deg->rad 90.0) 1.0 1.0 10.0))) (is (vtransform ortho (v -1 -3 5 1)) (v -1 -1 -1 1) :test #'v=) (is (vtransform ortho (v 2 4 -6 1)) (v 1 1 1 1) :test #'v=) (is (vtransform ortho (v 0.5 0.5 -0.5 1)) (v 0 0 0 1) :test #'v=) (is (vtransform persp (v 0 0 -1 1)) (v 0 0 -1 1) :test #'v=) (is (vtransform persp (v 1 1 -1 1)) (v 1 1 -1 1) :test #'v=) (is (vtransform persp (v 0 0 -10 1)) (v 0 0 10 10) :test #'v=) (is (vtransform persp (v -10 -10 -10 1)) (v -10 -10 10 10) :test #'v=))) (finalize)
3,169
Common Lisp
.lisp
87
30.494253
76
0.534505
Th30n/cl-shake
10
1
1
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
b0386645a68a4d592c1b3a935a38122fbfa3e74c15b9579d6d85a2308504ec65
10,771
[ -1 ]
10,772
package.lisp
Th30n_cl-shake/shiva/package.lisp
;;;; Copyright (C) 2016 Teon Banek ;;;; ;;;; This program is free software; you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation; either version 2 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License along ;;;; with this program; if not, write to the Free Software Foundation, Inc., ;;;; 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. (in-package #:cl-user) (defpackage #:shiva (:use #:cl #:iterate #:alexandria #:metabang.bind) (:export #:shiva-float #:float= #:float> #:float>= #:float< #:float<= #:rad->deg #:deg->rad #:vec #:v #:vf #:vx #:vy #:vz #:vw #:v3->v2 #:v2->v3 #:v2->v3f #:v- #:v+ #:v= #:vnorm #:vnormalize #:vnormalizef #:vscale #:vscalef #:vdot #:vcross #:vtransform #:vrotate #:v3dot #:vdist #:vdistsq #:quat #:q #:q+ #:q* #:qconj #:qrotation #:q->mat #:q->euler-x #:mat #:mat-row #:mat-col #:m* #:translation #:scale #:rotation #:ortho #:perspective) ;; swizzle operators (:export #:vxx #:vxy #:vyx #:vyy #:vxxx #:vxxy #:vxxz #:vxyx #:vxyy #:vxyz #:vxzx #:vxzy #:vxzz #:vyxx :vyxy :vyxz :vyyx :vyyy :vyyz :vyzx :vyzy :vyzz :vzxx :vzxy #:vzxz :vzyx :vzyy :vzyz :vzzx :vzzy :vzzz) (:export #:vrrr #:vrrg #:vrrb #:vrgr #:vrgg #:vrgb #:vrbr #:vrbg #:vrbb #:vgrr #:vgrg #:vgrb #:vggr #:vggg #:vggb #:vgbr #:vgbg #:vgbb #:vbrr #:vbrg :vbrb #:vbgr #:vbgg #:vbgb #:vbbr #:vbbg #:vbbb))
1,966
Common Lisp
.lisp
42
40.5
77
0.593132
Th30n/cl-shake
10
1
1
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
d962a377215957ba564bda5b3d492dfa99880d33c25b98a3892af849b9f3f02e
10,772
[ -1 ]
10,773
shiva.lisp
Th30n_cl-shake/shiva/shiva.lisp
;;;; Copyright (C) 2016 Teon Banek ;;;; ;;;; This program is free software; you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation; either version 2 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License along ;;;; with this program; if not, write to the Free Software Foundation, Inc., ;;;; 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. (in-package #:shiva) (declaim (optimize (speed 3))) (eval-when (:compile-toplevel :load-toplevel :execute) #-shiva-double-float (pushnew :shiva-single-float *features*) #+shiva-double-float (pushnew :shiva-double-float *features*) (assert (not (and (member :shiva-single-float *features*) (member :shiva-double-float *features*))))) #+shiva-double-float (deftype shiva-float (&optional min max) `(double-float ,min ,max)) #-shiva-double-float (deftype shiva-float (&optional min max) `(single-float ,min ,max)) (eval-when (:compile-toplevel :load-toplevel :execute) (declaim (inline shiva-float)) (defun shiva-float (x) (coerce x 'shiva-float))) (deftype vec (size) `(simple-array shiva-float (,size))) ;; purpose-specific language compiler for matrix computation (defmacro tensor (indices arrays (&key scalars simple-arrays) &body body) (let ((base-arrays `(,@(mapcar #'car arrays) ,@(mapcar (lambda (x) (if (consp x) (car x) x)) simple-arrays))) (loop-collectors '((sum . sum) (min . minimize) (max . maximize)))) (labels ((expand-array (dims &key (type 'shiva-float)) `(make-array ,dims :element-type ',type)) (expand-array-declaration (name dims &key (type 'shiva-float)) (declare (ignore dims)) `(declare (type (simple-array ,type) ,name))) (let-arrays (code) (let ((decls (iter (for array in arrays) (collect `(,(car array) ,(apply #'expand-array (cdr array)))))) (new-array-decls (iter (for array in arrays) (collect (apply #'expand-array-declaration array)))) (other-decls `(,@(iter (for scalar in scalars) (collect `(declare (type shiva-float ,scalar)))) ,@(iter (for simple-array in simple-arrays) (if (consp simple-array) (bind (((name &key type) simple-array)) (collect `(declare (type (simple-array ,type) ,name)))) (collect `(declare (type (simple-array shiva-float) ,simple-array)))))))) (cond ((or decls other-decls) `(let ,decls ,@new-array-decls ,@other-decls ,@code)) (t `(progn ,@code))))) (expand-index (index) (bind (((iname ifrom ito &key down) (assoc index indices))) (if down `((for ,iname from ,ifrom downto ,ito) (declare (type fixnum ,iname))) `((for ,iname from ,ifrom to ,ito) (declare (type fixnum ,iname)))))) (expand-compare (term comparison) (let ((iname (car (assoc (cadr term) indices)))) `(iter ,@(expand-index (cadr term)) (finding ,iname ,comparison ,@(expand-code (cddr term)))))) (expand-term (term) (cond ((not (consp term)) term) ((member (car term) base-arrays) `(aref ,@(expand-code term))) ((eq (car term) '$) `(iter ,@(expand-index (cadr term)) ,@(expand-code (cddr term)))) ((assoc (car term) loop-collectors) (let ((name (cdr (assoc (car term) loop-collectors)))) (with-gensyms (acc) `(iter ,@(expand-index (cadr term)) (,name (progn ,@(expand-code (cddr term))) into ,acc) (declare (type shiva-float ,acc)) (finally (return ,acc)))))) ((eq (car term) 'min-index) (expand-compare term 'minimizing)) ((eq (car term) 'max-index) (expand-compare term 'maximizing)) (t (expand-code term)))) (expand-code (code) (mapcar #'expand-term code))) (let-arrays (expand-code body))))) ;; basic matrix/vector ops (defmacro defmacro-vector-apply (name op-name) `(defmacro ,name (&rest args) (let ((arg-vars (iter (for arg in args) (collect (gensym))))) (with-gensyms (i out) `(let ((n (1- (array-dimension ,(car args) 0))) ,@(mapcar #'list arg-vars args)) (tensor ((,i 0 n)) ((,out (1+ n))) (:simple-arrays ,arg-vars) ($ ,i (setf (,out ,i) (,',op-name ,@(mapcar (lambda (arg) `(aref ,arg ,i)) ,'arg-vars)))) ,out)))))) (defmacro-vector-apply v+ +) (defmacro-vector-apply v- -) (defmacro-vector-apply vmin min) (defmacro-vector-apply vmax max) (declaim (inline vscale)) (defun vscale (scalar vector &aux (n (1- (array-dimension vector 0)))) "Scale a VECTOR by given SCALAR." (check-type vector (simple-array shiva-float)) (setf scalar (shiva-float scalar)) (tensor ((i 0 n)) ((out (1+ n))) (:scalars (scalar) :simple-arrays (vector)) ($ i (setf (out i) (* scalar (vector i)))) out)) (declaim (notinline vscale)) (defun vscalef (scalar vector &aux (n (1- (array-dimension vector 0)))) "Scale a VECTOR in-place by given SCALAR." (check-type vector (simple-array shiva-float)) (setf scalar (shiva-float scalar)) (tensor ((i 0 n)) () (:scalars (scalar) :simple-arrays (vector)) ($ i (setf (vector i) (* scalar (vector i)))) vector)) (defun vtransform (matrix vector &aux (m (1- (array-dimension matrix 0))) (n (1- (array-dimension matrix 1)))) "Transform the given VECTOR using the given MATRIX." (tensor ((i 0 m) (j 0 n)) ((out (1+ m))) (:simple-arrays (vector matrix)) ($ i (setf (out i) (sum j (* (matrix i j) (vector j))))) out)) (defun m* (m1 m2 &aux (n1 (1- (array-dimension m1 0))) (n2 (1- (array-dimension m1 1))) (n3 (1- (array-dimension m2 1)))) (tensor ((i 0 n1) (j 0 n2) (k 0 n3)) ((out (list (1+ n1) (1+ n3)))) (:simple-arrays (m1 m2)) ($ i ($ k (setf (out i k) (sum j (* (m1 i j) (m2 j k)))))) out)) (declaim (inline v3dot)) (declaim (ftype (function ((vec 3) (vec 3)) shiva-float) v3dot)) (defun v3dot (v1 v2) (declare (type (vec 3) v1 v2)) (+ (* (aref v1 0) (aref v2 0)) (* (aref v1 1) (aref v2 1)) (* (aref v1 2) (aref v2 2)))) (defun vdot (v1 v2 &aux (n (1- (array-dimension v1 0)))) "Return the dot product of vectors V1 and V2." (tensor ((i 0 n)) () (:simple-arrays (v1 v2)) (sum i (* (v1 i) (v2 i))))) (declaim (inline vnorm vnormalize vdist vdistsq)) (defun vnorm (v) (sqrt (the (shiva-float #.(shiva-float 0.0)) (vdot v v)))) (defun vnormalize (v) (vscale (/ 1.0 (vnorm v)) v)) (defun vnormalizef (v) (vscalef (/ 1.0 (vnorm v)) v)) (defun vdist (v1 v2) (vnorm (v- v1 v2))) (defun vdistsq (v1 v2) (let ((d (v- v1 v2))) (vdot d d))) (defun angle (v) "Return the angle in radians of vector V around the Z axis." (declare (type (simple-array shiva-float) v)) (atan (vy v) (vx v))) (defun direction (v1 v2) "Return the direction angle in radians between points V1 and V2" (angle (v- v2 v1))) (defconstant rad->deg (shiva-float (/ 180 pi)) "Constant for conversion from radians to degrees.") (defconstant deg->rad (shiva-float (/ pi 180)) "Constant for conversion from degrees to radians.") (defun deg-angle (v) (* rad->deg (angle v))) (defun deg-direction (v1 v2) (* rad->deg (direction v1 v2))) ;; LR-decomposition, linear system solver and matrix inversion (defun lr (m &aux (n (1- (array-dimension m 0)))) (tensor ((i 0 n) (j 0 n) (col-right (1+ i) n) (col-swap 0 n) (row-down (1+ i) n) (row-search i n)) ((a (list (1+ n) (1+ n))) (pivots (1+ n) :type fixnum)) (:simple-arrays (m)) ($ i (setf (pivots i) i)) ($ i ($ j (setf (a i j) (m i j)))) ($ i (let ((pivot (max-index row-search (a row-search i)))) (rotatef (pivots i) (pivots pivot)) ($ col-swap (rotatef (a pivot col-swap) (a i col-swap))) (let ((scale (/ (shiva-float 1.0) (a i i)))) ($ row-down (let ((row-value (a row-down i))) (setf (a row-down i) (* row-value scale)) ($ col-right (decf (a row-down col-right) (* scale row-value (a i col-right))))))))) (values a pivots))) (defun lr* (lr v pivots &aux (n (1- (array-dimension lr 0)))) (tensor ((i 0 n) (j i n) (k 0 (1- i))) ((tmp (1+ n)) (out (1+ n))) (:simple-arrays (lr v (pivots :type fixnum))) ($ i (setf (tmp i) (sum j (* (lr i j) (v j))))) ($ i (setf (out (pivots i)) (+ (tmp i) (sum k (* (lr i k) (tmp k)))))) out)) (defun lr-solve (lr b pivots &aux (n (1- (array-dimension lr 0)))) (tensor ((i 0 n) (ii n 0 :down t) (j (1+ ii) n) (k 0 (1- i))) ((tmp (1+ n))) (:simple-arrays (lr b (pivots :type fixnum))) ($ i (setf (tmp i) (b (pivots i)))) ($ i (decf (tmp i) (sum k (* (lr i k) (tmp k))))) ($ ii (decf (tmp ii) (sum j (* (lr ii j) (tmp j)))) (setf (tmp ii) (/ (tmp ii) (lr ii ii)))) tmp)) (defun lr-inverse (lr pivots &aux (n (1- (array-dimension lr 0)))) (tensor ((col 0 n) (ip 0 (1- pcol)) (i (1+ pcol) n) (ii n 0 :down t) (j (1+ ii) n) (k pcol (1- i))) ((ipivots (1+ n) :type fixnum) (tmp (1+ n)) (out (list (1+ n) (1+ n)))) (:simple-arrays (lr (pivots :type fixnum))) ($ col (setf (ipivots (pivots col)) col)) ($ col (let ((pcol (ipivots col))) ($ ip (setf (tmp ip) (shiva-float 0.0))) (setf (tmp pcol) (shiva-float 1.0)) ($ i (setf (tmp i) (- (sum k (* (lr i k) (tmp k))))))) ($ ii (decf (tmp ii) (sum j (* (lr ii j) (tmp j)))) (setf (tmp ii) (/ (tmp ii) (lr ii ii))) (setf (out ii col) (tmp ii)))) out)) (defun vf (out &rest elements) (declare (dynamic-extent elements)) (check-type out (simple-array shiva-float)) (let* ((n (list-length elements))) (assert (<= n (array-dimension out 0))) (iter (for i from 0) (declare (type fixnum i)) (for elt in elements) (setf (aref out i) (shiva-float elt))) out)) (defun v (&rest elements) "Create a vector of `SHIVA-FLOAT' and fill it with ELEMENTS." (declare (dynamic-extent elements)) (let* ((n (list-length elements)) (vector (make-array n :element-type 'shiva-float))) (iter (for i from 0) (declare (type fixnum i)) (for elt in elements) (setf (aref vector i) (shiva-float elt))) vector)) (defmacro vx (vector) `(aref ,vector 0)) (defmacro vy (vector) `(aref ,vector 1)) (defmacro vz (vector) `(aref ,vector 2)) (defmacro vw (vector) `(aref ,vector 3)) (defmacro define-swizzle (&rest components) "Define a swizzle operator for vector using given COMPONENTS. Inspired by GLSL swizzling." (flet ((comp->accessor (comp) (ecase comp ((x r) 'vx) ((y g) 'vy) ((z b) 'vz) ((w a) 'vw)))) (let ((accessors (mapcar #'comp->accessor components)) (op-name (apply #'symbolicate 'v components))) `(defun ,op-name (vector) (v ,@(mapcar (lambda (accessor) `(,accessor vector)) accessors)))))) (defmacro define-swizzles (&rest component-lists) "Generate swizzle operators using a Cartesian product of COMPONENT-LISTS." `(progn ,@(apply #'map-product (lambda (&rest components) `(define-swizzle ,@components)) component-lists))) (define-swizzles (x y) (x y)) (define-swizzles (x y z) (x y z) (x y z)) (define-swizzles (r g b) (r g b) (r g b)) (declaim (inline v3->v2)) (defun v3->v2 (v) "Convert VEC 3 to VEC 2 by dropping the y axis." (declare (type (vec 3) v)) (v (vx v) (vz v))) (defun v2->v3f (out v &optional (y #.(shiva-float 0.0))) (check-type out (vec 3)) (check-type v (vec 2)) (vf out (vx v) y (vy v))) (declaim (inline v2->v3)) (defun v2->v3 (v &optional (y (shiva-float 0.0))) "Convert VEC 2 to VEC 3 by adding the y axis, set to 0." (declare (type (vec 2) v)) (v (vx v) y (vy v))) (deftype mat (n &optional m) `(simple-array shiva-float (,n ,(if (null m) n m)))) (defun mat (&rest rows) "Construct a row major matrix as a 2D vector of `SHIVA-FLOAT' and fill it with ROWS." (declare (dynamic-extent rows)) (let* ((n (list-length rows)) (m (length (car rows))) (matrix (make-array (list n m) :element-type 'shiva-float))) (iter (for i from 0) (for row in rows) (iter (for j from 0) (for elt in row) (setf (aref matrix i j) (shiva-float elt)))) matrix)) (defun mat-row (matrix row-index) "Return a matrix row as a vector." (destructuring-bind (rows cols) (array-dimensions matrix) (declare (ignore rows)) (apply #'v (iter (for col-index below cols) (collect (aref matrix row-index col-index)))))) (defun mat-col (matrix col-index) "Return a matrix column as a vector." (destructuring-bind (rows cols) (array-dimensions matrix) (declare (ignore cols)) (apply #'v (iter (for row-index below rows) (collect (aref matrix row-index col-index)))))) (declaim (inline midentity4)) (defun midentity4 () "Construct a 4x4 identity matrix." (let ((out (make-array '(4 4) :element-type 'shiva-float ;; This doesn't look good if we get a pointer to double-float :initial-element (shiva-float 0.0)))) (setf (aref out 0 0) (shiva-float 1.0)) (setf (aref out 1 1) (shiva-float 1.0)) (setf (aref out 2 2) (shiva-float 1.0)) (setf (aref out 3 3) (shiva-float 1.0)) out)) (defmacro deftransform (row-index values col-index) "Iterate over first three rows and set given VALUES on given COL-INDEX." (with-gensyms (out) `(let ((,out (midentity4))) ,@(iter (for i below 3) (for val in values) (collect `(let ((,row-index ,i)) (setf (aref ,out ,row-index ,col-index) (shiva-float ,val))))) ,out))) (declaim (inline translation)) (defun translation (&key (x 0.0) (y 0.0) (z 0.0)) "Construct a translation matrix." (deftransform i (x y z) 3)) (declaim (inline scale)) (defun scale (&key (x 1.0) (y 1.0) (z 1.0)) "Construct a scale matrix." (deftransform i (x y z) i)) (defun ortho (left right bottom top near far) "Create orthographic projection from 6 clipping planes." (check-type left real) (check-type right real) (check-type bottom real) (check-type top real) (check-type near real) (check-type far real) (let ((rml (shiva-float (- right left))) (tmb (shiva-float (- top bottom))) ;; negate near and far, to switch OpenGL view direction. (nmf (shiva-float (- near far))) (rpl (shiva-float (+ right left))) (tpb (shiva-float (+ top bottom))) (fpn (shiva-float (+ far near)))) (declare (type shiva-float rml tmb nmf rpl tpb fpn)) (mat (list (/ 2.0 rml) 0.0 0.0 (- (/ rpl rml))) (list 0.0 (/ 2.0 tmb) 0.0 (- (/ tpb tmb))) (list 0.0 0.0 (/ 2.0 nmf) (/ fpn nmf)) (list 0.0 0.0 0.0 1.0)))) (defun perspective (fovy aspect near far) "Create a perspective projection with symmetric view frustum." (check-type fovy (real 0)) (check-type aspect (real 0)) (check-type near (real 0)) (check-type far (real 0)) (let* ((tan-half-fov (shiva-float (tan (* 0.5 fovy)))) (x (/ 1.0 (* (shiva-float aspect) tan-half-fov))) (y (/ 1.0 tan-half-fov)) (fmn (shiva-float (- far near))) (fpn (shiva-float (+ far near)))) (declare (type shiva-float tan-half-fov x y fmn fpn)) (mat (list x 0.0 0.0 0.0) (list 0.0 y 0.0 0.0) (list 0.0 0.0 (- (/ fpn fmn)) (/ (* -2.0 far near) fmn)) (list 0.0 0.0 -1.0 0.0)))) (declaim (inline double=)) (defun double= (a b &key (epsilon 1d-9) (rel-epsilon double-float-epsilon)) "Compare floating points using epsilon difference and fallback to relative epsilon. Doesn't handle infinities." (declare (type double-float a b epsilon rel-epsilon)) (let ((diff (abs (- a b))) (max (max (abs a) (abs b)))) (declare (type double-float diff max)) (or (<= diff epsilon) ;; Needed when near zero. (<= diff (* max rel-epsilon))))) (declaim (inline double>)) (defun double> (a b) (declare (type double-float a b)) (and (not (double= a b)) (> a b))) (declaim (inline double>=)) (defun double>= (a b) (declare (type double-float a b)) (or (double= a b) (> a b))) (declaim (inline double<)) (defun double< (a b) (declare (type double-float a b)) (and (not (double= a b)) (< a b))) (declaim (inline double<=)) (defun double<= (a b) (declare (type double-float a b)) (or (double= a b) (< a b))) (declaim (inline single=)) (defun single= (a b &key (epsilon 1s-5) (rel-epsilon single-float-epsilon)) "Compare floating points using epsilon difference and fallback to relative epsilon. Doesn't handle infinities." (declare (type single-float a b epsilon rel-epsilon)) (let ((diff (abs (- a b))) (max (max (abs a) (abs b)))) (declare (type single-float diff max)) (or (<= diff epsilon) ;; Needed when near zero. (<= diff (* max rel-epsilon))))) (declaim (inline single>)) (defun single> (a b) (declare (type single-float a b)) (and (not (single= a b)) (> a b))) (declaim (inline single>=)) (defun single>= (a b) (declare (type single-float a b)) (or (single= a b) (> a b))) (declaim (inline single<)) (defun single< (a b) (declare (type single-float a b)) (and (not (single= a b)) (< a b))) (declaim (inline single<=)) (defun single<= (a b) (declare (type single-float a b)) (or (single= a b) (< a b))) (declaim (inline float=)) (defun float= (a b) #+shiva-double-float(double= a b) #+shiva-single-float(single= a b) ) (declaim (inline float>)) (defun float> (a b) #+shiva-double-float(double> a b) #+shiva-single-float(single> a b) ) (declaim (inline float>=)) (defun float>= (a b) #+shiva-double-float(double>= a b) #+shiva-single-float(single>= a b) ) (declaim (inline float<)) (defun float< (a b) #+shiva-double-float(double< a b) #+shiva-single-float(single< a b) ) (declaim (inline float<=)) (defun float<= (a b) #+shiva-double-float(double<= a b) #+shiva-single-float(single<= a b)) (defun v= (v1 v2 &key (test #'float=)) "Perform a comparison of two vectors." (let ((n1 (array-dimension v1 0)) (n2 (array-dimension v2 0))) (when (= n1 n2) (iter (for i below n1) (always (funcall test (aref v1 i) (aref v2 i))))))) (defun vcross (v1 v2) "Get the cross product of two vectors." (tensor ((i 0 2)) ((out 3)) (:simple-arrays (v1 v2)) ($ i (let* ((j (mod (1+ i) 3)) (k (mod (1+ j) 3))) (setf (out i) (- (* (v1 j) (v2 k)) (* (v1 k) (v2 j)))))) out)) (deftype quat () `(cons (vec 3) shiva-float)) (defun q (x y z w) "Construct a quaternion as a cons of vector X Y Z and W." (cons (v x y z) (shiva-float w))) (defmacro qx (quaternion) `(vx (car ,quaternion))) (defmacro qy (quaternion) `(vy (car ,quaternion))) (defmacro qz (quaternion) `(vz (car ,quaternion))) (defmacro qw (quaternion) `(cdr ,quaternion)) (defun q+ (q1 q2) "Add two quaternions." (cons (v+ (car q1) (car q2)) (+ (cdr q1) (cdr q2)))) (defun q* (q1 q2) "Multiply two quaternions." (let ((v1 (car q1)) (w1 (cdr q1)) (v2 (car q2)) (w2 (cdr q2))) (cons (v+ (vcross v1 v2) (vscale w2 v1) (vscale w1 v2)) (- (* w1 w2) (vdot v1 v2))))) (defun qconj (q) "Conjugate a quaternion." (cons (vscale (shiva-float -1.0) (car q)) (cdr q))) (defun qrotation (axis rad-angle) "Construct a quaternion for rotation of RAD-ANGLE around AXIS vector." (let ((half-angle (* 0.5 (shiva-float rad-angle)))) (cons (vscale (sin half-angle) axis) (cos half-angle)))) (defun vrotate (quaternion vector) "Rotate a 3 component VECTOR by given QUATERNION." (declare (type quat quaternion) (type (vec 3) vector)) (vnormalize (car (q* (q* quaternion (q (vx vector) (vy vector) (vz vector) 0)) (qconj quaternion))))) (defun q->mat (quaternion) "Construct a rotation matrix from given unit QUATERNION." (let ((x (qx quaternion)) (y (qy quaternion)) (z (qz quaternion)) (w (qw quaternion))) (mat (list (- 1 (* 2 (+ (* y y) (* z z)))) (* 2 (- (* x y) (* w z))) (* 2 (+ (* x z) (* w y))) 0) (list (* 2 (+ (* x y) (* w z))) (- 1 (* 2 (+ (* x x) (* z z)))) (* 2 (- (* y z) (* w x))) 0) (list (* 2 (- (* x z) (* w y))) (* 2 (+ (* y z) (* w x))) (- 1 (* 2 (+ (* x x) (* y y)))) 0) (list 0 0 0 1)))) (defun rotation (axis rad-angle) "Construct a rotation matrix for RAD-ANGLE around AXIS vector." (q->mat (qrotation axis rad-angle))) (defun q->euler-x (quaternion) "Extract the euler angle about the x-axis (roll) from QUATERNION." (let ((qx (qx quaternion)) (qy (qy quaternion)) (qz (qz quaternion)) (qw (qw quaternion))) (atan (* 2.0 (+ (* qw qx) (* qy qz))) (- 1.0 (* 2.0 (+ (* qx qx) (* qy qy)))))))
21,071
Common Lisp
.lisp
511
36.542074
108
0.601855
Th30n/cl-shake
10
1
1
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
8cbef65b10509a993f08d726b0af44076789deccd0a12eea1a90249e44e52f8a
10,773
[ -1 ]
10,774
model.lisp
Th30n_cl-shake/shake/model.lisp
;;;; Loading and managing various 3D models (in-package #:shake.model) (defvar *world-model* nil "Currently loaded 3D model of the world (map)") (cffi:defcstruct (vertex-data :class c-vertex-data) (position :float :count 3) (color :float :count 3) (normal :float :count 3) (uv :float :count 2)) (defstruct surf-triangles "Stores surface triangles ready for rendering. VERTS is a foreign array of `C-VERTEX-DATA', ready for sending to GPU. TEX-NAME is the name of texture image used, can be NIL." (num-verts 0 :type fixnum :read-only t) (verts-byte-size 0 :type fixnum :read-only t) (verts nil :read-only t) ;; TODO: Texture should be wired differently (tex-name nil :type (or null string))) (declaim (inline make-l-vertex-data)) (defstruct l-vertex-data (position (v 0 0 0) :type (vec 3) :read-only t) (color (v 0 0 0) :type (vec 3) :read-only t) (normal (v 0 0 0) :type (vec 3) :read-only t) (uv (v 0 0) :type (vec 2) :read-only t)) (defmethod cffi:translate-from-foreign (ptr (type c-vertex-data)) (cffi:with-foreign-slots ((position color normal uv) ptr (:struct vertex-data)) (flet ((vec-from-foreign (ptr count) ;; NOTE: cffi:foreign-array-to-lisp cannot be used since we ;; convert C float array to Lisp double array. (apply #'v (loop for i from 0 below count collect (cffi:mem-aref ptr :float i))))) (make-l-vertex-data :position (vec-from-foreign position 3) :color (vec-from-foreign color 3) :normal (vec-from-foreign normal 3) :uv (vec-from-foreign uv 2))))) (defmethod cffi:expand-from-foreign (ptr (type c-vertex-data)) `(cffi:with-foreign-slots ((position color normal uv) ,ptr (:struct vertex-data)) (flet ((vec-from-foreign (ptr count) (apply #'v (loop for i from 0 below count collect (cffi:mem-aref ptr :float i))))) (make-l-vertex-data :position (vec-from-foreign position 3) :color (vec-from-foreign color 3) :normal (vec-from-foreign normal 3) :uv (vec-from-foreign uv 2))))) (defmethod cffi:translate-into-foreign-memory (vd (type c-vertex-data) ptr) (cffi:with-foreign-slots ((position color normal uv) ptr (:struct vertex-data)) (flet ((vec-to-foreign (v ptr) ;; NOTE: cffi:lisp-array-to-foreign cannot be used since we ;; convert Lisp double array to C float array. (loop for i fixnum from 0 below (array-total-size v) do (setf (cffi:mem-aref ptr :float i) (coerce (aref v i) 'single-float))))) (vec-to-foreign (l-vertex-data-position vd) position) (vec-to-foreign (l-vertex-data-color vd) color) (vec-to-foreign (l-vertex-data-normal vd) normal) (vec-to-foreign (l-vertex-data-uv vd) uv)))) (defmethod cffi:expand-into-foreign-memory (vd (type c-vertex-data) ptr) `(cffi:with-foreign-slots ((position color normal uv) ,ptr (:struct vertex-data)) (flet ((vec-to-foreign (v ptr) ;; NOTE: cffi:lisp-array-to-foreign cannot be used since we ;; convert Lisp double array to C float array. (loop for i fixnum from 0 below (array-total-size v) do (setf (cffi:mem-aref ptr :float i) (coerce (aref v i) 'single-float))))) (vec-to-foreign (l-vertex-data-position ,vd) position) (vec-to-foreign (l-vertex-data-color ,vd) color) (vec-to-foreign (l-vertex-data-normal ,vd) normal) (vec-to-foreign (l-vertex-data-uv ,vd) uv)))) (defun free-surf-triangles (surf-triangles) (when surf-triangles (cffi:foreign-free (surf-triangles-verts surf-triangles)))) (defstruct (surface (:include sbsp:sidedef)) "Extended SIDEDEF which contains 3D faces for rendering." (geometry nil :type (or null surf-triangles))) (defstruct (mleaf (:include sbsp:leaf)) "In memory, model leaf node of model BSP." floor-geometry ceiling-geometry) (declaim (inline make-bsp-model)) (defstruct bsp-model "A 3D model. The NODES slot contains bsp nodes for rendering. The HULL slot contains bsp nodes for collision detection. Remaining entities are stored in THINGS slot." (nodes nil :type (or mleaf sbsp:node) :read-only t) hull things) (declaim (inline make-obj-model)) (defstruct obj-model "A 3D model obtained from Wavefront OBJ file." (verts nil :type surf-triangles) (min-bounds (v 0 0 0) :type (vec 3)) (max-bounds (v 0 0 0) :type (vec 3))) (declaim (ftype (function (sbsp::sidedef) (values shiva-float shiva-float)) sidedef-uv)) (defun sidedef-uv (sidedef) ;; NOTE: This function doesn't cons, so keep it as such. (let ((texinfo (sbsp:sidedef-texinfo sidedef))) (if (or (null texinfo) (eq :caulk texinfo)) (values #.(shiva-float 0) #.(shiva-float 1)) (ecase (sbsp:texinfo-draw-mode texinfo) (:tile (with-struct (lineseg- start end orig-line) (sbsp:sidedef-lineseg sidedef) ;; Winding is clockwise (right to left), so reverse the ;; texture. (values (vdist start (linedef-end orig-line)) (vdist end (linedef-end orig-line))))) (:scale-to-fit (with-struct (lineseg- t-start t-end) (sbsp:sidedef-lineseg sidedef) ;; Reverse the coordinates, due to vertex winding. (values (- #.(shiva-float 1) t-start) (- #.(shiva-float 1) t-end)))))))) (defun fill-vertex-data (ptr offset &key start end bot top normal color u-start u-end rotatedp) (declare (type fixnum offset) (type (vec 2) start) (type (vec 2) end) (type (vec 3) normal) (type (vec 3) color) (type shiva-float u-start) (type shiva-float u-end) (type boolean rotatedp)) (flet ((set-data (index pos u v) (let* ((uv (make-array 2 :element-type 'shiva-float)) (data (make-l-vertex-data :position pos :normal (vscale (if rotatedp #.(shiva-float -1) #.(shiva-float 1)) normal) :uv uv :color color))) (declare (dynamic-extent uv data)) (vf uv u v) ;; NOTE: This conses for some reason (setf (cffi:mem-aref ptr '(:struct vertex-data) (+ offset index)) data)))) (let ((start-3d-bot (make-array 3 :element-type 'shiva-float)) (end-3d-bot (make-array 3 :element-type 'shiva-float)) (start-3d-top (make-array 3 :element-type 'shiva-float)) (end-3d-top (make-array 3 :element-type 'shiva-float))) (declare (dynamic-extent start-3d-bot end-3d-bot start-3d-top end-3d-top)) (v2->v3f start-3d-bot start bot) (v2->v3f end-3d-bot end bot) (v2->v3f start-3d-top start top) (v2->v3f end-3d-top end top) (set-data (if rotatedp 1 0) start-3d-top u-start 0) (set-data (if rotatedp 0 1) end-3d-top u-end 0) (set-data 2 start-3d-bot u-start 1) (set-data (if rotatedp 4 3) start-3d-bot u-start 1) (set-data (if rotatedp 3 4) end-3d-top u-end 0) (set-data 5 end-3d-bot u-end 1)))) (defun sidedef->surf-triangles (sidedef) (assert (sbsp:sidedef-back-sector sidedef)) (let* ((front-sector (sbsp:sidedef-front-sector sidedef)) (back-sector (sbsp:sidedef-back-sector sidedef)) (floor-bottom (aif front-sector (sbsp:sector-floor-height it) #.(shiva-float 0))) (floor-top (sbsp:sector-floor-height back-sector)) (ceiling-top (aif front-sector (sbsp:sector-ceiling-height it) #.(shiva-float 1))) (ceiling-bottom (sbsp:sector-ceiling-height back-sector)) ;; Don't generate floor or ceiling part if its superseded by the front sector. (gen-floor-p (not (and front-sector (float< (shiva-float floor-top) (shiva-float floor-bottom))))) (gen-ceiling-p (not (and front-sector (float< (shiva-float ceiling-top) (shiva-float ceiling-bottom))))) (num-verts (cond ((and gen-floor-p gen-ceiling-p) 12) ((or gen-floor-p gen-ceiling-p) 6) (t 0)))) (unless (zerop num-verts) (let ((tex-name (aif (sbsp:sidedef-texinfo sidedef) (string-downcase (sbsp:texinfo-name it)))) (ptr (cffi:foreign-alloc '(:struct vertex-data) :count num-verts)) (start (lineseg-start (sbsp:sidedef-lineseg sidedef))) (end (lineseg-end (sbsp:sidedef-lineseg sidedef))) (floor-rotated-p nil) (ceiling-rotated-p nil)) (when (float< (shiva-float floor-top) (shiva-float floor-bottom)) (setf floor-rotated-p t) (rotatef floor-bottom floor-top)) (when (float< (shiva-float ceiling-top) (shiva-float ceiling-bottom)) (setf ceiling-rotated-p t) (rotatef ceiling-bottom ceiling-top)) (multiple-value-bind (u-start u-end) (sidedef-uv sidedef) (when gen-floor-p (fill-vertex-data ptr 0 :start start :end end :bot floor-bottom :top floor-top :normal (v2->v3 (sbsp:lineseg-normal (sbsp:sidedef-lineseg sidedef))) :color (sbsp:sidedef-color sidedef) :u-start u-start :u-end u-end :rotatedp floor-rotated-p)) (when gen-ceiling-p (fill-vertex-data ptr (if gen-floor-p 6 0) :start start :end end :bot ceiling-bottom :top ceiling-top :normal (v2->v3 (sbsp:lineseg-normal (sbsp:sidedef-lineseg sidedef))) :color (sbsp:sidedef-color sidedef) :u-start u-start :u-end u-end :rotatedp ceiling-rotated-p))) (make-surf-triangles :num-verts num-verts :verts-byte-size (* num-verts (cffi:foreign-type-size '(:struct vertex-data))) :verts ptr :tex-name tex-name))))) (defun polygon->surf-triangles (polygon height &key (color (v 1 0 0)) reverse-p) (let* ((triangles (sbsp:triangulate (mapcar #'sbsp:linedef->lineseg polygon))) (positions (mapcar #'sbsp:lineseg-start (apply #'append triangles))) (num-verts (list-length positions)) (verts (cffi:foreign-alloc '(:struct vertex-data) :count num-verts))) (loop for pos in (if reverse-p (reverse positions) positions) and i from 0 do (setf (cffi:mem-aref verts '(:struct vertex-data) i) (make-l-vertex-data :position (v2->v3 pos height) :color color :normal (v 0 1 0) :uv (v 0 0)))) (make-surf-triangles :num-verts num-verts :verts-byte-size (* num-verts (cffi:foreign-type-size '(:struct vertex-data))) :verts verts))) (defun obj->model (obj) (declare (type sobj:obj obj)) ;; This assumes that object only consists of triangles. (let* ((num-verts (* 3 (length (sobj:obj-element-data obj)))) (verts (cffi:foreign-alloc '(:struct vertex-data) :count num-verts)) (min-bounds nil) (max-bounds nil)) (loop for face across (sobj:obj-element-data obj) with i = 0 do (loop for point across (sobj:element-points face) for position = (sobj:vertex-val (aref (sobj:obj-geometric-vertices obj) (sobj:vref-geometric point))) for normal = (sobj:vertex-val (aref (sobj:obj-normal-vertices obj) (sobj:vref-normal point))) for uv = (sobj:vertex-val (aref (sobj:obj-texture-vertices obj) (sobj:vref-texture point))) do (progn (unless (and min-bounds max-bounds) (setf min-bounds (vxyz position)) (setf max-bounds (vxyz position))) (dotimes (i 3) (when (< (aref position i) (aref min-bounds i)) (setf (aref min-bounds i) (aref position i))) (when (> (aref position i) (aref max-bounds i)) (setf (aref max-bounds i) (aref position i)))) (setf (cffi:mem-aref verts '(:struct vertex-data) i) (make-l-vertex-data :position (vxyz position) :color (v 1 1 1) :normal (vxyz normal) :uv (vxy uv))) (incf i)))) (assert (and min-bounds max-bounds)) (make-obj-model :min-bounds min-bounds :max-bounds max-bounds :verts (make-surf-triangles :num-verts num-verts :verts-byte-size (* num-verts (cffi:foreign-type-size '(:struct vertex-data))) :verts verts)))) (defun sidedef->surface (sidedef) (make-surface :lineseg (sbsp:sidedef-lineseg sidedef) :front-sector (sbsp:sidedef-front-sector sidedef) :color (sbsp:sidedef-color sidedef) :texinfo (sbsp:sidedef-texinfo sidedef) :geometry (sidedef->surf-triangles sidedef))) (defun dbg-sector-color () (v (/ (+ 15 (random 200)) 256d0) (/ (+ 15 (random 240)) 256d0) (/ (+ 15 (random 240)) 256d0))) (defun leaf->mleaf (leaf) (let* ((subsector (sbsp::leaf-subsector leaf)) (sector (sbsp::subsector-orig-sector subsector)) (floor-height (if sector (sbsp:sector-floor-height sector) 0)) (ceiling-height (if sector (sbsp:sector-ceiling-height sector) 1))) (assert (sbsp:leaf-contents leaf)) (make-mleaf :bounds (sbsp:leaf-bounds leaf) :surfaces (sbsp:leaf-surfaces leaf) :contents (sbsp:leaf-contents leaf) :subsector (sbsp::leaf-subsector leaf) :floor-geometry (when-let ((lines (sbsp::subsector-lines subsector))) (polygon->surf-triangles lines floor-height :reverse-p t :color (if (eq :contents-solid (sbsp:leaf-contents leaf)) (v 1d0 0d0 0d0) (dbg-sector-color)))) :ceiling-geometry (when-let ((lines (sbsp::subsector-lines subsector))) (polygon->surf-triangles lines ceiling-height :color (v 0.1 0.1 0.1)))))) (defun nadapt-nodes (bsp) (sbsp:bsp-rec bsp (lambda (node front back) (setf (sbsp:node-front node) (funcall front) (sbsp:node-back node) (funcall back)) node) (lambda (leaf) (zap (curry #'mapcar #'sidedef->surface) (sbsp:leaf-surfaces leaf)) (leaf->mleaf leaf)))) (defun bspfile->model (bspfile) (make-bsp-model :hull (sbsp:bspfile-clip-nodes bspfile) :nodes (nadapt-nodes (sbsp:bspfile-nodes bspfile)) :things (sbsp:bspfile-things bspfile))) (defun load-model (model-fname) "Try to load a 3D model from MODEL-FNAME. In case of error, print the error and return the default model." (handler-case (with-data-file (file model-fname) (let ((ext (pathname-type model-fname))) (cond ((string= "obj" ext) (obj->model (sobj:read-obj file))) ((string= "bsp" ext) (bspfile->model (sbsp:read-bspfile file))) (t (shake:print-error "unknown model format ~S" model-fname) (make-default-model))))) (sdata:data-file-error (c) (shake:print-error "~A~%" c) (make-default-model)))) (defun free-model (model) (declare (type (or obj-model bsp-model) model)) (etypecase model (obj-model (free-surf-triangles (obj-model-verts model))) (bsp-model (with-struct (bsp-model- nodes) model (sbsp:bsp-trav nodes (constantly nil) (lambda (leaf) (with-struct (mleaf- surfaces floor-geometry ceiling-geometry) leaf (when floor-geometry (free-surf-triangles floor-geometry)) (when ceiling-geometry (free-surf-triangles ceiling-geometry)) (dolist (surf surfaces) (free-surf-triangles (surface-geometry surf)))))))))) (defun reload-model (model model-fname) "Try to reload a MODEL from MODEL-FNAME. In case of error, print the error and return leave MODEL unchanged." (check-type model obj-model) (check-type model-fname string) (shake:printf "Reloading model '~A'~%" model-fname) (handler-case (with-data-file (file model-fname) (let ((ext (pathname-type model-fname))) (cond ((string= "obj" ext) (let ((new-model (obj->model (sobj:read-obj file)))) (free-model model) (setf (surf-triangles-tex-name (obj-model-verts new-model)) (surf-triangles-tex-name (obj-model-verts model))) (setf (obj-model-verts model) (obj-model-verts new-model)) (setf (obj-model-min-bounds model) (obj-model-min-bounds new-model)) (setf (obj-model-max-bounds model) (obj-model-max-bounds new-model)))) (t (shake:print-error "unknown model format ~S" model-fname)))) (shake:printf "Reloaded model '~A'~%" model-fname)) (sdata:data-file-error (c) (shake:print-error "~A~%" c)))) (declaim (inline make-model-manager)) (defstruct model-manager "All model loading and unloading should go through this." (world-model nil :type (or null bsp-model)) (models (make-hash-table :test #'equal) :type hash-table) ;; Default model is the cube (default-model nil :type obj-model :read-only t)) (defun make-default-model () "Return the default cube model, size is 2 (-1, 1)." (let ((model (with-input-from-string (s sobj::+cube+) (obj->model (sobj:read-obj s))))) (setf (surf-triangles-tex-name (obj-model-verts model)) "missing.bmp") model)) (defun init-model-manager () (make-model-manager :default-model (make-default-model))) (defun shutdown-model-manager (model-manager) (declare (type model-manager model-manager)) (maphash-values #'free-model (model-manager-models model-manager)) (free-model (model-manager-default-model model-manager))) (defmacro with-model-manager (model-manager &body body) `(bracket (,model-manager (init-model-manager) shutdown-model-manager) ,@body)) (defun add-model (model-manager model &key name) (declare (type model-manager model-manager) (type (or bsp-model obj-model)) (type string name)) (setf (gethash name (model-manager-models model-manager)) model)) (defun get-model (model-manager name) (check-type model-manager model-manager) (check-type name string) (or (gethash name (model-manager-models model-manager)) (add-model model-manager (load-model name) :name name))) (defun model-manager-reload-models (model-manager) (check-type model-manager model-manager) (maphash (lambda (model-fname model) (when (obj-model-p model) (reload-model model model-fname))) (model-manager-models model-manager)))
20,380
Common Lisp
.lisp
407
37.749386
91
0.571622
Th30n/cl-shake
10
1
1
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
00d37c7b6be798134276fcf2bc55af057325f2e4a4e66125a8b60d204ea3b661
10,774
[ -1 ]
10,775
package.lisp
Th30n_cl-shake/shake/package.lisp
;;;; Copyright (C) 2017 Teon Banek ;;;; ;;;; This program is free software; you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation; either version 2 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License along ;;;; with this program; if not, write to the Free Software Foundation, Inc., ;;;; 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. (in-package #:cl-user) (defpackage #:shake.debug (:use #:cl #:alexandria #:shake-utils) (:export #:timer #:timer-name #:timer-max #:timer-avg #:make-timer #:with-timer)) (defpackage #:shake.data (:nicknames #:sdata) (:use #:cl #:alexandria #:shake-utils) (:export #:data-path #:data-file-error #:exe-dir #:with-data-dirs #:with-data-file ;; resource management #:with-resources #:add-res #:res #:res-let #:free-res #:free-resources)) (defpackage #:shake.obj (:nicknames #:sobj) (:use #:cl #:shiva) (:export #:read-obj #:obj #:obj-geometric-vertices #:obj-normal-vertices #:obj-texture-vertices #:obj-element-data #:element-points #:vref-geometric #:vref-normal #:vref-texture #:vertex-val)) (defpackage #:shake.fbx (:nicknames #:sfbx) (:use #:cl #:shiva)) (defpackage #:shake.model (:nicknames #:smdl) (:use #:cl #:alexandria #:shiva #:shake-utils #:shake.data) (:export #:*world-model* #:bsp-model #:bsp-model-nodes #:bsp-model-hull #:bsp-model-things #:mleaf-floor-geometry #:mleaf-ceiling-geometry #:surface #:surface-geometry #:with-model-manager #:model-manager-default-model #:model-manager-reload-models #:get-model) (:import-from #:sbsp #:lineseg-start #:lineseg-end #:lineseg-orig-line #:lineseg-t-start #:lineseg-t-end #:linedef-end)) (defpackage #:shake.render (:nicknames #:srend) (:use #:cl #:alexandria #:shiva #:shake-utils #:shake.debug) (:export #:draw-gui-text #:draw-gui-quad #:draw-text #:load-map-images #:list-modes #:gl-config #:print-gl-info #:print-memory-usage #:render-surface #:render-system #:render-system-gl-config #:render-system-prog-manager #:render-system-rend-height #:render-system-rend-width #:with-render-system #:with-draw-frame ;; These are just command symbols #:*fullscreen* #:*v-sync* #:*vid-mode* #:*win-width* #:*win-height* #:vid-restart)) (defpackage #:shake (:use #:cl #:alexandria #:shiva #:shake-gl #:shake-utils #:shake.data #:shake.debug) (:export #:main #:clip-hull #:hull-point-contents ;; mtrace #:mtrace #:mtrace-endpos #:mtrace-fraction #:mtrace-normal #:mtrace-start-solid-p ;; console and commands ;; TODO: These should be defined in another file, perhaps another ;; package #:add-command #:add-variable #:command-progn #:print-error #:print-warning #:printf))
4,001
Common Lisp
.lisp
126
22.84127
76
0.550556
Th30n/cl-shake
10
1
1
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
36eb160e6926580aacc0869fd8c279d25c3b3fb5ff9e19dcbfec52d2b3542440
10,775
[ -1 ]
10,776
data-test.lisp
Th30n_cl-shake/shake/data-test.lisp
;;;; Copyright (C) 2016 Teon Banek ;;;; ;;;; This program is free software; you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation; either version 2 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License along ;;;; with this program; if not, write to the Free Software Foundation, Inc., ;;;; 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. (in-package #:cl-user) (defpackage #:shake.data-test (:use #:cl #:prove #:sdata)) (in-package #:shake.data-test) (plan nil) (subtest "Test basic resource management" (let ((freep t) (test-res 42)) (flet ((load-fun () (setf freep nil) test-res) (free-fun (res) (declare (ignore res)) (setf freep t))) (with-resources "basic" (add-res "res1" #'load-fun #'free-fun) (is (res "res1") test-res) (ok (not freep)) (free-res "res1") (ok freep) (is (res "res1") test-res) (ok (not freep))) (ok freep)))) (subtest "Test double free" (let ((free-count 0)) (flet ((free-fun (res) (declare (ignore res)) (incf free-count))) (with-resources "double-free" (add-res "res" (lambda ()) #'free-fun) (is free-count 0) (free-res "res") (is free-count 1) (free-res "res") (free-res "res") (is free-count 1)) (is free-count 1)))) (subtest "Test scopes" (let ((first-free 0) (second-free 0)) (with-resources "first" (add-res "res" (constantly 'first) (lambda (res) (declare (ignore res)) (incf first-free))) (with-resources "second" (add-res "res" (constantly 'second) (lambda (res) (declare (ignore res)) (incf second-free))) (is (res "res") 'second) (is (res "res" :scope "second") 'second) (is (res "res" :scope "first") 'first) (free-res "res") (free-res "res") (is second-free 1) (is first-free 0) (is (res "res") 'second) (free-res "res" :scope "first") (is first-free 1) (is (res "res" :scope "first") 'first)) (is second-free 2) (is first-free 1) (is (res "res") 'first)) (is first-free 2))) (finalize)
2,817
Common Lisp
.lisp
81
27.024691
76
0.558284
Th30n/cl-shake
10
1
1
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
238521171766c6b916d69dcddc4220e03630696a394db216d454f54fa81e616d
10,776
[ -1 ]
10,777
obj.lisp
Th30n_cl-shake/shake/obj.lisp
;;;; Loading Wavefront OBJ 3D model files (in-package #:shake.obj) (alexandria:define-constant +cube+ " # Bottom vertices v 1 -1 -1 v 1 -1 1 v -1 -1 1 v -1 -1 -1 # Top vertices v 1 1 -1 v 1 1 1 v -1 1 1 v -1 1 -1 vn 0 -1 0 vn 0 1 0 vn 1 -0 0 vn 0 -0 1 vn -1 -0 -0 vn 0 0 -1 vt 0 0 vt 1 0 vt 1 1 vt 0 1 # Front face (+Z towards camera) f 6/2/4 3/4/4 2/3/4 f 6/2/4 7/1/4 3/4/4 # Back face f 1/3/6 8/1/6 5/4/6 f 1/3/6 4/2/6 8/1/6 # Top face (+Y) f 8/2/2 6/4/2 5/3/2 f 8/2/2 7/1/2 6/4/2 # Bottom face f 2/2/1 4/4/1 1/3/1 f 2/2/1 3/1/1 4/4/1 # Right face (+X) f 5/3/3 2/1/3 1/4/3 f 5/3/3 6/2/3 2/1/3 # Left face f 3/1/5 8/3/5 4/2/5 f 3/1/5 7/4/5 8/3/5 " :test #'string= :documentation "OBJ string defining a cube, counter clockwise.") (declaim (inline make-token)) (defstruct token (type :unknown :read-only t :type (member :eof :word :number :comment :slash :unknown)) (string "" :type string :read-only t) (leading-whitespace "" :type string :read-only t) (number 0 :type (or shiva-float fixnum) :read-only t)) (declaim (inline make-token-error)) (defstruct token-error (string "" :type string :read-only t) (message "" :type string :read-only t)) (declaim (inline make-tokenizer)) (defstruct tokenizer (stream nil :type stream :read-only t) (next-token nil :type (or null token token-error))) (declaim (inline whitespace-char-p)) (defun whitespace-char-p (c) (when (member c '(#\Tab #\Newline #\Linefeed #\Page #\Return #\Space) :test #'char=) c)) (declaim (inline word-char-p)) (defun word-char-p (c) (when (or (alphanumericp c) (member c '(#\_ #\.) :test #'char=)) c)) (defun read-number (stream &optional (leading-whitespace "")) (flet ((make-number (sign significand exponent) (if (= exponent 0) (let ((int (* sign significand))) (if (<= most-negative-fixnum int most-positive-fixnum) (coerce int 'fixnum) (error "Integer '~S' doesn't fit in fixnum" int))) (shiva-float (* sign significand (expt 10 exponent)))))) (do ((c (read-char stream nil :eof) (read-char stream nil :eof)) (string (make-array 0 :element-type 'character :adjustable t :fill-pointer 0)) (first-char-p t nil) (floating-point-p nil) (sign 1) (significand 0) (exponent 0)) ((eq c :eof) (make-token :type (if first-char-p :eof :number) :number (make-number sign significand exponent) :string string :leading-whitespace leading-whitespace)) (declare (type (integer 0) significand) (type (integer * 0) exponent)) (cond ((and first-char-p (char= c #\-)) (setf sign -1)) ((let ((digit (digit-char-p c))) (when digit (when floating-point-p (incf exponent -1)) (setf significand (+ (* 10 significand) digit))))) ((char= c #\.) (if floating-point-p (return (make-token-error :string (format nil "~A~A" string c) :message "unexpected floating point")) (setf floating-point-p t))) ((or (char= c #\/) (whitespace-char-p c)) (unread-char c stream) (return (make-token :type :number :number (make-number sign significand exponent) :string string :leading-whitespace leading-whitespace))) (t (return (make-token-error :string (format nil "~A~A" string c) :message (format nil "unexpected character ~S" c))))) (vector-push-extend c string)))) (defun read-word (stream &optional (leading-whitespace "")) (do ((c (read-char stream nil :eof) (read-char stream nil :eof)) (string (make-array 0 :element-type 'character :adjustable t :fill-pointer 0))) ((eq c :eof) (make-token :type :word :string string :leading-whitespace leading-whitespace)) (cond ((word-char-p c) (vector-push-extend c string)) ((whitespace-char-p c) (unread-char c stream) (return (make-token :type :word :string string :leading-whitespace leading-whitespace))) (t (return (make-token-error :string (format nil "~A~A" string c) :message (format nil "unexpected word character ~S" c))))))) (defun read-comment (stream &optional (leading-whitespace "")) (do ((c (read-char stream nil :eof) (read-char stream nil :eof)) (string (make-array 0 :element-type 'character :adjustable t :fill-pointer 0))) ((or (eq c :eof) (member c '(#\Newline #\Linefeed #\Return) :test #'char=)) (make-token :type :comment :string string :leading-whitespace leading-whitespace)) (vector-push-extend c string))) (defun read-token (tokenizer) (let ((token (tokenizer-next-token tokenizer))) (when token (setf (tokenizer-next-token tokenizer) nil) (return-from read-token token))) (let ((stream (tokenizer-stream tokenizer))) (do ((c (read-char stream nil :eof) (read-char stream nil :eof)) (leading-whitespace (make-array 0 :element-type 'character :adjustable t :fill-pointer 0))) ((eq c :eof) (make-token :type :eof :leading-whitespace leading-whitespace)) (when (char= c #\\) (setf c (read-char stream nil :eof)) (when (eq c :eof) (return (make-token :type :eof :leading-whitespace leading-whitespace)))) (cond ((or (digit-char-p c) (char= c #\-)) (unread-char c stream) (return (read-number stream leading-whitespace))) ((word-char-p c) (unread-char c stream) (return (read-word stream leading-whitespace))) ((char= c #\#) ;; Don't unread, since `read-comment' does no checking and simply reads ;; the whole line. (return (read-comment stream leading-whitespace))) ((char= c #\/) (return (make-token :type :slash :string "/" :leading-whitespace leading-whitespace))) ((whitespace-char-p c) (vector-push-extend c leading-whitespace)) (t (return (make-token-error :string (string c) :message (format nil "unexpected character ~S" c)))))))) (declaim (inline peek-token)) (defun peek-token (tokenizer) (setf (tokenizer-next-token tokenizer) (read-token tokenizer))) ;;; Vertex Data ;; geometric vertex -- v x y z (w 1.0, required for rational curve and surface) ;; texture vertex -- vt u (v 0.0) (w 0.0) ;; vertex normal -- vn x y z ;;; Element Data ;; Each element indexes into vertex data, indexing starts from 1. Negative ;; index means immediately before the element in the file. ;; points -- p v1 (...) ;; lines -- l v1(/vt1) *2 (...) ;; faces -- f v1(/(vt1)(/vn1)) *3 (...) ;;; Grouping ;; Each grouping statement sets the state until the next one. Elements may ;; belong to multiple groups if multiple names are specified in the grouping ;; statement. ;; group name -- g name (...), default is the default group ;; object name -- o name, optional statement (may be skipped) (declaim (inline make-vertex)) (defstruct vertex (type :geometric :read-only t :type (member :geometric :texture :normal)) (val nil :type (vec 4) :read-only t)) (declaim (inline make-vref)) (defstruct vref "Reference to vertex data. Indexes are normalized to (0, vertex-data-size - 1)." (geometric nil :type fixnum :read-only t) (texture nil :type (or null fixnum) :read-only t) (normal nil :type (or null fixnum) :read-only t)) (declaim (inline make-element)) (defstruct element (type nil :read-only t :type (member :point :line :face)) (points nil :type (simple-array vref (*)) :read-only t)) (declaim (inline make-obj)) (defstruct obj (geometric-vertices (make-array 0 :element-type 'vertex :adjustable t :fill-pointer 0) :type (vector vertex) :read-only t) (texture-vertices (make-array 0 :element-type 'vertex :adjustable t :fill-pointer 0) :type (vector vertex) :read-only t) (normal-vertices (make-array 0 :element-type 'vertex :adjustable t :fill-pointer 0) :type (vector vertex) :read-only t) (element-data (make-array 0 :element-type 'element :adjustable t :fill-pointer 0) :type (vector element) :read-only t)) (defun read-geometric-vertex (tokenizer) (flet ((expect-number () (let ((token (read-token tokenizer))) (when (or (token-error-p token) (not (eq (token-type token) :number))) (error "Expected number, got ~S" token)) (token-number token))) (maybe-number (default-value) (let ((token (peek-token tokenizer))) (if (and (token-p token) (eq (token-type token) :number)) (token-number (read-token tokenizer)) default-value)))) (make-vertex :type :geometric :val (v (expect-number) (expect-number) (expect-number) (maybe-number 1.0))))) (defun read-texture-vertex (tokenizer) (flet ((expect-number () (let ((token (read-token tokenizer))) (when (or (token-error-p token) (not (eq (token-type token) :number))) (error "Expected number, got ~S" token)) (token-number token))) (maybe-number (default-value) (let ((token (peek-token tokenizer))) (if (and (token-p token) (eq (token-type token) :number)) (token-number (read-token tokenizer)) default-value)))) (make-vertex :type :texture :val (v (expect-number) (maybe-number 0.0) (maybe-number 0.0) 0.0)))) (defun read-normal-vertex (tokenizer) (flet ((expect-number () (let ((token (read-token tokenizer))) (when (or (token-error-p token) (not (eq (token-type token) :number))) (error "Expected number, got ~S" token)) (token-number token)))) (make-vertex :type :normal :val (v (expect-number) (expect-number) (expect-number) 0.0)))) (defun read-faces (tokenizer obj) (labels ((expect-fixnum () (let ((token (read-token tokenizer))) (if (and (token-p token) (eq (token-type token) :number) (typep (token-number token) 'fixnum)) (token-number token) (error "Expected fixnum, got ~S" token)))) (normalize-index (index size) (declare (type (or null fixnum) index)) (when index (if (minusp index) (setf index (+ size index)) ;; Use indexing starting from 0. (incf index -1)) (if (<= 0 index (1- size)) index (error "Index '~S' is out of bounds for size '~S'" index size)))) (read-point () (let ((geometric-ref (expect-fixnum)) (texture-ref nil) (normal-ref nil)) (when (and (not (token-error-p (peek-token tokenizer))) (eq (token-type (peek-token tokenizer)) :slash)) (when (< 0 (length (token-leading-whitespace (read-token tokenizer)))) (error "There shouldn't be any whitespace before '/'")) (cond ((token-error-p (peek-token tokenizer)) (error "Expected '/' or an integer, got ~S" (read-token tokenizer))) ;; Maybe read texture ((eq (token-type (peek-token tokenizer)) :number) (setf texture-ref (expect-fixnum)) ;; Maybe read a normal after texture (when (eq (token-type (peek-token tokenizer)) :slash) (read-token tokenizer) ;; skip slash (setf normal-ref (expect-fixnum)))) ;; Missing texture, but maybe read normal ((eq (token-type (peek-token tokenizer)) :slash) (read-token tokenizer) ;; skip slash (setf normal-ref (expect-fixnum))) (t (error "Expected '/' or an integer, got ~S" (read-token tokenizer))))) (make-vref :geometric (normalize-index geometric-ref (length (obj-geometric-vertices obj))) :texture (normalize-index texture-ref (length (obj-texture-vertices obj))) :normal (normalize-index normal-ref (length (obj-normal-vertices obj))))))) (let ((points (loop while (and (token-p (peek-token tokenizer)) (eq (token-type (peek-token tokenizer)) :number)) collect (read-point)))) ;; TODO: Check that points have uniform references to texture or normals (vector-push-extend (make-element :type :face :points (apply #'vector points)) (obj-element-data obj))))) (defun read-obj (stream) (let ((tokenizer (make-tokenizer :stream stream)) (obj (make-obj))) (do ((token (read-token tokenizer) (read-token tokenizer))) ((and (token-p token) (eq (token-type token) :eof)) obj) (when (token-error-p token) (return token)) (case (token-type token) (:comment nil) (:word (cond ((string= "v" (token-string token)) (vector-push-extend (read-geometric-vertex tokenizer) (obj-geometric-vertices obj))) ((string= "vt" (token-string token)) (vector-push-extend (read-texture-vertex tokenizer) (obj-texture-vertices obj))) ((string= "vn" (token-string token)) (vector-push-extend (read-normal-vertex tokenizer) (obj-normal-vertices obj))) ((string= "f" (token-string token)) (read-faces tokenizer obj)) (t nil ;; (shake:printf "Ignoring ~S~%" token) ))) (otherwise (error "Unexpected token ~S" token))))))
14,243
Common Lisp
.lisp
316
35.53481
106
0.577546
Th30n/cl-shake
10
1
1
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
a45fb9f60b7853c4824f00513228cf05b54955aec2b6669be166b7cd0e18a3b4
10,777
[ -1 ]
10,778
debug.lisp
Th30n_cl-shake/shake/debug.lisp
;;;; Contains various utilities for debugging and profiling. (in-package #:shake.debug) (defstruct timer (name "<null>" :type string :read-only t) (count 0 :type fixnum) (total 0.0 :type single-float) (new-max 0.0 :type single-float) (max 0.0 :type single-float) (avg 0.0 :type single-float)) (defun nupdate-timer (timer dt) (declare (optimize (speed 3) (space 3))) (declare (type timer timer)) (declare (type single-float dt)) (incf (timer-count timer)) (incf (timer-total timer) dt) (zap #'max (timer-new-max timer) dt) timer) (defun nreset-timer (timer) "Reset the maximum and average calculations of a TIMER." (declare (optimize (speed 3) (space 3))) (declare (type timer timer)) (with-struct (timer- total count new-max) timer (setf (timer-avg timer) (/ total count) (timer-max timer) new-max (timer-count timer) 0 (timer-total timer) 0.0 (timer-new-max timer) 0.0)) timer) (defun performance-delta (start stop) "Return the delta in seconds between two performance counters." (declare (optimize (speed 3))) (declare (type (unsigned-byte 64) start)) (declare (type (unsigned-byte 64) stop)) (/ (coerce (the (unsigned-byte 64) (- stop start)) 'single-float) (coerce (the (unsigned-byte 64) (sdl2:get-performance-frequency)) 'single-float))) (defun call-with-timer (timer function &key (reset-every 60)) "Upate the TIMER with the execution time of FUNCTION. If the TIMER-COUNT exceeds RESET-EVERY call counts, TIMER is reset." (declare (optimize (speed 3))) (check-type timer timer) (check-type reset-every fixnum) (check-type function function) (let ((start (sdl2:get-performance-counter))) (declare (type (unsigned-byte 64) start)) (multiple-value-prog1 (funcall function) (let ((end (sdl2:get-performance-counter))) (declare (type (unsigned-byte 64) end)) ;; Sometimes END is set to a lower value than START, in such a case ;; ignore the update. This usually happens if the performance counter ;; overflowed, but it seems rather unlikely to happen as often as it ;; does. (when (> end start) (nupdate-timer timer (performance-delta start end))) (when (>= (timer-count timer) reset-every) (nreset-timer timer)))))) (defmacro with-timer ((timer &key (reset-every 60)) &body body) `(call-with-timer ,timer (lambda () ,@body) :reset-every ,reset-every))
2,476
Common Lisp
.lisp
58
37.87931
77
0.677727
Th30n/cl-shake
10
1
1
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
435479e1bba606e6c05e6384e4c162f90a9a96c2e21aef9d0fd276f0a7515b49
10,778
[ -1 ]
10,779
image.lisp
Th30n_cl-shake/shake/image.lisp
;;;; Defines `image-manager' which is responsible for taking care of images ;;;; used for rendering. (in-package #:shake.render) (defstruct image-opts (width 0 :type fixnum :read-only t) (height 0 :type fixnum :read-only t) (depth 1 :type fixnum :read-only t)) (defstruct image (name nil :type string :read-only t) (tex-type :texture-2d :read-only t) (opts nil :type (or null image-opts)) (files nil :type list) (gl-tex -1 :type integer) ;; In case of array texture, maps file name to layer index. (layer-map (make-hash-table :test #'equal))) (defun image-path (name) (sdata:data-path (concatenate 'string "share/textures/" name) :if-does-not-exist :error)) (defun get-image-layer (image name) (with-struct (image- tex-type layer-map) image (assert (eq tex-type :texture-2d-array)) (assert (image-loaded-p image)) (let ((layer (gethash name layer-map))) (if layer layer (progn ;; We need to have a valid LAYER-MAP, otherwise we are using a ;; defaulted image. (assert (string= "missing.bmp" (image-name image))) 0))))) (defun read-image-from-file (fname) (sdl2:load-bmp (image-path fname))) (defun load-image-to-array (name binary-image image-array) (bind-image image-array) (with-struct (image-opts- width height) (image-opts image-array) (assert (= width (sdl2:surface-width binary-image))) (assert (= height (sdl2:surface-height binary-image))) (let ((layer (hash-table-count (image-layer-map image-array)))) (gl:tex-sub-image-3d :texture-2d-array 0 0 0 layer width height 1 :bgr :unsigned-byte (sdl2:surface-pixels binary-image)) (gl:generate-mipmap :texture-2d-array) (setf (gethash name (image-layer-map image-array)) layer)))) (defun load-image (image) (assert (not (image-loaded-p image))) (with-struct (image- tex-type files) image (setf (image-gl-tex image) (first (gl:gen-textures 1))) (bind-image image) (ecase tex-type (:texture-2d-array (assert (length>= 1 files)) (let* ((depth (list-length files)) (binary-images (mapcar (lambda (fname) (cons fname (read-image-from-file fname))) files)) (width (sdl2:surface-width (cdr (first binary-images)))) (height (sdl2:surface-height (cdr (first binary-images))))) (setf (image-opts image) (make-image-opts :width width :height height :depth depth)) (gl:tex-image-3d :texture-2d-array 0 :srgb8 width height depth 0 :bgr :unsigned-byte (cffi:null-pointer)) (dolist (bimage binary-images) ;; TODO: Better error handling. (destructuring-bind (name . data) bimage (load-image-to-array name data image) (sdl2:free-surface data))))) (:texture-2d (assert (length= 1 files)) (let* ((data (read-image-from-file (first files))) (width (sdl2:surface-width data)) (height (sdl2:surface-height data))) (setf (image-opts image) (make-image-opts :width width :height height)) (gl:tex-image-2d :texture-2d 0 :srgb8 width height 0 :bgr :unsigned-byte (sdl2:surface-pixels data)) (sdl2:free-surface data)))) (gl:generate-mipmap tex-type) (gl:tex-parameter tex-type :texture-min-filter :linear-mipmap-nearest) (gl:tex-parameter tex-type :texture-mag-filter :linear)) image) (defun purge-image (image) (when (image-loaded-p image) (gl:delete-textures (list (image-gl-tex image))) (setf (image-gl-tex image) -1))) (defun bind-image (image) (unless (image-loaded-p image) (load-image image)) (with-struct (image- tex-type gl-tex) image (gl:bind-texture tex-type gl-tex))) (defun image-loaded-p (image) (/= (image-gl-tex image) -1)) (defun image-storage-size (image) "Return the estimated size in bytes this image is using in GL." (if (not (image-loaded-p image)) 0 (with-struct (image- opts) image (with-struct (image-opts- width height depth) opts (* width height depth 3 ;; 3 bytes per pixel; TODO: Calc for different formats. (/ 4 3)))))) ;; Account for mipmaps; TODO: Calc without mipmaps. (defstruct image-manager (images nil :type list) ;; Maps image name to image structure. (image-map (make-hash-table :test #'equal) :type hash-table) ;; Maps image-opts to a list of images. (image-opts-map (make-hash-table :test #'equalp) :type hash-table) (missing-image nil :type (or null image))) (defun get-image (image-manager name &key (default (image-manager-missing-image image-manager))) "Return a loaded image called NAME. If the image is not loaded (either it failed to load or no load was requested), returns DEFAULT." (with-struct (image-manager- image-map) image-manager (gethash name image-map default))) (defun get-images-with-opts (image-manager opts) (gethash opts (image-manager-image-opts-map image-manager))) (defun add-image (image-manager image) (push image (image-manager-images image-manager)) (setf (gethash (image-name image) (image-manager-image-map image-manager)) image)) (defun find-image-array (image-manager opts) (with-struct (image-opts- depth) opts (dolist (image (get-images-with-opts image-manager opts)) (when (> depth (hash-table-count (image-layer-map image))) (return image))))) (defun get-or-create-image-array (image-manager name opts) (or (find-image-array image-manager opts) (let ((image-array (make-image :name name :tex-type :texture-2d-array :opts opts))) (setf (image-gl-tex image-array) (first (gl:gen-textures 1))) (bind-image image-array) (with-struct (image-opts- width height depth) opts (gl:tex-image-3d :texture-2d-array 0 :srgb8 width height depth 0 :bgr :unsigned-byte (cffi:null-pointer))) (gl:tex-parameter :texture-2d-array :texture-min-filter :linear-mipmap-nearest) (gl:tex-parameter :texture-2d-array :texture-mag-filter :linear) (setf (gethash opts (image-manager-image-opts-map image-manager)) (list image-array)) (add-image image-manager image-array) image-array))) (defun load-image-from-file (image-manager fname) "Load image from file FNAME. If the image was already loaded, return the existing one. In case of any loading errors, return default image for missing textures." (or (get-image image-manager fname :default nil) (handler-case (let ((binary-image (read-image-from-file fname))) (unwind-protect (let* ((opts (make-image-opts :width (sdl2:surface-width binary-image) :height (sdl2:surface-height binary-image) :depth 10)) (image-array (get-or-create-image-array image-manager fname opts))) (push fname (image-files image-array)) (setf (gethash fname (image-manager-image-map image-manager)) image-array) (load-image-to-array fname binary-image image-array) image-array) (sdl2:free-surface binary-image))) ;; TODO: Other errors? (sdata:data-file-error (c) (shake:print-error "~A~%" c) (image-manager-missing-image image-manager))))) (defun load-map-images (image-manager image-names) (dolist (name image-names) (load-image-from-file image-manager name))) (defun init-image-manager () (let ((im (make-image-manager))) ;; TODO: Replace missing image with a programmatic image, so we don't ;; depend on potentially missing file. (setf (image-manager-missing-image im) (load-image-from-file im "missing.bmp")) im)) (defun shutdown-image-manager (image-manager) (dolist (image (image-manager-images image-manager)) (purge-image image)) (setf (image-manager-images image-manager) nil) (clrhash (image-manager-image-map image-manager)) (clrhash (image-manager-image-opts-map image-manager)))
8,570
Common Lisp
.lisp
180
38.416667
96
0.62261
Th30n/cl-shake
10
1
1
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
f53dffc5ccaa636543a4be2410c5801f3fb6a1b9bd61e023293e5a68d250a827
10,779
[ -1 ]
10,780
fbx.lisp
Th30n_cl-shake/shake/fbx.lisp
;;;; Loading Autodesk Kaydara Filmbox (FBX) 3D model files (in-package #:shake.fbx) (declaim (inline float32-ieee-754-sign)) (defun float32-ieee-754-sign (binary) "Return sign bit value from BINARY representation of a float." (check-type binary (unsigned-byte 32)) (ldb (byte 1 31) binary)) (declaim (inline float32-ieee-754-exponent)) (defun float32-ieee-754-exponent (binary) "Return exponent value after offseting by 127 from the BINARY representation" (check-type binary (unsigned-byte 32)) (- (ldb (byte 8 23) binary) 127)) (declaim (inline float32-ieee-754-mantissa)) (defun float32-ieee-754-mantissa (binary) "Return value mantissa bits from BINARY representation of a float." (check-type binary (unsigned-byte 32)) (ldb (byte 23 0) binary)) (defun decode-float32-iee-754 (binary) "Return either a SINGLE-FLOAT, :NAN, :POSITIVE-INFINITY or :NEGATIVE-INFINITY by decoding the BINARY IEEE 754 representation." (declare (optimize (speed 3) (space 3))) (check-type binary (unsigned-byte 32)) (let ((mantissa (float32-ieee-754-mantissa binary)) (exponent (float32-ieee-754-exponent binary)) (sign (float32-ieee-754-sign binary))) (when (= 128 exponent) ;; Handle infinity or NaN (return-from decode-float32-iee-754 (cond ((/= 0 mantissa) :nan) ((zerop sign) :positive-infinity) (t :negative-infinity)))) (if (= -127 exponent) ;; Denormalized (setf exponent -126) ;; Regular (setf (ldb (byte 1 23) mantissa) 1)) (scale-float (float (if (zerop sign) mantissa (- mantissa))) (- exponent 23)))) (defun decode-float64-iee-754 (binary) "Return either a DOUBLE-FLOAT, :NAN, :POSITIVE-INFINITY or :NEGATIVE-INFINITY by decoding the BINARY IEEE 754 representation." (declare (optimize (speed 3) (space 3))) (check-type binary (unsigned-byte 64)) (let ((mantissa (ldb (byte 52 0) binary)) (exponent (- (ldb (byte 11 52) binary) 1023)) (sign (ldb (byte 1 63) binary))) (when (= 1024 exponent) ;; Handle infinity or NaN (return-from decode-float64-iee-754 (cond ((/= 0 mantissa) :nan) ((zerop sign) :positive-infinity) (t :negative-infinity)))) (if (= -1023 exponent) ;; Denormalized (setf exponent -1022) ;; Regular (setf (ldb (byte 1 52) mantissa) 1)) (scale-float (float (if (zerop sign) mantissa (- mantissa)) 1d0) (- exponent 52)))) (defun fbx-read-header-from-stream (stream) "Read the header from byte STREAM and return FBX version." (declare (optimize (speed 3) (space 3))) (check-type stream stream) (assert (input-stream-p stream)) (assert (equalp (stream-element-type stream) '(unsigned-byte 8))) (loop for c across "Kaydara FBX Binary " unless (= (char-code c) (read-byte stream)) do (error "Not a valid FBX file!")) (unless (and (= #x00 (read-byte stream)) (= #x1a (read-byte stream)) (= #x00 (read-byte stream))) (error "Not a valid FBX file!")) (uiop:read-little-endian stream 4)) (defstruct node-header (end-offset 0 :type (unsigned-byte 32)) (num-properties 0 :type (unsigned-byte 32)) ;; byte length (property-list-len 0 :type (unsigned-byte 32)) (name-len 0 :type (unsigned-byte 8)) (name "" :type string) (properties nil) (nested-nodes nil)) (defun read-array-property-from-stream (stream element-type element-reader) (let* ((len (uiop:read-little-endian stream 4)) (encoding (uiop:read-little-endian stream 4)) (compressed-len (uiop:read-little-endian stream 4)) (array (make-array len :element-type element-type))) (case encoding (0 (loop for i from 0 below len do (setf (aref array i) (funcall element-reader stream)))) (1 ;; zip compressed ;; TODO: (loop repeat compressed-len do (read-byte stream))) (t (error "Unsupported FBX array property encoding!"))) array)) (defun read-property-from-stream (stream) (let ((type-code (code-char (read-byte stream)))) (case type-code ;; boolean (#\C (if (/= 0 (read-byte stream)) t)) ;; TODO: ;; 2b signed int (#\Y (uiop:read-little-endian stream 2)) ;; 4b signed int (#\I (uiop:read-little-endian stream 4)) ;; 8b signed int (#\L (uiop:read-little-endian stream 8)) ;; 4b float32-ieee-754 (#\F (decode-float32-iee-754 (uiop:read-little-endian stream 4))) ;; 8b float64-ieee-754 (#\D (decode-float64-iee-754 (uiop:read-little-endian stream 8))) ;; array of 1b booleans (#\b (read-array-property-from-stream stream 'boolean (lambda (s) (if (/= 0 (read-byte s)) t)))) ;; array of 4b signed ints (#\i (read-array-property-from-stream stream '(unsigned-byte 32) #'uiop:read-little-endian)) ;; array of 8b signed ints (#\l (read-array-property-from-stream stream '(unsigned-byte 64) (lambda (s) (uiop:read-little-endian s 8)))) ;; array of 4b float32-ieee-754 (#\f (read-array-property-from-stream stream 'single-float (lambda (s) (decode-float32-iee-754 (uiop:read-little-endian s 4))))) ;; array of 8b float64-ieee-754 (#\d (read-array-property-from-stream stream 'double-float (lambda (s) (decode-float64-iee-754 (uiop:read-little-endian s 8))))) ;; string (#\S (let* ((len (uiop:read-little-endian stream 4)) (string (make-array len :element-type 'character))) (loop for i from 0 below len do (setf (aref string i) (code-char (read-byte stream)))) string)) ;; raw binary data (#\R (let* ((len (uiop:read-little-endian stream 4)) (string (make-array len :element-type '(unsigned-byte 8)))) (loop for i from 0 below len do (setf (aref string i) (read-byte stream))) string)) (t (error "Unsupported FBX property type '~A'" type-code))))) (defun fbx-read-node-header-from-stream (stream) (let* ((end-offset (uiop:read-little-endian stream 4)) (num-properties (uiop:read-little-endian stream 4)) (property-list-len (uiop:read-little-endian stream 4)) (name-len (read-byte stream)) (name (make-array name-len :element-type 'character))) (loop for i from 0 below name-len do (setf (aref name i) (code-char (read-byte stream)))) (make-node-header :end-offset end-offset :num-properties num-properties :property-list-len property-list-len :name-len name-len :name name :properties (loop repeat num-properties collect (read-property-from-stream stream))))) (defun read-fbx-from-file (filespec) (with-open-file (fstream filespec :element-type '(unsigned-byte 8)) (let ((version (fbx-read-header-from-stream fstream))) (unless (< 7000 version 7500) (error "Unsupported FBX version ~A" version))) (labels ((read-node () (let ((node (fbx-read-node-header-from-stream fstream))) (when (zerop (node-header-end-offset node)) (return-from read-node :eof)) (when (< (file-position fstream) (node-header-end-offset node)) ;; Read nested nodes (setf (node-header-nested-nodes node) (loop while (< (file-position fstream) (- (node-header-end-offset node) 13)) collecting (read-node))) (loop repeat 13 unless (= #x00 (read-byte fstream)) do (error "Not a valid FBX file!"))) (unless (= (file-position fstream) (node-header-end-offset node)) (error "Not a valid FBX file!")) node))) (loop while (< (file-position fstream) (file-length fstream)) collect (let ((node-or-eof (read-node))) (if (eq :eof node-or-eof) (loop-finish) node-or-eof))))))
8,263
Common Lisp
.lisp
186
35.951613
83
0.606944
Th30n/cl-shake
10
1
1
GPL-2.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
ab07d1868b599c6801ac7bab04e87e48b1f88dbb8c3f483d500ad7a6f537b1da
10,780
[ -1 ]