Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/MinimalRoboticsPlatform/src/environments | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest/envConfig.zig | pub const envConfTemplate = @import("configTemplates").envConfigTemplate;
const StatusControlConf = envConfTemplate.StatusControlConf;
pub const env_config = envConfTemplate.EnvConfig(3){
.status_control = [_]StatusControlConf{
.{
.status_type = .isize,
.name = "height",
.id = 0,
.topic_conf = null,
},
.{
.status_type = .topic,
.name = "height-sensor",
.id = 1,
.topic_conf = .{
.buffer_type = envConfTemplate.TopicBufferTypes.RingBuffer,
.buffer_size = 0x100000,
},
},
.{
.status_type = .topic,
.name = "front-ultrasonic-proximity",
.id = 2,
.topic_conf = .{
.buffer_type = envConfTemplate.TopicBufferTypes.RingBuffer,
.buffer_size = 1024,
},
},
},
};
|
0 | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest/setupRoutines/raspi3bSetup.zig | const std = @import("std");
const board = @import("board");
const arm = @import("arm");
const cpuContext = arm.cpuContext;
const periph = @import("periph");
const kprint = periph.uart.UartWriter(.ttbr1).kprint;
const ProccessorRegMap = arm.processor.ProccessorRegMap;
const sharedKernelServices = @import("sharedKernelServices");
const Scheduler = sharedKernelServices.Scheduler;
pub fn bcm2835Setup(scheduler: *Scheduler) void {
_ = scheduler;
// enabling arm generic timer irq
@as(*volatile u32, @ptrFromInt(board.PeriphConfig(.ttbr1).ArmGenericTimer.base_address)).* = 1 << 1 | 1 << 3;
ProccessorRegMap.DaifReg.setDaifClr(.{
.debug = true,
.serr = true,
.irqs = true,
.fiqs = true,
});
if (board.driver.secondaryInterruptConrtollerDriver) |secondary_ic| {
secondary_ic.addIcHandler(&irqHandler) catch |e| {
kprint("[error] addIcHandler error: {s} \n", .{@errorName(e)});
while (true) {}
};
}
kprint("inited raspberry secondary Ic and arm timer \n", .{});
}
pub const RegValues = struct {
// all banks are lister here: https://github.com/torvalds/linux/blob/master/Documentation/devicetree/bindings/interrupt-controller/brcm%2Cbcm2835-armctrl-ic.txt
pub const Bank0 = enum(u32) {
armTimer = 1 << 0,
armMailbox = 1 << 1,
armDoorbell0 = 1 << 2,
armDoorbell1 = 1 << 3,
vpu0Halted = 1 << 4,
vpu1Halted = 1 << 5,
illegalType0 = 1 << 6,
illegalType1 = 1 << 7,
pending1 = 1 << 8,
pending2 = 1 << 9,
notDefined = 0,
};
pub const Bank1 = enum(u32) {
timer0 = 1 << 0,
timer1 = 1 << 1,
timer2 = 1 << 2,
timer3 = 1 << 3,
codec0 = 1 << 4,
codec1 = 1 << 5,
codec2 = 1 << 6,
vcJpeg = 1 << 7,
isp = 1 << 8,
vcUsb = 1 << 9,
vc3d = 1 << 10,
transposer = 1 << 11,
multicoresync0 = 1 << 12,
multicoresync1 = 1 << 13,
multicoresync2 = 1 << 14,
multicoresync3 = 1 << 15,
dma0 = 1 << 16,
dma1 = 1 << 17,
vcDma2 = 1 << 18,
vcDma3 = 1 << 19,
dma4 = 1 << 20,
dma5 = 1 << 21,
dma6 = 1 << 22,
dma7 = 1 << 23,
dma8 = 1 << 24,
dma9 = 1 << 25,
dma10 = 1 << 26,
// 27: dma11-14 - shared interrupt for dma 11 to 14
dma11 = 1 << 27,
// 28: dmaall - triggers on all dma interrupts (including chanel 15)
dmaall = 1 << 28,
aux = 1 << 29,
arm = 1 << 30,
vpudma = 1 << 31,
notDefined = 0,
};
// bank2
pub const Bank2 = enum(u32) {
hostport = 1 << 0,
videoscaler = 1 << 1,
ccp2tx = 1 << 2,
sdc = 1 << 3,
dsi0 = 1 << 4,
ave = 1 << 5,
cam0 = 1 << 6,
cam1 = 1 << 7,
hdmi0 = 1 << 8,
hdmi1 = 1 << 9,
pixelValve1 = 1 << 10,
i2cSpislv = 1 << 11,
dsi1 = 1 << 12,
pwa0 = 1 << 13,
pwa1 = 1 << 14,
cpr = 1 << 15,
smi = 1 << 16,
gpio0 = 1 << 17,
gpio1 = 1 << 18,
gpio2 = 1 << 19,
gpio3 = 1 << 20,
vci2c = 1 << 21,
vcSpi = 1 << 22,
vcI2spcm = 1 << 23,
vcSdio = 1 << 24,
vcUart = 1 << 25,
slimbus = 1 << 26,
vec = 1 << 27,
cpg = 1 << 28,
rng = 1 << 29,
vcArasansdio = 1 << 30,
avspmon = 1 << 31,
notDefined = 0,
};
};
// bcm2835 interrupt controller handler for raspberry
const Bank0 = RegValues.Bank0;
const Bank1 = RegValues.Bank1;
const Bank2 = RegValues.Bank2;
pub fn irqHandler(context: *cpuContext.CpuContext) void {
var irq_bank_0 = std.meta.intToEnum(Bank0, board.SecondaryInterruptControllerKpiType.RegMap.pendingBasic.*) catch |e| {
kprint("[panic] std meta intToEnum error: {s} \n", .{@errorName(e)});
while (true) {}
};
var irq_bank_1 = std.meta.intToEnum(Bank1, board.SecondaryInterruptControllerKpiType.RegMap.pendingIrq1.*) catch |e| {
kprint("[panic] std meta intToEnum error: {s} \n", .{@errorName(e)});
while (true) {}
};
var irq_bank_2 = std.meta.intToEnum(Bank2, board.SecondaryInterruptControllerKpiType.RegMap.pendingIrq2.*) catch |e| {
kprint("[panic] std meta intToEnum error: {s} \n", .{@errorName(e)});
while (true) {}
};
switch (irq_bank_0) {
// One or more bits set in pending register 1
Bank0.pending1 => {
switch (irq_bank_1) {
Bank1.timer1 => {
if (std.mem.eql(u8, board.driver.timerDriver.timer_name, "bcm2835_timer")) {
board.driver.timerDriver.timerTick(context) catch |e| {
kprint("[panic] timerDriver timerTick error: {s} \n", .{@errorName(e)});
while (true) {}
};
}
},
else => {
// kprint("Not supported 1 irq num: {s} \n", .{@tagName(irq_bank_1)});
},
}
},
// One or more bits set in pending register 2
Bank0.pending2 => {
switch (irq_bank_2) {
else => {
// kprint("Not supported bank 2 irq num: {s} \n", .{@tagName(irq_bank_0)});
},
}
},
Bank0.armTimer => {
if (std.mem.eql(u8, board.driver.timerDriver.timer_name, "arm_gt")) {
board.driver.timerDriver.timerTick(context) catch |e| {
kprint("[panic] timerDriver timerTick error: {s} \n", .{@errorName(e)});
while (true) {}
};
}
},
else => {
// kprint("Not supported bank(neither 1/2) irq num: {d} \n", .{intController.RegMap.pendingBasic.*});
// raspberries timers are a mess and I'm currently unsure if the Arm Generic timer
// has an enum defined in the banks or if it's not defined through the bcm28835 system.
},
}
}
|
0 | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest/setupRoutines/routines.zig | const board = @import("board");
const std = @import("std");
const sharedKernelServices = @import("sharedKernelServices");
const Scheduler = sharedKernelServices.Scheduler;
const raspi3bSetup = @import("raspi3bSetup.zig").bcm2835Setup;
const qemuVirtSetup = @import("qemuVirtSetup.zig").qemuVirtSetup;
const SetupRoutine = fn (scheduler: *Scheduler) void;
const boardSpecificSetup = blk: {
if (std.mem.eql(u8, board.config.board_name, "raspi3b")) {
break :blk [_]SetupRoutine{raspi3bSetup};
} else if (std.mem.eql(u8, board.config.board_name, "qemuVirt")) {
break :blk [_]SetupRoutine{qemuVirtSetup};
}
};
// setupRoutines array is loaded and inited by the kernel
pub const setupRoutines = [_]SetupRoutine{} ++ boardSpecificSetup;
|
0 | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest/setupRoutines/qemuVirtSetup.zig | const std = @import("std");
const board = @import("board");
const arm = @import("arm");
const cpuContext = arm.cpuContext;
const ProccessorRegMap = arm.processor.ProccessorRegMap;
const gic = arm.gicv2.Gic(.ttbr1);
const InterruptIds = gic.InterruptIds;
const periph = @import("periph");
const kprint = periph.uart.UartWriter(.ttbr1).kprint;
const sharedKernelServices = @import("sharedKernelServices");
const Scheduler = sharedKernelServices.Scheduler;
pub fn qemuVirtSetup(scheduler: *Scheduler) void {
_ = scheduler;
gic.init() catch |e| {
kprint("[panic] gic init error: {s}\n", .{@errorName(e)});
while (true) {}
};
gic.Gicd.gicdConfig(InterruptIds.non_secure_physical_timer, 0x2) catch |e| {
kprint("[panic] gicd gicdConfig error: {s}\n", .{@errorName(e)});
while (true) {}
};
gic.Gicd.gicdSetPriority(InterruptIds.non_secure_physical_timer, 0) catch |e| {
kprint("[panic] gicd setPriority error: {s}\n", .{@errorName(e)});
while (true) {}
};
gic.Gicd.gicdSetTarget(InterruptIds.non_secure_physical_timer, 1) catch |e| {
kprint("[panic] gicd setTarget error: {s}\n", .{@errorName(e)});
while (true) {}
};
gic.Gicd.gicdClearPending(InterruptIds.non_secure_physical_timer) catch |e| {
kprint("[panic] gicd clearPending error: {s}\n", .{@errorName(e)});
while (true) {}
};
gic.Gicd.gicdEnableInt(InterruptIds.non_secure_physical_timer) catch |e| {
kprint("[panic] gicdEnableInt address calc error: {s}\n", .{@errorName(e)});
while (true) {}
};
ProccessorRegMap.DaifReg.setDaifClr(.{
.debug = true,
.serr = true,
.irqs = true,
.fiqs = true,
});
}
|
0 | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest/userApps | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest/userApps/app3/main.zig | const std = @import("std");
const board = @import("board");
const appLib = @import("appLib");
const Mutex = appLib.Mutex;
const AppAlloc = appLib.AppAllocator;
const SharedMemTopicsInterface = appLib.SharedMemTopicsInterface;
const sysCalls = appLib.sysCalls;
const utils = appLib.utils;
const kprint = appLib.sysCalls.SysCallPrint.kprint;
var test_counter: usize = 0;
var shared_thread_counter: isize = 0;
var mutex = Mutex.init();
var shared_mutex: *Mutex = &mutex;
export fn app_main(pid: usize) linksection(".text.main") callconv(.C) noreturn {
kprint("app3 initial pid: {d} \n", .{pid});
var ret: usize = 0;
var ret_buff: []u8 = undefined;
ret_buff.ptr = @as([*]u8, @ptrCast(&ret));
ret_buff.len = @sizeOf(@TypeOf(ret));
var topics_interf = SharedMemTopicsInterface.init() catch |e| {
kprint("app3 SharedMemTopicsInterface init err: {s} \n", .{@errorName(e)});
while (true) {}
};
while (true) {
var read_len = topics_interf.read("front-ultrasonic-proximity", ret_buff) catch |e| {
kprint("app3 SharedMemTopicsInterface read err: {s} \n", .{@errorName(e)});
while (true) {}
};
if (read_len < ret_buff.len) kprint("buffer partially filled {d}/ {d} bytes \n", .{ read_len, ret_buff.len });
kprint("SharedMemTopicsInterface read: {any} \n", .{ret});
// _ = topics_interf;
// _ = ret_buff;
}
}
|
0 | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest/userApps | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest/userApps/app3/linker.ld | ENTRY(app_main)
SECTIONS {
. = 0x0;
.text : ALIGN(16) {
*(.text.main)
}
.got : {
*(.got.plt);
*(.got);
}
.rodata : ALIGN(0x8) {
*(.rodata);
*(.rodata.*);
}
.bss : ALIGN(0x10) {
_bss_start = .;
*(.bss.*);
*(COMMON);
_bss_end = .;
}
.data : {
*(.data);
*(.data.*);
}
.heap (NOLOAD) : ALIGN(8) {
_heap_start = .;
}
} |
0 | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest/userApps | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest/userApps/app1/main.zig | const std = @import("std");
const appLib = @import("appLib");
const AppAlloc = appLib.AppAllocator;
const sysCalls = appLib.sysCalls;
const kprint = appLib.sysCalls.SysCallPrint.kprint;
export fn app_main(pid: usize) linksection(".text.main") callconv(.C) noreturn {
kprint("app1 initial pid: {d} \n", .{pid});
var counter: usize = 0;
var payload: []u8 = undefined;
payload.ptr = @as([*]u8, @ptrCast(&counter));
payload.len = @sizeOf(@TypeOf(counter));
while (true) {
var data_written = sysCalls.pushToTopic("front-ultrasonic-proximity", payload) catch |e| {
kprint("syscall pushToTopic err: {s} \n", .{@errorName(e)});
while (true) {}
};
if (data_written < payload.len) kprint("partially written {d}/ {d} bytes \n", .{ data_written, payload.len });
kprint("pushin: {d} \n", .{counter});
counter += 1;
// const topics_interfaces_read = @intToPtr(*volatile [1000]usize, 0x20000000).*;
// kprint("topics interface read: {any} \n", .{topics_interfaces_read});
}
}
|
0 | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest/userApps | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest/userApps/app1/linker.ld | ENTRY(app_main)
SECTIONS {
. = 0x0;
.text : ALIGN(16) {
*(.text.main)
}
.got : {
*(.got.plt);
*(.got);
}
.rodata : ALIGN(0x8) {
*(.rodata);
*(.rodata.*);
}
.bss : ALIGN(0x10) {
_bss_start = .;
*(.bss.*);
*(COMMON);
_bss_end = .;
}
.data : {
*(.data);
*(.data.*);
}
.heap (NOLOAD) : ALIGN(8) {
_heap_start = .;
}
} |
0 | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest/userApps/actions | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest/userApps/actions/action1/main.zig | const std = @import("std");
const appLib = @import("appLib");
const board = @import("board");
const arm = @import("arm");
const cpuContext = arm.cpuContext;
const AppAlloc = appLib.AppAllocator;
const sysCalls = appLib.sysCalls;
const kprint = appLib.sysCalls.SysCallPrint.kprint;
var test_counter: usize = 0;
export fn app_main(pid: usize) linksection(".text.main") callconv(.C) noreturn {
_ = pid;
while (true) {}
}
|
0 | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest/userApps/actions | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest/userApps/actions/action1/linker.ld | ENTRY(app_main)
SECTIONS {
. = 0x0;
.text : ALIGN(16) {
*(.text.main)
}
.got : {
*(.got.plt);
*(.got);
}
.rodata : ALIGN(0x8) {
*(.rodata);
*(.rodata.*);
}
.bss : ALIGN(0x10) {
_bss_start = .;
*(.bss.*);
*(COMMON);
_bss_end = .;
}
.data : {
*(.data);
*(.data.*);
}
.heap (NOLOAD) : ALIGN(8) {
_heap_start = .;
}
} |
0 | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest/userApps | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest/userApps/app2/main.zig | const std = @import("std");
const board = @import("board");
const appLib = @import("appLib");
const Mutex = appLib.Mutex;
const AppAlloc = appLib.AppAllocator;
const sysCalls = appLib.sysCalls;
const utils = appLib.utils;
const kprint = appLib.sysCalls.SysCallPrint.kprint;
var test_counter: usize = 0;
var shared_thread_counter: isize = 0;
var mutex = Mutex.init();
var shared_mutex: *Mutex = &mutex;
export fn app_main(pid: usize) linksection(".text.main") callconv(.C) noreturn {
kprint("app2 initial pid: {d} \n", .{pid});
var ret: usize = 0;
var ret_buff: []u8 = undefined;
ret_buff.ptr = @as([*]u8, @ptrCast(&ret));
ret_buff.len = @sizeOf(@TypeOf(ret));
while (true) {
kprint("going to wait \n", .{});
sysCalls.waitForTopicUpdate("front-ultrasonic-proximity") catch |e| {
kprint("syscall waitForTopicUpdate err: {s} \n", .{@errorName(e)});
// while (true) {}
};
var read_len = sysCalls.popFromTopic("front-ultrasonic-proximity", ret_buff) catch |e| {
kprint("syscall popFromTopic err: {s} \n", .{@errorName(e)});
while (true) {}
};
if (read_len < ret_buff.len) kprint("buffer partially filled {d}/ {d} bytes \n", .{ read_len, ret_buff.len });
kprint("topic pop: {any} \n", .{ret});
}
}
|
0 | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest/userApps | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest/userApps/app2/linker.ld | ENTRY(app_main)
SECTIONS {
. = 0x0;
.text : ALIGN(16) {
*(.text.main)
*(.text.);
*(.text.*);
}
.rodata : ALIGN(0x8) {
*(.rodata);
*(.rodata.*);
}
.got : {
*(.got.plt);
*(.got);
}
.bss : ALIGN(0x10) {
_bss_start = .;
*(.bss.*);
*(COMMON);
_bss_end = .;
}
.data : {
*(.data);
*(.data.*);
}
.heap (NOLOAD) : ALIGN(8) {
_heap_start = .;
}
} |
0 | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest | repos/MinimalRoboticsPlatform/src/environments/sysCallTopicsTest/kernelThreads/threads.zig | const sharedKernelServices = @import("sharedKernelServices");
const Scheduler = sharedKernelServices.Scheduler;
const Thread = fn (scheduler: *Scheduler) noreturn;
// threads array is loaded and inited by the kernel
pub const threads = [_]Thread{};
|
0 | repos/MinimalRoboticsPlatform/src/environments | repos/MinimalRoboticsPlatform/src/environments/statusControlTest/envConfig.zig | pub const envConfTemplate = @import("configTemplates").envConfigTemplate;
const StatusControlConf = envConfTemplate.StatusControlConf;
pub const env_config = envConfTemplate.EnvConfig(3){
.status_control = [_]StatusControlConf{
.{
.status_type = .isize,
.name = "height",
.id = 0,
.topic_conf = null,
},
.{
.status_type = .bool,
.name = "groundContact",
.id = 1,
.topic_conf = null,
},
.{
.status_type = .topic,
.name = "height-sensor",
.id = 2,
.topic_conf = .{
.buffer_type = envConfTemplate.TopicBufferTypes.RingBuffer,
.buffer_size = 1024,
},
},
},
};
|
0 | repos/MinimalRoboticsPlatform/src/environments/statusControlTest | repos/MinimalRoboticsPlatform/src/environments/statusControlTest/setupRoutines/raspi3bSetup.zig | const std = @import("std");
const board = @import("board");
const arm = @import("arm");
const cpuContext = arm.cpuContext;
const periph = @import("periph");
const kprint = periph.uart.UartWriter(.ttbr1).kprint;
const ProccessorRegMap = arm.processor.ProccessorRegMap;
const sharedKernelServices = @import("sharedKernelServices");
const Scheduler = sharedKernelServices.Scheduler;
pub fn bcm2835Setup(scheduler: *Scheduler) void {
_ = scheduler;
// enabling arm generic timer irq
@as(*volatile u32, @ptrFromInt(board.PeriphConfig(.ttbr1).ArmGenericTimer.base_address)).* = 1 << 1 | 1 << 3;
ProccessorRegMap.DaifReg.setDaifClr(.{
.debug = true,
.serr = true,
.irqs = true,
.fiqs = true,
});
if (board.driver.secondaryInterruptConrtollerDriver) |secondary_ic| {
secondary_ic.addIcHandler(&irqHandler) catch |e| {
kprint("[error] addIcHandler error: {s} \n", .{@errorName(e)});
while (true) {}
};
}
kprint("inited raspberry secondary Ic and arm timer \n", .{});
}
pub const RegValues = struct {
// all banks are lister here: https://github.com/torvalds/linux/blob/master/Documentation/devicetree/bindings/interrupt-controller/brcm%2Cbcm2835-armctrl-ic.txt
pub const Bank0 = enum(u32) {
armTimer = 1 << 0,
armMailbox = 1 << 1,
armDoorbell0 = 1 << 2,
armDoorbell1 = 1 << 3,
vpu0Halted = 1 << 4,
vpu1Halted = 1 << 5,
illegalType0 = 1 << 6,
illegalType1 = 1 << 7,
pending1 = 1 << 8,
pending2 = 1 << 9,
notDefined = 0,
};
pub const Bank1 = enum(u32) {
timer0 = 1 << 0,
timer1 = 1 << 1,
timer2 = 1 << 2,
timer3 = 1 << 3,
codec0 = 1 << 4,
codec1 = 1 << 5,
codec2 = 1 << 6,
vcJpeg = 1 << 7,
isp = 1 << 8,
vcUsb = 1 << 9,
vc3d = 1 << 10,
transposer = 1 << 11,
multicoresync0 = 1 << 12,
multicoresync1 = 1 << 13,
multicoresync2 = 1 << 14,
multicoresync3 = 1 << 15,
dma0 = 1 << 16,
dma1 = 1 << 17,
vcDma2 = 1 << 18,
vcDma3 = 1 << 19,
dma4 = 1 << 20,
dma5 = 1 << 21,
dma6 = 1 << 22,
dma7 = 1 << 23,
dma8 = 1 << 24,
dma9 = 1 << 25,
dma10 = 1 << 26,
// 27: dma11-14 - shared interrupt for dma 11 to 14
dma11 = 1 << 27,
// 28: dmaall - triggers on all dma interrupts (including chanel 15)
dmaall = 1 << 28,
aux = 1 << 29,
arm = 1 << 30,
vpudma = 1 << 31,
notDefined = 0,
};
// bank2
pub const Bank2 = enum(u32) {
hostport = 1 << 0,
videoscaler = 1 << 1,
ccp2tx = 1 << 2,
sdc = 1 << 3,
dsi0 = 1 << 4,
ave = 1 << 5,
cam0 = 1 << 6,
cam1 = 1 << 7,
hdmi0 = 1 << 8,
hdmi1 = 1 << 9,
pixelValve1 = 1 << 10,
i2cSpislv = 1 << 11,
dsi1 = 1 << 12,
pwa0 = 1 << 13,
pwa1 = 1 << 14,
cpr = 1 << 15,
smi = 1 << 16,
gpio0 = 1 << 17,
gpio1 = 1 << 18,
gpio2 = 1 << 19,
gpio3 = 1 << 20,
vci2c = 1 << 21,
vcSpi = 1 << 22,
vcI2spcm = 1 << 23,
vcSdio = 1 << 24,
vcUart = 1 << 25,
slimbus = 1 << 26,
vec = 1 << 27,
cpg = 1 << 28,
rng = 1 << 29,
vcArasansdio = 1 << 30,
avspmon = 1 << 31,
notDefined = 0,
};
};
// bcm2835 interrupt controller handler for raspberry
const Bank0 = RegValues.Bank0;
const Bank1 = RegValues.Bank1;
const Bank2 = RegValues.Bank2;
pub fn irqHandler(context: *cpuContext.CpuContext) void {
var irq_bank_0 = std.meta.intToEnum(Bank0, board.SecondaryInterruptControllerKpiType.RegMap.pendingBasic.*) catch |e| {
kprint("[panic] std meta intToEnum error: {s} \n", .{@errorName(e)});
while (true) {}
};
var irq_bank_1 = std.meta.intToEnum(Bank1, board.SecondaryInterruptControllerKpiType.RegMap.pendingIrq1.*) catch |e| {
kprint("[panic] std meta intToEnum error: {s} \n", .{@errorName(e)});
while (true) {}
};
var irq_bank_2 = std.meta.intToEnum(Bank2, board.SecondaryInterruptControllerKpiType.RegMap.pendingIrq2.*) catch |e| {
kprint("[panic] std meta intToEnum error: {s} \n", .{@errorName(e)});
while (true) {}
};
switch (irq_bank_0) {
// One or more bits set in pending register 1
Bank0.pending1 => {
switch (irq_bank_1) {
Bank1.timer1 => {
if (std.mem.eql(u8, board.driver.timerDriver.timer_name, "bcm2835_timer")) {
board.driver.timerDriver.timerTick(context) catch |e| {
kprint("[panic] timerDriver timerTick error: {s} \n", .{@errorName(e)});
while (true) {}
};
}
},
else => {
// kprint("Not supported 1 irq num: {s} \n", .{@tagName(irq_bank_1)});
},
}
},
// One or more bits set in pending register 2
Bank0.pending2 => {
switch (irq_bank_2) {
else => {
// kprint("Not supported bank 2 irq num: {s} \n", .{@tagName(irq_bank_0)});
},
}
},
Bank0.armTimer => {
if (std.mem.eql(u8, board.driver.timerDriver.timer_name, "arm_gt")) {
board.driver.timerDriver.timerTick(context) catch |e| {
kprint("[panic] timerDriver timerTick error: {s} \n", .{@errorName(e)});
while (true) {}
};
}
},
else => {
// kprint("Not supported bank(neither 1/2) irq num: {d} \n", .{intController.RegMap.pendingBasic.*});
// raspberries timers are a mess and I'm currently unsure if the Arm Generic timer
// has an enum defined in the banks or if it's not defined through the bcm28835 system.
},
}
}
|
0 | repos/MinimalRoboticsPlatform/src/environments/statusControlTest | repos/MinimalRoboticsPlatform/src/environments/statusControlTest/setupRoutines/routines.zig | const board = @import("board");
const std = @import("std");
const sharedKernelServices = @import("sharedKernelServices");
const Scheduler = sharedKernelServices.Scheduler;
const raspi3bSetup = @import("raspi3bSetup.zig").bcm2835Setup;
const qemuVirtSetup = @import("qemuVirtSetup.zig").qemuVirtSetup;
const SetupRoutine = fn (scheduler: *Scheduler) void;
const boardSpecificSetup = blk: {
if (std.mem.eql(u8, board.config.board_name, "raspi3b")) {
break :blk [_]SetupRoutine{raspi3bSetup};
} else if (std.mem.eql(u8, board.config.board_name, "qemuVirt")) {
break :blk [_]SetupRoutine{qemuVirtSetup};
}
};
// setupRoutines array is loaded and inited by the kernel
pub const setupRoutines = [_]SetupRoutine{} ++ boardSpecificSetup;
|
0 | repos/MinimalRoboticsPlatform/src/environments/statusControlTest | repos/MinimalRoboticsPlatform/src/environments/statusControlTest/setupRoutines/qemuVirtSetup.zig | const std = @import("std");
const board = @import("board");
const arm = @import("arm");
const cpuContext = arm.cpuContext;
const ProccessorRegMap = arm.processor.ProccessorRegMap;
const gic = arm.gicv2.Gic(.ttbr1);
const InterruptIds = gic.InterruptIds;
const periph = @import("periph");
const kprint = periph.uart.UartWriter(.ttbr1).kprint;
const sharedKernelServices = @import("sharedKernelServices");
const Scheduler = sharedKernelServices.Scheduler;
pub fn qemuVirtSetup(scheduler: *Scheduler) void {
_ = scheduler;
gic.init() catch |e| {
kprint("[panic] gic init error: {s}\n", .{@errorName(e)});
while (true) {}
};
gic.Gicd.gicdConfig(InterruptIds.non_secure_physical_timer, 0x2) catch |e| {
kprint("[panic] gicd gicdConfig error: {s}\n", .{@errorName(e)});
while (true) {}
};
gic.Gicd.gicdSetPriority(InterruptIds.non_secure_physical_timer, 0) catch |e| {
kprint("[panic] gicd setPriority error: {s}\n", .{@errorName(e)});
while (true) {}
};
gic.Gicd.gicdSetTarget(InterruptIds.non_secure_physical_timer, 1) catch |e| {
kprint("[panic] gicd setTarget error: {s}\n", .{@errorName(e)});
while (true) {}
};
gic.Gicd.gicdClearPending(InterruptIds.non_secure_physical_timer) catch |e| {
kprint("[panic] gicd clearPending error: {s}\n", .{@errorName(e)});
while (true) {}
};
gic.Gicd.gicdEnableInt(InterruptIds.non_secure_physical_timer) catch |e| {
kprint("[panic] gicdEnableInt address calc error: {s}\n", .{@errorName(e)});
while (true) {}
};
ProccessorRegMap.DaifReg.setDaifClr(.{
.debug = true,
.serr = true,
.irqs = true,
.fiqs = true,
});
}
|
0 | repos/MinimalRoboticsPlatform/src/environments/statusControlTest/userApps | repos/MinimalRoboticsPlatform/src/environments/statusControlTest/userApps/app1/main.zig | const std = @import("std");
const appLib = @import("appLib");
const board = @import("board");
const arm = @import("arm");
const cpuContext = arm.cpuContext;
const AppAlloc = appLib.AppAllocator;
const sysCalls = appLib.sysCalls;
const kprint = appLib.sysCalls.SysCallPrint.kprint;
var test_counter: usize = 0;
export fn app_main(pid: usize) linksection(".text.main") callconv(.C) noreturn {
kprint("app1 initial pid: {d} \n", .{pid});
var read_state: bool = true;
sysCalls.updateStatus("groundContact", true) catch |e| {
kprint("sysCalls updateStatus err: {s} \n", .{@errorName(e)});
};
while (true) {
read_state = sysCalls.readStatus(bool, "groundContact") catch |e| {
kprint("sysCalls readStatus err: {s} \n", .{@errorName(e)});
while (true) {}
};
if (read_state) {
sysCalls.updateStatus("groundContact", false) catch |e| {
kprint("sysCalls updateStatus err: {s} \n", .{@errorName(e)});
};
kprint("status set 1 to false \n", .{});
}
kprint("status read 1: {any} \n", .{read_state});
}
}
// var test_counter: usize = 0;
// export fn app_main(pid: usize) linksection(".text.main") callconv(.C) noreturn {
// kprint("app1 initial pid: {d} \n", .{pid});
// while (true) {
// test_counter += 1;
// sysCalls.updateStatus("height", @intCast(isize, test_counter)) catch |e| {
// kprint("sysCalls updateStatus err: {s} \n", .{@errorName(e)});
// };
// var read = sysCalls.readStatus(isize, "height") catch |e| {
// kprint("sysCalls readStatus err: {s} \n", .{@errorName(e)});
// while (true) {}
// };
// kprint("status read: {d} \n", .{read});
// }
// }
|
0 | repos/MinimalRoboticsPlatform/src/environments/statusControlTest/userApps | repos/MinimalRoboticsPlatform/src/environments/statusControlTest/userApps/app1/linker.ld | ENTRY(app_main)
SECTIONS {
. = 0x0;
.text : ALIGN(16) {
*(.text.main)
}
.got : {
*(.got.plt);
*(.got);
}
.rodata : ALIGN(0x8) {
*(.rodata);
*(.rodata.*);
}
.bss : ALIGN(0x10) {
_bss_start = .;
*(.bss.*);
*(COMMON);
_bss_end = .;
}
.data : {
*(.data);
*(.data.*);
}
.heap (NOLOAD) : ALIGN(8) {
_heap_start = .;
}
} |
0 | repos/MinimalRoboticsPlatform/src/environments/statusControlTest/userApps/actions | repos/MinimalRoboticsPlatform/src/environments/statusControlTest/userApps/actions/action1/main.zig | const std = @import("std");
const appLib = @import("appLib");
const board = @import("board");
const arm = @import("arm");
const cpuContext = arm.cpuContext;
const AppAlloc = appLib.AppAllocator;
const sysCalls = appLib.sysCalls;
const kprint = appLib.sysCalls.SysCallPrint.kprint;
var test_counter: usize = 0;
export fn app_main(pid: usize) linksection(".text.main") callconv(.C) noreturn {
_ = pid;
while (true) {}
}
|
0 | repos/MinimalRoboticsPlatform/src/environments/statusControlTest/userApps/actions | repos/MinimalRoboticsPlatform/src/environments/statusControlTest/userApps/actions/action1/linker.ld | ENTRY(app_main)
SECTIONS {
. = 0x0;
.text : ALIGN(16) {
*(.text.main)
}
.got : {
*(.got.plt);
*(.got);
}
.rodata : ALIGN(0x8) {
*(.rodata);
*(.rodata.*);
}
.bss : ALIGN(0x10) {
_bss_start = .;
*(.bss.*);
*(COMMON);
_bss_end = .;
}
.data : {
*(.data);
*(.data.*);
}
.heap (NOLOAD) : ALIGN(8) {
_heap_start = .;
}
} |
0 | repos/MinimalRoboticsPlatform/src/environments/statusControlTest/userApps | repos/MinimalRoboticsPlatform/src/environments/statusControlTest/userApps/app2/main.zig | const std = @import("std");
const board = @import("board");
const appLib = @import("appLib");
const Mutex = appLib.Mutex;
const AppAlloc = appLib.AppAllocator;
const sysCalls = appLib.sysCalls;
const utils = appLib.utils;
const kprint = appLib.sysCalls.SysCallPrint.kprint;
var test_counter: usize = 0;
var shared_thread_counter: isize = 0;
var mutex = Mutex.init();
var shared_mutex: *Mutex = &mutex;
export fn app_main(pid: usize) linksection(".text.main") callconv(.C) noreturn {
kprint("app2 initial pid: {d} \n", .{pid});
var read_state: bool = false;
while (true) {
// test_counter += 1;
// kprint("app{d} test print {d} \n", .{ pid, test_counter });
read_state = sysCalls.readStatus(bool, "groundContact") catch |e| {
kprint("sysCalls readStatus err: {s} \n", .{@errorName(e)});
while (true) {}
};
if (!read_state) {
sysCalls.updateStatus("groundContact", true) catch |e| {
kprint("sysCalls updateStatus err: {s} \n", .{@errorName(e)});
};
kprint("status set 2 to true \n", .{});
}
kprint("status read 2: {any} \n", .{read_state});
}
}
|
0 | repos/MinimalRoboticsPlatform/src/environments/statusControlTest/userApps | repos/MinimalRoboticsPlatform/src/environments/statusControlTest/userApps/app2/linker.ld | ENTRY(app_main)
SECTIONS {
. = 0x0;
.text : ALIGN(16) {
*(.text.main)
*(.text.);
*(.text.*);
}
.rodata : ALIGN(0x8) {
*(.rodata);
*(.rodata.*);
}
.got : {
*(.got.plt);
*(.got);
}
.bss : ALIGN(0x10) {
_bss_start = .;
*(.bss.*);
*(COMMON);
_bss_end = .;
}
.data : {
*(.data);
*(.data.*);
}
.heap (NOLOAD) : ALIGN(8) {
_heap_start = .;
}
} |
0 | repos/MinimalRoboticsPlatform/src/environments/statusControlTest | repos/MinimalRoboticsPlatform/src/environments/statusControlTest/kernelThreads/threads.zig | const sharedKernelServices = @import("sharedKernelServices");
const Scheduler = sharedKernelServices.Scheduler;
const Thread = fn (scheduler: *Scheduler) noreturn;
pub const testThread = @import("testThread.zig");
// threads array is loaded and inited by the kernel
pub const threads = [_]Thread{testThread.threadFn};
|
0 | repos/MinimalRoboticsPlatform/src/environments/statusControlTest | repos/MinimalRoboticsPlatform/src/environments/statusControlTest/kernelThreads/testThread.zig | const std = @import("std");
const board = @import("board");
const arm = @import("arm");
const cpuContext = arm.cpuContext;
const periph = @import("periph");
const kprint = periph.uart.UartWriter(.ttbr1).kprint;
const sharedKernelServices = @import("sharedKernelServices");
const Scheduler = sharedKernelServices.Scheduler;
pub fn threadFn(scheduler: *Scheduler) noreturn {
_ = scheduler;
while (true) {}
}
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/periph/pl011.zig | const std = @import("std");
const board = @import("board");
const AddrSpace = board.boardConfig.AddrSpace;
pub fn Pl011(comptime addr_space: AddrSpace) type {
const pl011Cfg = board.PeriphConfig(addr_space).Pl011;
return struct {
const RegMap = struct {
pub const dataReg = @as(*volatile u32, @ptrFromInt(pl011Cfg.base_address + 0x000));
pub const flagReg = @as(*volatile u32, @ptrFromInt(pl011Cfg.base_address + 0x018));
pub const intBaudRateReg = @as(*volatile u32, @ptrFromInt(pl011Cfg.base_address + 0x024));
pub const fracBaudRateReg = @as(*volatile u32, @ptrFromInt(pl011Cfg.base_address + 0x028));
pub const lineCtrlReg = struct {
pub const reg = @as(*volatile u32, @ptrFromInt(pl011Cfg.base_address + 0x02c));
pub const RegAttr = packed struct {
padding: u24 = 0,
stick_parity_select: bool = false,
tx_word_len: u2 = 3, // 3 => b11 => 8 bits
enable_fifo: bool = false,
two_stop_bits_select: bool = false,
even_parity_select: bool = false,
parity_enabled: bool = false,
send_break: bool = false,
pub fn asInt(self: RegAttr) u32 {
return @as(u32, @bitCast(self));
}
};
};
pub const ctrlReg = struct {
pub const reg = @as(*volatile u32, @ptrFromInt(pl011Cfg.base_address + 0x030));
pub const RegAttr = packed struct {
padding: u16 = 0,
cts_hwflow_ctrl_en: bool = false,
rts_hwflow_ctrl_en: bool = false,
out2: bool = false,
ou1: bool = false,
req_to_send: bool = false,
data_tx_ready: bool = false,
rec_enable: bool = false,
tx_enable: bool = false,
loopback_enable: bool = false,
reserved: u4 = 0,
sir_low_power_irda_mode: bool = false,
sir_enable: bool = false,
uart_enable: bool = false,
pub fn asInt(self: RegAttr) u32 {
return @as(u32, @bitCast(self));
}
};
};
pub const intMaskSetClearReg = @as(*volatile u32, @ptrFromInt(pl011Cfg.base_address + 0x038));
pub const dmaCtrlReg = @as(*volatile u32, @ptrFromInt(pl011Cfg.base_address + 0x048));
};
fn waitForTransmissionEnd() void {
// 1 << 3 -> busy bit in flagReg reg
while (RegMap.flagReg.* & @as(u32, 1 << 3) != 0) {}
}
// used for fracBaudRateReg, intBaudRateReg config registers
fn calcClockDevisor() struct { integer: u16, fraction: u6 } {
const div: u32 = 4 * pl011Cfg.base_clock / pl011Cfg.baudrate;
return .{ .integer = (div >> 6) & 0xffff, .fraction = div & 0x3f };
}
pub fn init() void {
// disable uart
RegMap.ctrlReg.reg.* = (RegMap.ctrlReg.RegAttr{ .uart_enable = false }).asInt();
waitForTransmissionEnd();
// flush fifo
RegMap.lineCtrlReg.reg.* = RegMap.lineCtrlReg.reg.* & ~@as(u32, 1 << 4);
// calc int and fraction part of the clock devisor and write it to regs
const dev = calcClockDevisor();
RegMap.intBaudRateReg.* = dev.integer;
RegMap.fracBaudRateReg.* = dev.fraction;
var two_stop_bits = false;
if (pl011Cfg.stop_bits == 2)
two_stop_bits = true;
if (pl011Cfg.data_bits != 8)
@compileError("pl011 only supports 8 bit wlen");
RegMap.lineCtrlReg.reg.* = (RegMap.lineCtrlReg.RegAttr{
.two_stop_bits_select = two_stop_bits,
.tx_word_len = 3,
.enable_fifo = false,
}).asInt();
// Mask all interrupts by setting corresponding bits to 1
RegMap.intMaskSetClearReg.* = 0x7ff;
// Disable DMA by setting all bits to 0
RegMap.dmaCtrlReg.* = 0;
// enabling only tx (has to happen first according to docs)
RegMap.ctrlReg.reg.* = (RegMap.ctrlReg.RegAttr{ .tx_enable = true }).asInt();
RegMap.ctrlReg.reg.* = (RegMap.ctrlReg.RegAttr{ .tx_enable = true, .uart_enable = true }).asInt();
}
pub fn write(data: []const u8) void {
waitForTransmissionEnd();
for (data) |ch| {
RegMap.dataReg.* = ch;
waitForTransmissionEnd();
}
}
};
}
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/periph/periph.zig | pub const Pl011 = @import("pl011.zig").Pl011;
pub const uart = @import("uart.zig");
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/periph/uart.zig | const std = @import("std");
const board = @import("board");
const AddrSpace = board.boardConfig.AddrSpace;
pub fn UartWriter(comptime addr_space: AddrSpace) type {
const pl011 = @import("pl011.zig").Pl011(addr_space);
return struct {
const Self = @This();
pub const Writer = std.io.Writer(*Self, error{}, appendWrite);
pub fn writer(self: *Self) Writer {
return .{ .context = self };
}
/// Same as `append` except it returns the number of bytes written, which is always the same
/// as `m.len`. The purpose of this function existing is to match `std.io.Writer` API.
fn appendWrite(self: *Self, data: []const u8) error{}!usize {
_ = self;
pl011.write(data);
return data.len;
}
pub fn kprint(comptime print_string: []const u8, args: anytype) void {
var tempW: UartWriter(addr_space) = undefined;
std.fmt.format(tempW.writer(), print_string, args) catch |err| {
@panic(err);
};
}
};
}
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/bootloader/utils.zig | const kprint = @import("periph").uart.UartWriter(.ttbr0).kprint;
pub fn panic() noreturn {
kprint("[bootloader] panic \n", .{});
while (true) {}
}
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/bootloader/linker.ld | ENTRY(_start)
SECTIONS {
. = {@zig};
_bl_bin_start = .;
.text : ALIGN(16) {
*(.text.boot)
}
.exceptions : ALIGN(0x800) {
*(.text.exc_vec);
}
.rodata : ALIGN(0x8) {
*(.rodata);
*(.rodata.*);
}
.bootloader : ALIGN(16) {
*(.text.);
*(.text.*);
}
.got : {
*(.got.plt);
*(.got);
}
.bss : ALIGN(0x10) {
_bss_start = .;
*(.bss.*);
*(COMMON);
_bss_end = .;
}
.data : {
*(.data);
*(.data.*);
}
.bl_end (NOLOAD) : ALIGN(8) {
_bl_end = .;
}
} |
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/bootloader/bootloader.zig | const std = @import("std");
const alignForward = std.mem.alignForward;
const utils = @import("utils");
// bootloader specific
const board = @import("board");
const PeriphConfig = board.PeriphConfig(.ttbr0);
const bl_utils = @import("utils.zig");
const intHandle = @import("blIntHandler.zig");
const b_options = @import("build_options");
// general periphs
const periph = @import("periph");
// .ttbr0 arg sets the addresses value to either or user_, kernel_space
const pl011 = periph.Pl011(.ttbr0);
const kprint = periph.uart.UartWriter(.ttbr0).kprint;
const arm = @import("arm");
const gic = arm.gicv2.Gic(.ttbr0);
const ProccessorRegMap = arm.processor.ProccessorRegMap;
const mmu = arm.mmu;
const Granule = board.boardConfig.Granule;
const GranuleParams = board.boardConfig.GranuleParams;
const TransLvl = board.boardConfig.TransLvl;
const kernel_bin = @embedFile("bins/kernel.bin");
// note: when bl_main gets too big(instruction mem wise), the exception vector table could be pushed too far up and potentially not be read!
// todo => remember => callconv(.Naked) removed...
export fn bl_main() linksection(".text.boot") noreturn {
// setting stack pointer to writable memory (ram (userspace))
// using userspace as stack, incase the bootloader is located in rom
const user_space_start = blk: {
var user_space_start_tmp = (board.config.mem.bl_load_addr orelse 0) + (board.config.mem.rom_size orelse 0) + board.config.mem.kernel_space_size;
// increasing user_space_start_tmp by stack_size so that later writes to the user_space don't overwrite the bl's stack
user_space_start_tmp += board.config.mem.bl_stack_size;
const aligned_userspace_addr = alignForward(usize, user_space_start_tmp, 16);
ProccessorRegMap.setSp(aligned_userspace_addr);
break :blk user_space_start_tmp;
};
const _bl_bin_end: usize = @intFromPtr(@extern(?*u8, .{ .name = "_bl_end" }) orelse {
kprint("[panic] error reading _bl_end label\n", .{});
bl_utils.panic();
});
var boot_without_rom_new_kernel_loc: usize = alignForward(usize, _bl_bin_end, 4096);
if (board.config.mem.bl_load_addr == null) boot_without_rom_new_kernel_loc = 0;
// mmu configuration...
{
const ttbr1 = blk: {
const page_table = mmu.PageTable(board.config.mem.ram_size, Granule.Fourk) catch |e| {
kprint("[panic] Page table init error: {s}\n", .{@errorName(e)});
bl_utils.panic();
};
// writing page dirs to userspace in ram. Writing to userspace because it would be overwritten in kernel space, when copying
// the kernel. Additionally, on mmu turn on, the mmu would try to read from the page tables without mmu kernel space identifier bits on
const ttbr1_mem = @as(*volatile [page_table.totaPageTableSize]usize, @ptrFromInt(alignForward(usize, user_space_start, Granule.Fourk.page_size)));
// mapping general kernel mem (inlcuding device base)
var ttbr1_write = page_table.init(ttbr1_mem, 0) catch |e| {
kprint("[panic] Page table init error: {s}\n", .{@errorName(e)});
bl_utils.panic();
};
// creating virtual address space for kernel
const kernel_mapping = mmu.Mapping{
.mem_size = board.config.mem.ram_size,
.pointing_addr_start = board.config.mem.ram_start_addr + boot_without_rom_new_kernel_loc,
.virt_addr_start = 0,
.granule = Granule.Fourk,
.addr_space = .ttbr1,
.flags_last_lvl = mmu.TableDescriptorAttr{ .accessPerm = .only_el1_read_write, .attrIndex = .mair0 },
.flags_non_last_lvl = mmu.TableDescriptorAttr{ .accessPerm = .only_el1_read_write },
};
ttbr1_write.mapMem(kernel_mapping) catch |e| {
kprint("[panic] Page table write error: {s}\n", .{@errorName(e)});
bl_utils.panic();
};
break :blk ttbr1_mem;
};
const ttbr0 = blk: {
// in case there is no rom(rom_size is equal to zero) and the kernel(and bl) are directly loaded to memory by some rom bootloader
// the ttbr0 memory is also identity mapped to the ram
const mapping_bl_phys_size: usize = (board.config.mem.rom_size orelse 0) + board.config.mem.ram_size;
const page_table = mmu.PageTable(mapping_bl_phys_size, Granule.FourkSection) catch |e| {
kprint("[panic] Page table init error: {s}\n", .{@errorName(e)});
bl_utils.panic();
};
var ttbr0_addr = user_space_start + (ttbr1.len * @sizeOf(usize));
ttbr0_addr = alignForward(usize, ttbr0_addr, Granule.Fourk.page_size);
const ttbr0_mem = @as(*volatile [page_table.totaPageTableSize]usize, @ptrFromInt(ttbr0_addr));
// MMU page dir config
// identity mapped memory for bootloader and kernel control handover!
var ttbr0_write = page_table.init(ttbr0_mem, 0) catch |e| {
kprint("[panic] Page table init error: {s}\n", .{@errorName(e)});
bl_utils.panic();
};
// writing to _id_mapped_dir(label) page table and creating new
// identity mapped memory for bootloader to kernel transfer
const bootloader_mapping = mmu.Mapping{
.mem_size = mapping_bl_phys_size,
.pointing_addr_start = 0,
.virt_addr_start = 0,
.granule = Granule.FourkSection,
.addr_space = .ttbr0,
.flags_last_lvl = mmu.TableDescriptorAttr{ .accessPerm = .only_el1_read_write, .attrIndex = .mair0 },
.flags_non_last_lvl = mmu.TableDescriptorAttr{ .accessPerm = .only_el1_read_write },
};
ttbr0_write.mapMem(bootloader_mapping) catch |e| {
kprint("[panic] Page table write error: {s}\n", .{@errorName(e)});
bl_utils.panic();
};
break :blk ttbr0_mem;
};
// kprint("ttbr1: 0x{x} \n", .{@ptrToInt(ttbr1)});
// kprint("ttbr0: 0x{x} \n", .{@ptrToInt(ttbr0)});
// updating page dirs
ProccessorRegMap.setTTBR0(@intFromPtr(ttbr0));
ProccessorRegMap.setTTBR1(@intFromPtr(ttbr1));
ProccessorRegMap.TcrReg.setTcrEl(.el1, (ProccessorRegMap.TcrReg{ .t0sz = 25, .t1sz = 25, .tg0 = 0, .tg1 = 0 }).asInt());
// attr0 is normal mem, not cachable
ProccessorRegMap.MairReg.setMairEl(.el1, (ProccessorRegMap.MairReg{ .attr0 = 0xFF, .attr1 = 0x0, .attr2 = 0x0, .attr3 = 0x0, .attr4 = 0x0 }).asInt());
ProccessorRegMap.invalidateMmuTlbEl1();
ProccessorRegMap.invalidateCache();
ProccessorRegMap.isb();
ProccessorRegMap.dsb();
kprint("[bootloader] enabling mmu... \n", .{});
ProccessorRegMap.enableMmu(.el1);
ProccessorRegMap.nop();
ProccessorRegMap.nop();
}
// GIC Init
if (std.mem.eql(u8, board.config.board_name, "qemuVirt")) {
gic.init() catch |e| {
kprint("[panic] GIC init error: {s} \n", .{@errorName(e)});
bl_utils.panic();
};
pl011.init();
}
const current_el = ProccessorRegMap.getCurrentEl();
if (current_el != 1) {
kprint("[panic] el must be 1! (it's: {d})\n", .{current_el});
bl_utils.panic();
}
{
var kernel_target_loc: []u8 = undefined;
kernel_target_loc.ptr = @as([*]u8, @ptrFromInt(board.config.mem.va_start));
kernel_target_loc.len = kernel_bin.len;
kprint("[bootloader] Copying kernel to addr_space: 0x{x}, with size: {d} \n", .{ @intFromPtr(kernel_target_loc.ptr), kernel_target_loc.len });
std.mem.copy(u8, kernel_target_loc, kernel_bin);
const kernel_addr = @intFromPtr(kernel_target_loc.ptr);
const kernel_sp = blk: {
const aligned_ksize = alignForward(usize, kernel_target_loc.len, 0x8);
break :blk utils.toTtbr1(usize, aligned_ksize + board.config.mem.k_stack_size);
};
asm volatile (
\\mov sp, %[sp]
\\mov x0, %[boot_without_rom_new_kernel_loc]
\\br %[pc_addr]
:
: [sp] "r" (kernel_sp),
[boot_without_rom_new_kernel_loc] "r" (boot_without_rom_new_kernel_loc),
[pc_addr] "r" (kernel_addr),
);
}
while (true) {}
}
comptime {
@export(intHandle.trapHandler, .{ .name = "trapHandler", .linkage = .Strong });
}
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/bootloader/exc_vec.S | .section .text.exc_vec
.macro EXCEPTION_VECTOR int_type
// storing CpuContext src/arm/CpuContext.zig on stack
stp q1, q0, [sp, #-32]!
stp q3, q2, [sp, #-32]!
stp q5, q4, [sp, #-32]!
stp q7, q6, [sp, #-32]!
stp q9, q8, [sp, #-32]!
stp q11, q10, [sp, #-32]!
stp q13, q12, [sp, #-32]!
stp q15, q14, [sp, #-32]!
stp q17, q16, [sp, #-32]!
stp q19, q18, [sp, #-32]!
stp q21, q20, [sp, #-32]!
stp q23, q22, [sp, #-32]!
stp q25, q24, [sp, #-32]!
stp q27, q26, [sp, #-32]!
stp q29, q28, [sp, #-32]!
stp q31, q30, [sp, #-32]!
// gp regs
stp x1, x0, [sp, #-16]!
stp x3, x1, [sp, #-16]!
stp x5, x4, [sp, #-16]!
stp x7, x6, [sp, #-16]!
stp x9, x8, [sp, #-16]!
stp x11, x10, [sp, #-16]!
stp x13, x12, [sp, #-16]!
stp x15, x14, [sp, #-16]!
stp x17, x16, [sp, #-16]!
stp x19, x18, [sp, #-16]!
stp x21, x20, [sp, #-16]!
stp x23, x22, [sp, #-16]!
stp x25, x24, [sp, #-16]!
stp x27, x26, [sp, #-16]!
stp x29, x28, [sp, #-16]!
// sys regs
mov x1, sp
stp x1, x30, [sp, #-16]!
mov x0, fp
mrs x3, elr_el1
stp x3, x0, [sp, #-16]!
mrs x0, sp_el0
// debug regs
mrs x3, SPSel
stp x3, x0, [sp, #-16]!
mrs x0, far_el1
mrs x3, esr_el1
stp x0, x3, [sp, #-16]!
mrs x0, CurrentEL
lsr x0, x0, #2
stp xzr, x0, [sp, #-16]!
// end of CpuState stack store
// set stack as arg
mov x0, sp
ldr x1, #\int_type
bl trapHandler
// restoreContextFromStack are fns exported from CpuContext.zig
b _restoreContextWithoutSwitchFromSp
.endm
// https://developer.arm.com/documentation/100933/0100/AArch64-exception-vector-table
.globl _exception_vector_table
.balign 0x80
_exception_vector_table:
EXCEPTION_VECTOR el1Sp0Sync // el1_sp0_sync
.balign 0x80
EXCEPTION_VECTOR el1Sp0Irq // el1_sp0_irq
.balign 0x80
EXCEPTION_VECTOR el1Sp0Fiq // el1_sp0_fiq
.balign 0x80
EXCEPTION_VECTOR el1Sp0Err // el1_sp0_error
.balign 0x80
EXCEPTION_VECTOR el1Sync // el1Sync
.balign 0x80
EXCEPTION_VECTOR el1Irq // el1Irq
.balign 0x80
EXCEPTION_VECTOR el1Fiq // el1Fiq
.balign 0x80
EXCEPTION_VECTOR el1Err // el1Error
.balign 0x80
EXCEPTION_VECTOR el0Sync // el0_sync
.balign 0x80
EXCEPTION_VECTOR el0Irq // el0_irq
.balign 0x80
EXCEPTION_VECTOR el0Fiq // el0_fiq
.balign 0x80
EXCEPTION_VECTOR el0Err // el0_error
.balign 0x80
EXCEPTION_VECTOR el032Sync // el0_32_sync
.balign 0x80
EXCEPTION_VECTOR el032Irq // el0_32_irq
.balign 0x80
EXCEPTION_VECTOR el032Fiq // el0_32_fiq
.balign 0x80
EXCEPTION_VECTOR el032Err // el0_32_error
.balign 0x80 |
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/bootloader/blIntHandler.zig | const std = @import("std");
const bl_utils = @import("utils.zig");
const arm = @import("arm");
const ProccessorRegMap = arm.processor.ProccessorRegMap;
const CpuContext = arm.cpuContext.CpuContext;
const periph = @import("periph");
const kprint = periph.uart.UartWriter(.ttbr0).kprint;
const gic = arm.gicv2;
const timer = arm.timer;
pub const ExceptionClass = enum(u6) {
unknownReason = 0b000000,
trappedWF = 0b000001,
trappedMCR = 0b000011,
trappedMcrr = 0b000100,
trappedMCRWithAcc = 0b000101,
trappedLdcStcAcc = 0b000110,
sveAsmidFpAcc = 0b000111,
trappedLdStInst = 0b001010,
trappedMrrcWithAcc = 0b001100,
branchTargetExc = 0b001101,
illegalExecState = 0b001110,
svcInstExcAArch32 = 0b010001,
svcInstExAArch64 = 0b010101,
trappedMsrMrsSiAarch64 = 0b011000,
sveFuncTrappedAcc = 0b011001,
excFromPointerAuthInst = 0b011100,
instAbortFromLowerExcLvl = 0b100000,
instAbortTakenWithoutExcLvlChange = 0b100001,
pcAlignFaultExc = 0b100010,
dataAbortFromLowerExcLvl = 0b100100,
dataAbortWithoutExcLvlChange = 0b100101,
spAlignmentFaultExc = 0b100110,
trappedFpExcAarch32 = 0b101000,
trappedFpExcAarch64 = 0b101100,
brkPExcFromLowerExcLvl = 0b101111,
brkPExcWithoutExcLvlChg = 0b110001,
softwStepExcpFromLowerExcLvl = 0b110010,
softwStepExcTakenWithoutExcLvlChange = 0b110011,
watchPointExcpFromALowerExcLvl = 0b110100,
watchPointExcpWithoutTakenWithoutExcLvlChange = 0b110101,
bkptInstExecAarch32 = 0b111000,
bkptInstExecAarch64 = 0b111100,
};
pub fn trapHandler(temp_context: *CpuContext, tmp_int_type: usize) callconv(.C) noreturn {
const int_type = tmp_int_type;
const int_type_en = std.meta.intToEnum(gic.ExceptionType, int_type) catch {
kprint("intToEnum int_type failed \n", .{});
bl_utils.panic();
};
temp_context.int_type = int_type;
kprint("bl irqHandler \n", .{});
const iss = @as(u25, @truncate(temp_context.esr_el1));
const ifsc = @as(u6, @truncate(temp_context.esr_el1));
const il = @as(u1, @truncate(temp_context.esr_el1 >> 25));
const ec = @as(u6, @truncate(temp_context.esr_el1 >> 26));
const iss2 = @as(u5, @truncate(temp_context.esr_el1 >> 32));
_ = iss;
_ = iss2;
const ec_en = std.meta.intToEnum(ExceptionClass, ec) catch {
kprint("esp exception class not found \n", .{});
bl_utils.panic();
};
const ifsc_en = std.meta.intToEnum(ProccessorRegMap.Esr_el1.Ifsc, ifsc) catch {
kprint("esp exception class not found \n", .{});
bl_utils.panic();
};
kprint(".........sync exc............\n", .{});
kprint("Exception Class(from esp reg): {s} \n", .{@tagName(ec_en)});
kprint("IFC(from esp reg): {s} \n", .{@tagName(ifsc_en)});
kprint("- debug info: \n", .{});
kprint("Int Type: {s} \n", .{@tagName(int_type_en)});
kprint("el: {d} \n", .{temp_context.el});
kprint("esr_el1: 0x{x} \n", .{temp_context.esr_el1});
kprint("far_el1: 0x{x} \n", .{temp_context.far_el1});
kprint("elr_el1: 0x{x} \n", .{temp_context.elr_el1});
kprint("- sys regs: \n", .{});
kprint("sp: 0x{x} \n", .{temp_context.sp_el1});
kprint("sp_el0: 0x{x} \n", .{temp_context.sp_el0});
kprint("spSel: {d} \n", .{temp_context.sp_sel});
kprint("lr(x30): 0x{x} \n", .{temp_context.x30});
kprint("x0: 0x{x}, x1: 0x{x}, x2: 0x{x}, x3: 0x{x}, x4: 0x{x} \n", .{ temp_context.x0, temp_context.x1, temp_context.x2, temp_context.x3, temp_context.x4 });
kprint("x5: 0x{x}, x6: 0x{x}, x7: 0x{x}, x8: 0x{x}, x9: 0x{x} \n", .{ temp_context.x5, temp_context.x6, temp_context.x7, temp_context.x8, temp_context.x9 });
kprint("x10: 0x{x}, x11: 0x{x}, x12: 0x{x}, x13: 0x{x}, x14: 0x{x} \n", .{ temp_context.x10, temp_context.x11, temp_context.x12, temp_context.x13, temp_context.x14 });
kprint("x15: 0x{x}, x16: 0x{x}, x17: 0x{x}, x18: 0x{x}, x19: 0x{x} \n", .{ temp_context.x15, temp_context.x16, temp_context.x17, temp_context.x18, temp_context.x19 });
kprint("x20: 0x{x}, x21: 0x{x}, x22: 0x{x}, x23: 0x{x}, x24: 0x{x} \n", .{ temp_context.x20, temp_context.x21, temp_context.x22, temp_context.x23, temp_context.x24 });
kprint("x25: 0x{x}, x26: 0x{x}, x27: 0x{x}, x28: 0x{x}, x29: 0x{x} \n", .{ temp_context.x25, temp_context.x26, temp_context.x27, temp_context.x28, temp_context.x29 });
if (il == 1) {
kprint("32 bit instruction trapped \n", .{});
} else {
kprint("16 bit instruction trapped \n", .{});
}
kprint(".........sync temp_context............\n", .{});
bl_utils.panic();
}
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/kpi/timerKpi.zig | const std = @import("std");
const Scheduler = @import("sharedKernelServices").Scheduler;
const arm = @import("arm");
const CpuContext = arm.cpuContext.CpuContext;
// global user required since timer is handleTimerIrq is called from the exception vector table
extern var scheduler: *Scheduler;
pub fn TimerKpi(
comptime Context: type,
comptime TimerError: type,
comptime initTimer: fn (context: Context) TimerError!void,
comptime handleTimerTick: fn (context: Context) TimerError!void,
comptime timer_name: []const u8,
) type {
return struct {
const Self = @This();
pub const Error = TimerError;
context: Context,
timer_name: []const u8,
pub fn init(context: Context) Self {
return .{
.context = context,
.timer_name = timer_name,
};
}
pub fn initTimerDriver(self: Self) Error!void {
try initTimer(self.context);
}
pub fn timerTick(self: Self, irq_context: *CpuContext) Error!void {
try handleTimerTick(self.context);
scheduler.timerIntEvent(irq_context);
}
};
}
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/kpi/kpi.zig | pub const TimerKpi = @import("timerKpi.zig").TimerKpi;
pub const SecondaryInterruptControllerKpi = @import("secondaryInterruptControllerKpi.zig").SecondaryInterruptControllerKpi;
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/kpi/secondaryInterruptControllerKpi.zig | const std = @import("std");
const arm = @import("arm");
const cpuContext = arm.cpuContext;
pub fn SecondaryInterruptControllerKpi(
comptime Context: type,
comptime IcError: type,
comptime initIcDriver_: fn (context: Context) IcError!void,
comptime addIcHandler_: fn (context: Context, handler_fn: *const fn (cpu_context: *cpuContext.CpuContext) void) IcError!void,
comptime RegMap_: type,
) type {
return struct {
const Self = @This();
pub const Error = IcError;
pub const RegMap = RegMap_;
context: Context,
pub fn init(context: Context) Self {
return .{
.context = context,
};
}
pub fn initIcDriver(self: Self) Error!void {
try initIcDriver_(self.context);
}
pub fn addIcHandler(self: Self, handler_fn: *const fn (cpu_context: *cpuContext.CpuContext) void) Error!void {
try addIcHandler_(self.context, handler_fn);
}
};
}
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/boards/qemuVirt.zig | pub const boardConfig = @import("configTemplates").boardConfigTemplate;
const kpi = @import("kpi");
const timerDriver = @import("timerDriver");
const genericTimer = timerDriver.genericTimer;
// mmu starts at lvl1 for which 0xFFFFFF8000000000 is the lowest possible va
const vaStart: usize = 0xFFFFFF8000000000;
pub const config = boardConfig.BoardConfig{
.board_name = "qemuVirt",
.mem = boardConfig.BoardConfig.BoardMemLayout{
.va_start = vaStart,
.bl_stack_size = 0x10000,
.k_stack_size = 0x10000,
.app_stack_size = 0x20000,
.app_vm_mem_size = 0x1000000,
.rom_size = 0x40000000,
// since the bootloader is loaded at 0x no bl_load_addr is required
// (currently only supported for boot without rom)
.bl_load_addr = null,
// according to qemu docs ram starts at 1gib
.ram_start_addr = 0x40000000,
// the ram_size needs to be greater or equal to: kernel_space_size + user_space_size
.ram_size = 0x80000000,
// the kernel space starts at ram_start or bl_load_addr
.kernel_space_size = 0x60000000,
.user_space_size = 0x20000000,
.va_kernel_space_gran = boardConfig.Granule.Fourk,
.va_kernel_space_page_table_capacity = 0x40000000,
.va_user_space_gran = boardConfig.Granule.Fourk,
.va_user_space_page_table_capacity = 0x40000000,
.storage_start_addr = 0,
.storage_size = 0,
},
.static_memory_reserves = boardConfig.BoardConfig.StaticMemoryReserves{
.ksemaphore_max_process_in_queue = 1000,
.semaphore_max_process_in_queue = 1000,
.mutex_max_process_in_queue = 1000,
.topics_max_process_in_queue = 1000,
},
.scheduler_freq_in_hertz = 250,
};
pub const GenericTimerType = genericTimer.GenericTimer(null, config.scheduler_freq_in_hertz);
var genericTimerInst = GenericTimerType.init();
pub const GenericTimerKpiType = kpi.TimerKpi(*GenericTimerType, GenericTimerType.Error, GenericTimerType.setupGt, GenericTimerType.timerInt, GenericTimerType.timer_name);
pub const driver = boardConfig.Driver(GenericTimerKpiType, null){
.timerDriver = GenericTimerKpiType.init(&genericTimerInst),
.secondaryInterruptConrtollerDriver = null,
};
pub fn PeriphConfig(comptime addr_space: boardConfig.AddrSpace) type {
const new_ttbr1_device_base_ = 0x30000000;
comptime var device_base_mapping_bare: usize = 0x8000000;
// in ttbr1 all periph base is mapped to 0x40000000
if (addr_space.isKernelSpace()) device_base_mapping_bare = config.mem.va_start + new_ttbr1_device_base_;
return struct {
pub const device_base_size: usize = 0xA000000;
pub const device_base: usize = device_base_mapping_bare;
pub const new_ttbr1_device_base = new_ttbr1_device_base_;
pub const Pl011 = struct {
pub const base_address: u64 = device_base + 0x1000000;
pub const base_clock: u64 = 0x16e3600;
// 9600 slower baud
pub const baudrate: u32 = 115200;
pub const data_bits: u32 = 8;
pub const stop_bits: u32 = 1;
};
pub const GicV2 = struct {
pub const base_address: u64 = device_base + 0;
};
};
}
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/boards/raspi3b.zig | pub const boardConfig = @import("configTemplates").boardConfigTemplate;
const kpi = @import("kpi");
const timerDriver = @import("timerDriver");
const bcm2835Timer = timerDriver.bcm2835Timer;
const genericTimer = timerDriver.genericTimer;
const bcm2835IntController = @import("interruptControllerDriver").bcm2835InterruptController;
// mmu starts at lvl1 for which 0xFFFFFF8000000000 is the lowest possible va
const vaStart: usize = 0xFFFFFF8000000000;
pub const config = boardConfig.BoardConfig{
.board_name = "raspi3b",
.mem = .{
.va_start = vaStart,
.bl_stack_size = 0x10000,
.k_stack_size = 0x10000,
.app_stack_size = 0x20000,
.app_vm_mem_size = 0x1000000,
.rom_size = null,
.bl_load_addr = 0x80000,
// the raspberries addressable memory is all ram
.ram_start_addr = 0,
// the ram_size needs to be greater or equal to: kernel_space_size + user_space_size + (bl_load_addr or rom_size)
.ram_size = 0x40000000,
.kernel_space_size = 0x20000000,
.user_space_size = 0x20000000,
// has to be Fourk since without a rom the kernel is positioned at a (addr % 2mb) != 0, so a 4kb granule is required
.va_kernel_space_gran = boardConfig.Granule.Fourk,
.va_kernel_space_page_table_capacity = 0x40000000,
.va_user_space_gran = boardConfig.Granule.Fourk,
.va_user_space_page_table_capacity = 0x40000000,
.storage_start_addr = 0,
.storage_size = 0,
},
.static_memory_reserves = boardConfig.BoardConfig.StaticMemoryReserves{
.ksemaphore_max_process_in_queue = 1000,
.semaphore_max_process_in_queue = 1000,
.mutex_max_process_in_queue = 1000,
.topics_max_process_in_queue = 1000,
},
.scheduler_freq_in_hertz = 250,
};
// --- driver ---
pub const GenericTimerType = genericTimer.GenericTimer(null, config.scheduler_freq_in_hertz);
var genericTimerInst = GenericTimerType.init();
pub const Bcm2835TimerType = bcm2835Timer.Bcm2835Timer(PeriphConfig(.ttbr1).Timer.base_address, config.scheduler_freq_in_hertz);
var bcm2835TimerInst = Bcm2835TimerType.init();
pub const GenericTimerKpiType = kpi.TimerKpi(*GenericTimerType, GenericTimerType.Error, GenericTimerType.setupGt, GenericTimerType.timerInt, GenericTimerType.timer_name);
pub const Bcm2835TimerKpiType = kpi.TimerKpi(*Bcm2835TimerType, Bcm2835TimerType.Error, Bcm2835TimerType.initTimer, Bcm2835TimerType.handleTimerIrq, Bcm2835TimerType.timer_name);
// interrupt controller
const Bcm2835InterruptControllerType = bcm2835IntController.InterruptController(PeriphConfig(.ttbr1).InterruptController.base_address);
pub const SecondaryInterruptControllerKpiType = kpi.SecondaryInterruptControllerKpi(*Bcm2835InterruptControllerType, Bcm2835InterruptControllerType.Error, Bcm2835InterruptControllerType.initIc, Bcm2835InterruptControllerType.addIcHandler, Bcm2835InterruptControllerType.RegMap);
var secondaryInterruptControllerInst = Bcm2835InterruptControllerType.init();
pub const driver = boardConfig.Driver(GenericTimerKpiType, SecondaryInterruptControllerKpiType){
.timerDriver = GenericTimerKpiType.init(&genericTimerInst),
// .timerDriver = Bcm2835TimerKpiType.init(&bcm2835TimerInst),
.secondaryInterruptConrtollerDriver = SecondaryInterruptControllerKpiType.init(&secondaryInterruptControllerInst),
};
// -- driver --
pub fn PeriphConfig(comptime addr_space: boardConfig.AddrSpace) type {
const new_ttbr1_device_base_ = 0x30000000;
const device_base_mapping_bare: usize = 0x3f000000;
comptime var device_base_mapping_new: usize = undefined;
if (addr_space.isKernelSpace()) {
device_base_mapping_new = config.mem.va_start + new_ttbr1_device_base_;
} else device_base_mapping_new = device_base_mapping_bare;
return struct {
pub const device_base_size: usize = 0xA000000;
pub const new_ttbr1_device_base: usize = new_ttbr1_device_base_;
pub const device_base: usize = device_base_mapping_new;
pub const Pl011 = struct {
pub const base_address: u64 = device_base + 0x201000;
// config
pub const base_clock: u64 = 0x124f800;
// 9600 slower baud
pub const baudrate: u32 = 115200;
pub const data_bits: u32 = 8;
pub const stop_bits: u32 = 1;
};
pub const Timer = struct {
pub const base_address: usize = device_base + 0x00003000;
};
pub const ArmGenericTimer = struct {
pub const base_address: usize = device_base + 0x1000040;
};
pub const InterruptController = struct {
pub const base_address: usize = device_base + 0x0000b200;
};
pub const GicV2 = struct {
pub const base_address: u64 = device_base + 0;
};
};
}
|
0 | repos/MinimalRoboticsPlatform/src/boards/drivers | repos/MinimalRoboticsPlatform/src/boards/drivers/interruptController/interruptController.zig | pub const bcm2835InterruptController = @import("bcm2835InterruptController.zig");
|
0 | repos/MinimalRoboticsPlatform/src/boards/drivers | repos/MinimalRoboticsPlatform/src/boards/drivers/interruptController/bcm2835InterruptController.zig | const std = @import("std");
const board = @import("board");
const arm = @import("arm");
const cpuContext = arm.cpuContext;
pub fn InterruptController(comptime base_address: usize) type {
// const base_address = @import("board").PeriphConfig(addr_space).InterruptController.base_address;
return struct {
const Self = @This();
pub const Error = anyerror;
pub const RegMap = struct {
pub const pendingBasic = @as(*volatile u32, @ptrFromInt(base_address + 0));
pub const pendingIrq1 = @as(*volatile u32, @ptrFromInt(base_address + 0x4));
pub const pendingIrq2 = @as(*volatile u32, @ptrFromInt(base_address + 0x8));
pub const enableIrq1 = @as(*volatile u32, @ptrFromInt(base_address + 0x10));
pub const enableIrq2 = @as(*volatile u32, @ptrFromInt(base_address + 0x14));
pub const enableIrqBasic = @as(*volatile u32, @ptrFromInt(base_address + 0x18));
};
handler_fn: ?*const fn (cpu_context: *cpuContext.CpuContext) void,
pub fn init() Self {
return .{
.handler_fn = null,
};
}
pub fn initIc(self: *Self) Error!void {
_ = self;
// enabling all irq types
// enalbles system timer
RegMap.enableIrq1.* = 1 << 1;
// RegMap.enableIrq2.* = 1 << 1;
// RegMap.enableIrqBasic.* = 1 << 1;
}
pub fn addIcHandler(self: *Self, handler_fn: *const fn (cpu_context: *cpuContext.CpuContext) void) Error!void {
self.handler_fn = handler_fn;
}
};
}
|
0 | repos/MinimalRoboticsPlatform/src/boards/drivers | repos/MinimalRoboticsPlatform/src/boards/drivers/bootInit/raspi3b_boot.S | .section ".text.boot"
.equ AArch64_EL1_SP1, 0x05 // EL1h
// how to get from el3 to el1 is described here: https://developer.arm.com/documentation/102437/0100/Changing-Exception-levels
.globl _start
_start:
// checking for secure state
mrs x1, scr_el3
tbnz x1, 0, proc_hang
mrs x0, mpidr_el1
and x0, x0,#0xFF // Check processor id
cbz x0, master // Hang for all non-primary CPU
b proc_hang
el1_entry_aarch64:
ldr x0, = _exception_vector_table
msr vbar_el1, x0
isb
// Enable FP/SIMD for el1
mov x0, #3 << 20
msr cpacr_el1, x0
// clear bss section
adr x0, _bss_start
adr x1, _bss_end
sub x1, x1, x0
bl memzero
isb
bl bl_main
master:
// disabling mmu
mov x1, #0x0
msr sctlr_el1, x1
isb
// Configure SCR_EL3
// -----------------dd
mov w1, #0 // Initial value of register is unknown
orr w1, w1, #(1 << 11) // set ST bit (disable trapping of timer control registers)
orr w1, w1, #(1 << 10) // set RW bit (next lower EL in aarch64)
// orr w1, w1, #(1 << 3) // Set EA bit (SError routed to EL3)
// orr w1, w1, #(1 << 2) // Set FIQ bit (FIQs routed to EL3)
// orr w1, w1, #(1 << 1) // Set IRQ bit (IRQs routed to EL3)
msr SCR_EL3, x1
// Initialize SCTLR_EL1
// --------------------
// SCTLR_EL1 has an unknown reset value and must be configured
// before we can enter EL1
msr SCTLR_EL1, xzr
ldr x0, =el1_entry_aarch64
ldr x1, =AArch64_EL1_SP1
msr ELR_EL3, x0 // where to branch to when exception completes
msr SPSR_EL3, x1 // set the program state for this point to a known value
eret
proc_hang:
b proc_hang
.globl memzero
memzero:
str xzr, [x0], #8
subs x1, x1, #8
b.gt memzero
br lr
|
0 | repos/MinimalRoboticsPlatform/src/boards/drivers | repos/MinimalRoboticsPlatform/src/boards/drivers/bootInit/qemuVirt_boot.S | .section ".text.boot"
.globl _start
_start:
mrs x0, mpidr_el1
and x0, x0, #0xFF // Check processor id
cbz x0, master // Hang for all non-primary CPU
// mov w1, #0
// orr w1, w1, #(1 << 3)
// orr w1, w1, #(1 << 4)
// orr w1, w1, #(1 << 5)
// msr HCR_EL2, x1
b proc_hang
// virt does directly boot to el1 on startup
master:
// setting up vector table (https://github.com/Xilinx/embeddedsw/blob/master/lib/bsp/standalone/src/arm/ARMv8/64bit/armclang/boot.S)
ldr x0, =_exception_vector_table
msr vbar_el1, x0
isb
// disabling mmu
mov x1, #0x0
msr sctlr_el1, x1
isb
// Enable FP/SIMD for el1
mov x0, #3 << 20
msr cpacr_el1, x0
// clear bss section
adr x0, _bss_start
adr x1, _bss_end
sub x1, x1, x0
bl memzero
isb
bl bl_main
proc_hang:
b proc_hang
.globl memzero
memzero:
str xzr, [x0], #8
subs x1, x1, #8
b.gt memzero
br lr
|
0 | repos/MinimalRoboticsPlatform/src/boards/drivers | repos/MinimalRoboticsPlatform/src/boards/drivers/timer/timer.zig | pub const bcm2835Timer = @import("bcm2835Timer.zig");
pub const genericTimer = @import("genericTimer.zig");
|
0 | repos/MinimalRoboticsPlatform/src/boards/drivers | repos/MinimalRoboticsPlatform/src/boards/drivers/timer/genericTimer.zig | const std = @import("std");
const utils = @import("utils");
const periph = @import("periph");
const kprint = periph.uart.UartWriter(.ttbr1).kprint;
pub fn GenericTimer(comptime base_address: ?usize, comptime scheduler_freq_in_hertz: usize) type {
_ = base_address;
return struct {
const Self = @This();
pub const Error = anyerror;
pub const timer_name = "arm_gt";
timerVal: usize,
pub fn init() Self {
return .{
.timerVal = 0,
};
}
pub fn getFreq() usize {
return asm ("mrs %[curr], CNTFRQ_EL0"
: [curr] "=r" (-> usize),
);
}
// initialize gic controller
pub fn setupGt(self: *Self) !void {
const cnt_freq = getFreq();
const expire_count = utils.calcTicksFromHertz(cnt_freq, scheduler_freq_in_hertz);
self.timerVal = expire_count;
asm volatile (
\\msr CNTP_TVAL_EL0, %[cval]
\\mov x0, 1
\\msr CNTP_CTL_EL0, x0
:
: [cval] "r" (self.timerVal),
: "x0"
);
}
pub fn timerInt(self: *Self) !void {
asm volatile (
\\msr CNTP_TVAL_EL0, %[cval]
\\mov x0, 1
\\msr CNTP_CTL_EL0, x0
:
: [cval] "r" (self.timerVal),
: "x0"
);
}
pub fn isEnabled(self: *Self) !bool {
_ = self;
const icprendr: u64 = asm ("mrs %[curr], CNTP_CTL_EL0"
: [curr] "=r" (-> u64),
);
if (icprendr & (1 << 0) != 0) {
return true;
}
// kprint("is pending {b} \n", .{icprendr});
return false;
}
};
}
|
0 | repos/MinimalRoboticsPlatform/src/boards/drivers | repos/MinimalRoboticsPlatform/src/boards/drivers/timer/bcm2835Timer.zig | const utils = @import("utils");
const std = @import("std");
pub fn Bcm2835Timer(comptime base_address: ?usize, comptime scheduler_freq_in_hertz: usize) type {
return struct {
const Self = @This();
pub const Error = anyerror;
pub const timer_name = "bcm2835_timer";
// raspberry 3b available timers: system timer (this one), arm timer, free runnning timer
// raspberry system timer frequency is 1 Mhz
var cnt_freq: u32 = 1000000;
var increasePerTick: u32 = 0;
pub const RegMap = struct {
pub const timerCs = @as(*volatile u32, @ptrFromInt(base_address.? + 0x0));
pub const timerLo = @as(*volatile u32, @ptrFromInt(base_address.? + 0x4));
pub const timerHi = @as(*volatile u32, @ptrFromInt(base_address.? + 0x8));
pub const timerC0 = @as(*volatile u32, @ptrFromInt(base_address.? + 0xc));
pub const timerC1 = @as(*volatile u32, @ptrFromInt(base_address.? + 0x10));
pub const timerClo = @as(*volatile u32, @ptrFromInt(base_address.? + 0x4));
};
// address values
pub const RegValues = struct {
// System Timer Controll State irq clear vals
pub const timerCsM0: u32 = 1 << 0;
pub const timerCsM1: u32 = 1 << 1;
pub const timerCsM2: u32 = 1 << 2;
pub const timerCsM3: u32 = 1 << 3;
};
timerVal: u32,
initialTimerHi: u32,
pub fn init() Self {
return .{
.timerVal = 0,
.initialTimerHi = 0,
};
}
pub fn initTimer(self: *Self) Error!void {
self.initialTimerHi = RegMap.timerHi.*;
self.timerVal = RegMap.timerLo.*;
increasePerTick = @as(u32, @truncate(utils.calcTicksFromHertz(cnt_freq, scheduler_freq_in_hertz)));
self.timerVal += increasePerTick;
RegMap.timerC1.* = self.timerVal;
}
// the qemu system timer is weird. It only triggers an interrupt if timerC1 is == timerLo instead of timerC1 is <= timerLo.
// Qemu devs stated that this is intended and what the documentation is saying, but are also doubting that this is the physical bcm2835 implementation
// more on that issue here: https://gitlab.com/qemu-project/qemu/-/issues/1651
// also I'm unsure how overflows are handled since it's not described in the docs properly
pub fn handleTimerIrq(self: *Self) Error!void {
self.timerVal = RegMap.timerLo.* + increasePerTick;
if (self.initialTimerHi != RegMap.timerHi.*) {
self.timerVal = RegMap.timerLo.*;
self.timerVal += increasePerTick;
self.initialTimerHi = RegMap.timerHi.*;
}
RegMap.timerC1.* = self.timerVal;
RegMap.timerCs.* = RegMap.timerCs.* | RegValues.timerCsM1;
}
pub fn isEnabled(self: *Self) !bool {
_ = self;
if (RegMap.timerCs.* & RegValues.timerCsM1 != 0) {
return true;
}
return false;
}
};
}
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/appLib/utils.zig | const std = @import("std");
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/appLib/Semaphore.zig | const std = @import("std");
const board = @import("board");
const sysCalls = @import("userSysCallInterface.zig");
const kprint = sysCalls.SysCallPrint.kprint;
// max_process_waiting defines how many processes can be put into the waiting queue
pub fn Semaphore(comptime max_process_waiting: ?usize) type {
const max_process_waiting_queue = max_process_waiting orelse board.config.static_memory_reserves.semaphore_max_process_in_queue;
return struct {
const Self = @This();
const Error = error{
OutOfStaticMem,
};
waiting_processes: [max_process_waiting_queue]?u16,
i: isize,
locked_tasks_index: u16,
pub fn init(s: isize) Self {
return .{
.waiting_processes = [_]?u16{0} ** max_process_waiting_queue,
.locked_tasks_index = 0,
.i = s,
};
}
pub fn wait(self: *Self, halting_pid: ?u16) !void {
try sysCalls.increaseCurrTaskPreemptCounter();
var to_halt_proc: u16 = undefined;
if (halting_pid == null) to_halt_proc = (try sysCalls.getPid()) else to_halt_proc = halting_pid.?;
if (self.i < 1) {
self.locked_tasks_index += 1;
// kprint("ERR: {d} > {d}", .{ self.locked_tasks_index, self.waiting_processes.len });
if (self.waiting_processes.len > self.locked_tasks_index) return Error.OutOfStaticMem;
self.waiting_processes[self.locked_tasks_index] = to_halt_proc;
try sysCalls.haltProcess(to_halt_proc);
}
self.i -= 1;
}
pub fn signal(self: *Self) !void {
if (self.i < 1) {
if (self.waiting_processes[self.locked_tasks_index]) |locked_pid| {
self.locked_tasks_index -= 1;
try sysCalls.continueProcess(locked_pid);
}
self.i += 1;
}
try sysCalls.decreaseCurrTaskPreemptCounter();
}
};
}
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/appLib/SharedMemTopicsInterface.zig | const sharedKernelServices = @import("sharedKernelServices");
const env = @import("environment");
const std = @import("std");
const utils = @import("utils");
const board = @import("board");
const Semaphore = @import("Semaphore.zig");
const sysCalls = @import("userSysCallInterface.zig");
const kprint = sysCalls.SysCallPrint.kprint;
const alignForward = std.mem.alignForward;
const Topic = @import("sharedServices").Topic(Semaphore);
pub const SharedMemTopicsInterface = struct {
const Error = error{
TopicIdNotFound,
StatusInterfaceMissmatch,
};
topics: [env.env_config.countTopics()]Topic,
mem_pool: []u8,
pub fn init() !SharedMemTopicsInterface {
var topics = [_]Topic{undefined} ** env.env_config.countTopics();
var accumulatedTopicsBuffSize: usize = 0;
for (&env.env_config.status_control) |*status_control_conf| {
if (status_control_conf.*.status_type == .topic) {
accumulatedTopicsBuffSize += status_control_conf.topic_conf.?.buffer_size + @sizeOf(usize);
}
}
const pages_req = (try std.math.mod(usize, alignForward(usize, accumulatedTopicsBuffSize, 8), board.config.mem.va_user_space_gran.page_size)) + 1;
var fixedTopicMemPoolInterface: []u8 = undefined;
fixedTopicMemPoolInterface.ptr = @as([*]u8, @ptrFromInt(0x20000000));
fixedTopicMemPoolInterface.len = pages_req * board.config.mem.va_user_space_gran.page_size;
var used_topics_mem: usize = 0;
var i: usize = 0;
for (&env.env_config.status_control) |*status_control_conf| {
if (status_control_conf.*.status_type == .topic) {
const topic_read_write_buff_ptr = @as(*volatile usize, @ptrFromInt(@intFromPtr(fixedTopicMemPoolInterface.ptr) + used_topics_mem));
topic_read_write_buff_ptr.* = 0;
// + @sizeOf(usize) bytes for the buff_state
topics[i] = Topic.init(fixedTopicMemPoolInterface[used_topics_mem + @sizeOf(usize) .. used_topics_mem + status_control_conf.topic_conf.?.buffer_size], topic_read_write_buff_ptr, status_control_conf.id, status_control_conf.topic_conf.?.buffer_type);
used_topics_mem += status_control_conf.topic_conf.?.buffer_size;
i += 1;
}
}
return .{
.topics = topics,
.mem_pool = fixedTopicMemPoolInterface,
};
}
pub fn read(self: *SharedMemTopicsInterface, comptime name: []const u8, ret_buff: []u8) !usize {
const status = try env.env_config.getStatusInfo(name);
if (status.type != null) return Error.StatusInterfaceMissmatch;
if (self.findTopicById(status.id)) |index| {
return self.topics[index].read(ret_buff);
} else return Error.TopicIdNotFound;
}
pub fn write(self: *SharedMemTopicsInterface, comptime name: []const u8, data: []u8) !usize {
const status = try env.env_config.getStatusInfo(name);
if (status.type != null) return Error.StatusInterfaceMissmatch;
if (self.findTopicById(status.id)) |index| {
return self.topics[index].write(data);
} else return Error.TopicIdNotFound;
}
// returns index
fn findTopicById(self: *SharedMemTopicsInterface, id: usize) ?usize {
for (&self.topics, 0..) |*topic, i| {
if (topic.id == id) return i;
}
return null;
}
};
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/appLib/appLib.zig | pub const AppAllocator = @import("AppAllocator.zig").AppAllocator;
pub const sysCalls = @import("userSysCallInterface.zig");
pub const Semaphore = @import("Semaphore.zig").Semaphore;
pub const Mutex = @import("Mutex.zig").Mutex;
pub const SharedMemTopicsInterface = @import("SharedMemTopicsInterface.zig").SharedMemTopicsInterface;
pub const utils = @import("utils.zig");
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/appLib/Mutex.zig | const std = @import("std");
const board = @import("board");
const sysCalls = @import("userSysCallInterface.zig");
const kprint = sysCalls.SysCallPrint.kprint;
pub const Mutex = struct {
const Error = error{
OutOfStaticMem,
};
waiting_processes: [board.config.static_memory_reserves.mutex_max_process_in_queue]u16,
last_waiting_proc_index: usize,
curr_lock_owner_pid: usize,
locked: std.atomic.Atomic(bool),
pub fn init() Mutex {
return .{
.waiting_processes = [_]u16{0} ** board.config.static_memory_reserves.mutex_max_process_in_queue,
.last_waiting_proc_index = 0,
.curr_lock_owner_pid = 0,
.locked = std.atomic.Atomic(bool).init(false),
};
}
pub fn lock(self: *Mutex) !void {
sysCalls.increaseCurrTaskPreemptCounter();
const my_pid = sysCalls.getPid();
if (self.locked.load(.Unordered)) {
if (self.last_waiting_proc_index > self.waiting_processes.len) return Error.OutOfStaticMem;
sysCalls.haltProcess(my_pid);
self.waiting_processes[self.last_waiting_proc_index] = my_pid;
self.last_waiting_proc_index += 1;
}
self.curr_lock_owner_pid = my_pid;
self.locked.store(true, .Unordered);
}
pub fn unlock(self: *Mutex) void {
if (self.locked.load(.Unordered) and self.last_waiting_proc_index > 0 and self.curr_lock_owner_pid == sysCalls.getPid()) {
sysCalls.continueProcess(self.waiting_processes[self.last_waiting_proc_index]);
self.curr_lock_owner_pid = self.waiting_processes[self.last_waiting_proc_index];
self.last_waiting_proc_index -= 1;
}
self.locked.store(false, .Unordered);
sysCalls.decreaseCurrTaskPreemptCounter();
}
};
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/appLib/userSysCallInterface.zig | const std = @import("std");
const board = @import("board");
const env = @import("environment");
const alignForward = std.mem.alignForward;
const AppAllocator = @import("AppAllocator.zig").AppAllocator;
const Mutex = @import("Mutex.zig").Mutex;
const utils = @import("utils");
const sysCalls = @import("userSysCallInterface.zig");
const kprint = sysCalls.SysCallPrint.kprint;
const Error = error{ SleepDelayTooShortForScheduler, SysCallError, StatusInterfaceMissmatch, StatusTypeMissmatch };
pub const SysCallPrint = struct {
const Self = @This();
pub const Writer = std.io.Writer(*Self, error{}, appendWrite);
pub fn writer(self: *Self) Writer {
return .{ .context = self };
}
fn callKernelPrint(data: [*]const u8, len: usize) void {
asm volatile (
// args
\\mov x0, %[data_addr]
\\mov x1, %[len]
// sys call id
\\mov x8, #0
\\svc #0
:
: [data_addr] "r" (@intFromPtr(data)),
[len] "r" (len),
: "x0", "x1", "x8"
);
// asm volatile ("brk 0xdead");
}
/// Same as `append` except it returns the number of bytes written, which is always the same
/// as `m.len`. The purpose of this function existing is to match `std.io.Writer` API.
fn appendWrite(self: *Self, data: []const u8) error{}!usize {
_ = self;
// asm volatile ("brk 0xdead");
callKernelPrint(data.ptr, data.len);
return data.len;
}
pub fn kprint(comptime print_string: []const u8, args: anytype) void {
var tempW: SysCallPrint = undefined;
std.fmt.format(tempW.writer(), print_string, args) catch |err| {
@panic(err);
};
}
};
pub fn killTask(pid: usize) noreturn {
asm volatile (
// args
\\mov x0, %[pid]
// sys call id
\\mov x8, #1
\\svc #0
:
: [pid] "r" (pid),
: "x0", "x8"
);
while (true) {}
}
// pub fn forkProcess(pid: usize) void {
// asm volatile (
// // args
// \\mov x0, %[pid]
// // sys call id
// \\mov x8, #2
// \\svc #0
// :
// : [pid] "r" (pid),
// : "x0", "x8"
// );
// }
fn checkForError(x0: usize) !usize {
if (@as(isize, @intCast(x0)) < 0) {
return Error.SysCallError;
}
return x0;
}
pub fn getPid() !u16 {
const ret = asm (
\\mov x8, #3
\\svc #0
\\mov %[curr], x0
: [curr] "=r" (-> usize),
:
: "x0", "x8"
);
return @as(u16, @truncate(try checkForError(ret)));
}
pub fn killTaskRecursively(starting_pid: usize) !void {
const ret = asm volatile (
// args
\\mov x0, %[pid]
// sys call id
\\mov x8, #4
\\svc #0
\\mov %[ret], x0
: [ret] "=r" (-> usize),
: [pid] "r" (starting_pid),
: "x0", "x8"
);
_ = try checkForError(ret);
}
// creates thread for current process
pub fn createThread(thread_stack_mem: []u8, thread_fn: anytype, args: anytype) !void {
var thread_stack_start: []u8 = undefined;
thread_stack_start.ptr = @as([*]u8, @ptrFromInt(@intFromPtr(thread_stack_mem.ptr) + thread_stack_mem.len));
thread_stack_start.len = thread_stack_mem.len;
var arg_mem: []const u8 = undefined;
arg_mem.ptr = @as([*]const u8, @ptrCast(@alignCast(&args)));
arg_mem.len = @sizeOf(@TypeOf(args));
std.mem.copy(u8, thread_stack_start, arg_mem);
const ret = asm volatile (
// args
\\mov x0, %[entry_fn_ptr]
\\mov x1, %[thread_stack]
\\mov x2, %[args_addr]
\\mov x3, %[thread_fn_ptr]
// sys call id
\\mov x8, #6
\\svc #0
\\mov %[ret], x0
: [ret] "=r" (-> usize),
: [entry_fn_ptr] "r" (@intFromPtr(&(ThreadInstance(thread_fn, @TypeOf(args)).threadEntry))),
[thread_stack] "r" (@intFromPtr(thread_stack_start.ptr) - alignForward(usize, @sizeOf(@TypeOf(args)), 16)),
[args_addr] "r" (@intFromPtr(thread_stack_start.ptr)),
[thread_fn_ptr] "r" (@intFromPtr(&thread_fn)),
: "x0", "x1", "x2", "x3", "x8"
);
_ = try checkForError(ret);
}
// provides a generic entry function (generic in regard to the thread and argument function since @call builtin needs them to properly invoke the thread start)
fn ThreadInstance(comptime thread_fn: anytype, comptime Args: type) type {
const ThreadFn = @TypeOf(thread_fn);
return struct {
// todo => I removed callconv(.C), still safe?
fn threadEntry(entry_fn: *ThreadFn, entry_args: *Args) void {
@call(.auto, entry_fn, entry_args.*);
}
};
}
pub fn sleep(delay_in_nano_secs: usize) !void {
const delay_in_hertz = try std.math.divTrunc(usize, delay_in_nano_secs, std.time.ns_per_s);
const delay_sched_intervals = board.config.scheduler_freq_in_hertz / delay_in_hertz;
if (board.config.scheduler_freq_in_hertz < delay_in_hertz) return Error.SleepDelayTooShortForScheduler;
const ret = asm volatile (
// args
\\mov x0, %[delay]
// sys call id
\\mov x8, #7
\\svc #0
\\mov %[ret], x0
: [ret] "=r" (-> usize),
: [delay] "r" (delay_sched_intervals),
: "x0", "x8"
);
_ = try checkForError(ret);
}
pub fn haltProcess(pid: usize) !void {
const ret = asm volatile (
// args
\\mov x0, %[pid]
// sys call id
\\mov x8, #8
\\svc #0
\\mov %[ret], x0
: [ret] "=r" (-> usize),
: [pid] "r" (pid),
: "x0", "x8"
);
_ = try checkForError(ret);
}
pub fn continueProcess(pid: usize) !void {
const ret = asm volatile (
// args
\\mov x0, %[pid]
// sys call id
\\mov x8, #9
\\svc #0
\\mov %[ret], x0
: [ret] "=r" (-> usize),
: [pid] "r" (pid),
: "x0", "x8"
);
_ = try checkForError(ret);
}
pub fn pushToTopic(comptime name: []const u8, data: []u8) !usize {
const status = try env.env_config.getStatusInfo(name);
if (status.type != null) return Error.StatusInterfaceMissmatch;
const data_ptr: usize = @intFromPtr(data.ptr);
const data_len = data.len;
const ret = asm volatile (
// args
\\mov x0, %[id]
\\mov x1, %[data_ptr]
\\mov x2, %[data_len]
// sys call id
\\mov x8, #12
\\svc #0
\\mov %[ret], x0
: [ret] "=r" (-> usize),
: [id] "r" (status.id),
[data_ptr] "r" (data_ptr),
[data_len] "r" (data_len),
: "x0", "x1", "x2", "x8"
);
return checkForError(ret);
}
pub fn popFromTopic(comptime name: []const u8, ret_buff: []u8) !usize {
const status = try env.env_config.getStatusInfo(name);
if (status.type != null) return Error.StatusInterfaceMissmatch;
const ret = asm volatile (
// args
\\mov x0, %[id]
\\mov x1, %[data_len]
\\mov x2, %[ret_buff]
// sys call id
\\mov x8, #13
\\svc #0
\\mov %[ret], x0
: [ret] "=r" (-> usize),
: [id] "r" (status.id),
[data_len] "r" (ret_buff.len),
[ret_buff] "r" (@intFromPtr(ret_buff.ptr)),
: "x0", "x1", "x2", "x8"
);
return checkForError(ret);
}
pub fn waitForTopicUpdate(comptime name: []const u8) !void {
const status = try env.env_config.getStatusInfo(name);
const pid = getPid();
const ret = asm volatile (
// args
\\mov x0, %[topic_id]
\\mov x1, %[pid]
// sys call id
\\mov x8, #14
\\svc #0
\\mov %[ret], x0
: [ret] "=r" (-> usize),
: [topic_id] "r" (status.id),
[pid] "r" (pid),
: "x0", "x1", "x8"
);
_ = try checkForError(ret);
}
pub fn increaseCurrTaskPreemptCounter() !void {
const ret = asm volatile (
// args
// sys call id
\\mov x8, #15
\\svc #0
\\mov %[ret], x0
: [ret] "=r" (-> usize),
:
: "x8"
);
_ = try checkForError(ret);
}
pub fn decreaseCurrTaskPreemptCounter() !void {
const ret = asm volatile (
// args
// sys call id
\\mov x8, #16
\\svc #0
\\mov %[ret], x0
: [ret] "=r" (-> usize),
:
: "x8"
);
_ = try checkForError(ret);
}
pub fn updateStatus(comptime name: []const u8, value: anytype) !void {
const status = try env.env_config.getStatusInfo(name);
if (status.type == null) return Error.StatusInterfaceMissmatch;
if (@TypeOf(value) != status.type.?) return Error.StatusTypeMissmatch;
const ret = asm volatile (
// args
// sys call id
\\mov x0, %[id]
\\mov x1, %[val_addr]
\\mov x8, #17
\\svc #0
\\mov %[ret], x0
: [ret] "=r" (-> usize),
: [id] "r" (status.id),
[val_addr] "r" (&value),
: "x8"
);
_ = try checkForError(ret);
}
pub fn readStatus(comptime T: type, comptime name: []const u8) !T {
const status = try env.env_config.getStatusInfo(name);
if (status.type == null) return Error.StatusInterfaceMissmatch;
if (T != status.type.?) return Error.StatusTypeMissmatch;
var ret_buff: status.type.? = undefined;
const ret = asm volatile (
// args
\\mov x0, %[id]
\\mov x1, %[ret_buff]
// sys call id
\\mov x8, #18
\\svc #0
\\mov %[ret], x0
: [ret] "=r" (-> usize),
: [id] "r" (status.id),
[ret_buff] "r" (@intFromPtr(&ret_buff)),
: "x0", "x1", "x8"
);
_ = try checkForError(ret);
return ret_buff;
}
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/appLib/AppAllocator.zig | const std = @import("std");
const board = @import("board");
const alignForward = std.mem.alignForward;
const utils = @import("utils");
const appAllocatorChunkSize = 0x10000;
pub const AppAllocator = struct {
const Error = error{ OutOfChunks, OutOfMem, AddrNotInMem, AddrNotValid, MemBaseNotAligned, NoHeapStartLabel };
const maxChunks = @divExact(board.config.mem.app_vm_mem_size, appAllocatorChunkSize);
mem_base: usize,
kernel_mem: [maxChunks]bool,
used_chunks: usize,
pub fn init(mem_base: ?usize) !AppAllocator {
var heap_start: usize = undefined;
if (mem_base == null) {
const _heap_start: usize = @intFromPtr(@extern(?*u8, .{ .name = "_heap_start" }) orelse return Error.NoHeapStartLabel);
heap_start = _heap_start;
} else heap_start = mem_base.?;
if (heap_start % 8 != 0) return Error.MemBaseNotAligned;
const ka = AppAllocator{
.kernel_mem = [_]bool{false} ** maxChunks,
// can currently only increase and indicates at which point findFree() is required
.used_chunks = 0,
.mem_base = heap_start,
};
return ka;
}
pub fn alloc(self: *AppAllocator, comptime T: type, n: usize, alignment: ?usize) ![]T {
var alignm: usize = @alignOf(T);
if (alignment) |a| alignm = a;
const size = @sizeOf(T) * n;
const req_chunks = try std.math.divCeil(usize, size, appAllocatorChunkSize);
if (try self.findFree(self.used_chunks, size)) |free_mem_first_chunk| {
for (self.kernel_mem[free_mem_first_chunk .. free_mem_first_chunk + req_chunks]) |*chunk| {
chunk.* = true;
}
const alloc_addr = self.mem_base + (free_mem_first_chunk * appAllocatorChunkSize);
var aligned_alloc_slice = @as([*]T, @ptrFromInt(alignForward(usize, alloc_addr, alignm)));
return aligned_alloc_slice[0 .. n - 1];
} else if (self.used_chunks + req_chunks > maxChunks) {
return Error.OutOfMem;
}
const first_chunk = self.used_chunks;
const last_chunk = self.used_chunks + req_chunks;
self.used_chunks += req_chunks;
for (self.kernel_mem[first_chunk..last_chunk]) |*chunk| {
chunk.* = true;
}
const alloc_addr = self.mem_base + (first_chunk * appAllocatorChunkSize);
const aligned_alloc_slice = @as([*]T, @ptrFromInt(alignForward(usize, alloc_addr, alignm)));
return aligned_alloc_slice[0 .. n - 1];
}
/// finds continous free memory in fragmented kernel memory; marks returned memory as not free!
pub fn findFree(self: *AppAllocator, to_chunk: usize, req_size: usize) !?usize {
var continous_chunks: usize = 0;
const req_chunks = (try std.math.divCeil(usize, req_size, appAllocatorChunkSize));
for (self.kernel_mem, 0..) |chunk, i| {
if (i >= to_chunk) {
return null;
}
if (!chunk) {
continous_chunks += 1;
} else {
continous_chunks = 0;
}
if (continous_chunks >= req_chunks) {
var first_chunk = i;
if (i > 0) first_chunk -= req_chunks;
return first_chunk;
}
}
return null;
}
pub fn free(self: *AppAllocator, to_free: anytype) !void {
const Slice = @typeInfo(@TypeOf(to_free)).Pointer;
const byte_slice = std.mem.sliceAsBytes(to_free);
const size = byte_slice.len + if (Slice.sentinel != null) @sizeOf(Slice.child) else 0;
if (size == 0) return;
// compensating for alignment
var addr_unaligned = @intFromPtr(byte_slice.ptr);
if (addr_unaligned == self.mem_base) addr_unaligned -= (try std.math.mod(usize, @intFromPtr(byte_slice.ptr), appAllocatorChunkSize));
if (addr_unaligned > (self.mem_base + (maxChunks * appAllocatorChunkSize)))
return Error.AddrNotInMem;
const i_chunk_to_free: usize = (try std.math.divCeil(usize, std.math.sub(usize, addr_unaligned, self.mem_base) catch {
return Error.AddrNotInMem;
}, appAllocatorChunkSize)) - 1;
const n_chunks_to_free: usize = try std.math.divCeil(usize, size, appAllocatorChunkSize);
for (&self.kernel_mem[i_chunk_to_free .. i_chunk_to_free + n_chunks_to_free]) |*chunk| {
chunk.* = false;
}
}
};
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/utils/utils.zig | const std = @import("std");
const board = @import("board");
pub const Error = error{
SchedulerFreqTooLow,
};
pub fn calcTicksFromHertz(timer_freq_in_hertz: usize, wanted_freq_in_hertz: usize) usize {
// todo => restore line below
// if (wanted_freq_in_hertz > timer_freq_in_hertz) return Error.SchedulerFreqTooLow;
// todo => use std divtrunct not /
return timer_freq_in_hertz / wanted_freq_in_hertz;
}
pub inline fn toTtbr1(comptime T: type, inp: T) T {
switch (@typeInfo(T)) {
.Pointer => {
return @as(T, @ptrFromInt(@intFromPtr(inp) | board.config.mem.va_start));
},
.Int => {
return inp | board.config.mem.va_start;
},
else => @compileError("mmu address translation: not supported type"),
}
}
pub inline fn toTtbr0(comptime T: type, inp: T) T {
switch (@typeInfo(T)) {
.Pointer => {
return @as(T, @ptrFromInt(@intFromPtr(inp) & ~(board.config.mem.va_start)));
},
.Int => {
return inp & ~(board.config.mem.va_start);
},
else => @compileError("mmu address translation: not supported type"),
}
}
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/arm/gicv2.zig | const std = @import("std");
const arm = @import("arm");
const mmu = @import("mmu.zig");
const AddrSpace = @import("board").boardConfig.AddrSpace;
// identifiers for the vector table addr_handler call
pub const ExceptionType = enum(u64) {
el1Sync = 0x1,
el1Irq = 0x2,
el1Fiq = 0x3,
el1Err = 0x4,
el1Sp0Sync = 0x5,
el1Sp0Irq = 0x6,
el1Sp0Fiq = 0x7,
el1Sp0Err = 0x8,
el0Sync = 0x9,
el0Irq = 0xA,
el0Fiq = 0xB,
el0Err = 0xC,
el032Sync = 0xD,
el032Irq = 0xE,
el032Fiq = 0xF,
el032Err = 0x10,
};
export const el1Sync = ExceptionType.el1Sync;
export const el1Err = ExceptionType.el1Err;
export const el1Fiq = ExceptionType.el1Fiq;
export const el1Irq = ExceptionType.el1Irq;
export const el1Sp0Sync = ExceptionType.el1Sp0Sync;
export const el1Sp0Irq = ExceptionType.el1Sp0Irq;
export const el1Sp0Fiq = ExceptionType.el1Sp0Fiq;
export const el1Sp0Err = ExceptionType.el1Sp0Err;
export const el0Sync = ExceptionType.el0Sync;
export const el0Irq = ExceptionType.el0Irq;
export const el0Fiq = ExceptionType.el0Fiq;
export const el0Err = ExceptionType.el0Err;
export const el032Sync = ExceptionType.el032Sync;
export const el032Irq = ExceptionType.el032Irq;
export const el032Fiq = ExceptionType.el032Fiq;
export const el032Err = ExceptionType.el032Err;
pub fn Gic(comptime addr_space: AddrSpace) type {
const gicCfg = @import("board").PeriphConfig(addr_space).GicV2;
return struct {
// initialize gic controller
pub fn init() !void {
Gicc.init();
try Gicd.init();
}
pub const itargetsrPerReg = 4;
pub const isenablerPerReg = 32;
pub const isdisablerPerReg = 32;
pub const icpendrPerReg = 32;
pub const icfgrPerReg = 16;
pub const intPerReg = 32; // 32 interrupts per reg
pub const ipriorityPerReg = 4; // 4 priority per reg
pub const icenablerPerReg = 32;
pub const intNoPpi0 = 32;
pub const intNoSpi0 = 16;
// 8.8 The GIC Distributor register map
pub const GicdRegMap = struct {
pub const gicdBase = gicCfg.base_address; // gicd mmio base address
// Enables interrupts and affinity routing
pub const ctlr = @as(*volatile u32, @ptrFromInt(gicdBase + 0x0));
// Deactivates the corresponding interrupt. These registers are used when saving and restoring GIC state.
pub const intType = @as(*volatile u32, @ptrFromInt(gicdBase + 0x004));
// distributor implementer identification register
pub const iidr = @as(*volatile u32, @ptrFromInt(gicdBase + 0x008));
// Controls whether the corresponding interrupt is in Group 0 or Group 1.
pub const igroupr = @as(*volatile u32, @ptrFromInt(gicdBase + 0x080));
// interrupt set-enable registers
pub const isenabler = @as(*volatile u32, @ptrFromInt(gicdBase + 0x100));
// Disables forwarding of the corresponding interrupt to the CPU interfaces.
pub const icenabler = @as(*volatile u32, @ptrFromInt(gicdBase + 0x180));
// interrupt set-pending registers
pub const ispendr = @as(*volatile u32, @ptrFromInt(gicdBase + 0x200));
// Removes the pending state from the corresponding interrupt.
pub const icpendr = @as(*volatile u32, @ptrFromInt(gicdBase + 0x280));
pub const isactiver = @as(*volatile u32, @ptrFromInt(gicdBase + 0x300));
// Deactivates the corresponding interrupt. These registers are used when saving and restoring GIC state.
pub const icactiver = @as(*volatile u32, @ptrFromInt(gicdBase + 0x380));
// interrupt priority registers
pub const ipriorityr = @as(*volatile u32, @ptrFromInt(gicdBase + 0x400));
// interrupt processor targets registers
pub const itargetsr = @as(*volatile u32, @ptrFromInt(gicdBase + 0x800));
// Determines whether the corresponding interrupt is edge-triggered or level-sensitive
pub const icfgr = @as(*volatile u32, @ptrFromInt(gicdBase + 0xc00));
// software generated interrupt register
pub const nscar = @as(*volatile u32, @ptrFromInt(gicdBase + 0xe00));
// sgi clear-pending registers
pub const cpendsgir = @as(*volatile u32, @ptrFromInt(gicdBase + 0xf10));
// sgi set-pending registers
pub const spendsgir = @as(*volatile u32, @ptrFromInt(gicdBase + 0xf20));
pub const sgir = @as(*volatile u32, @ptrFromInt(0xf00));
};
// 8.12 the gic cpu interface register map
pub const GiccRegMap = struct {
pub const giccBase = gicCfg.base_address + 0x10000; // gicc mmio base address
// cpu interface control register
pub const ctlr = @as(*volatile u32, @ptrFromInt(giccBase + 0x000));
// interrupt priority mask register
pub const pmr = @as(*volatile u32, @ptrFromInt(giccBase + 0x004));
// binary point register
pub const bpr = @as(*volatile u32, @ptrFromInt(giccBase + 0x008));
// interrupt acknowledge register
pub const iar = @as(*volatile u32, @ptrFromInt(giccBase + 0x00c));
// end of interrupt register
pub const eoir = @as(*volatile u32, @ptrFromInt(giccBase + 0x010));
// running priority register
pub const rpr = @as(*volatile u32, @ptrFromInt(giccBase + 0x014));
// highest pending interrupt register
pub const hpir = @as(*volatile u32, @ptrFromInt(giccBase + 0x018));
// aliased binary point register
pub const abpr = @as(*volatile u32, @ptrFromInt(giccBase + 0x01c));
// cpu interface identification register
pub const iidr = @as(*volatile u32, @ptrFromInt(giccBase + 0x0fc));
};
pub const GicdRegValues = struct {
pub const itargetsrCore0TargetBmap = 0x01010101; // cpu interface 0
// 8.9.4 gicd_ctlr, distributor control register
pub const gicdCtlrEnable = 0x1; // enable gicd
pub const gicdCtlrDisable = 0; // disable gicd
// 8.9.7 gicd_icfgr<n>, interrupt configuration registers
pub const gicdIcfgrLevel = 0; // level-sensitive
pub const gicdIcfgrEdge = 0x2; // edge-triggered
};
pub const GiccRegValues = struct {
// gicc..
// 8.13.14 gicc_pmr, cpu interface priority mask register
pub const giccPmrPrioMin = 0xff; // the lowest level mask
pub const giccPmrPrioHigh = 0x0; // the highest level mask
// 8.13.7 gicc_ctlr, cpu interface control register
pub const giccCtlrEnable = 0x1; // enable gicc
pub const giccCtlrDisable = 0x0; // disable gicc
// 8.13.6 gicc_bpr, cpu interface binary point register
// in systems that support only one security state, when gicc_ctlr.cbpr == 0, this register determines only group 0 interrupt preemption.
pub const giccBprNoGroup = 0x0; // handle all interrupts
// 8.13.11 gicc_iar, cpu interface interrupt acknowledge register
pub const giccIarIntrIdmask = 0x3ff; // 0-9 bits means interrupt id
pub const giccIarSpuriousIntr = 0x3ff; // 1023 means spurious interrupt
};
pub const InterruptIds = enum(u32) {
non_secure_physical_timer = 30,
};
pub const Gicc = struct {
// initialize gic controller
fn init() void {
// disable cpu interface
GiccRegMap.ctlr.* = GiccRegValues.giccCtlrDisable;
// set the priority level as the lowest priority
// note: higher priority corresponds to a lower priority field value in the gic_pmr.
// in addition to this, writing 255 to the gicc_pmr always sets it to the largest supported priority field value.
GiccRegMap.pmr.* = GiccRegValues.giccPmrPrioMin;
// handle all of interrupts in a single group
GiccRegMap.bpr.* = GiccRegValues.giccBprNoGroup;
// clear all of the active interrupts
var pending_irq: u32 = 0;
while (pending_irq != GiccRegValues.giccIarSpuriousIntr) : (pending_irq = GiccRegMap.iar.* & GiccRegValues.giccIarSpuriousIntr) {
GiccRegMap.eoir.* = GiccRegMap.iar.*;
}
// enable cpu interface
GiccRegMap.ctlr.* = GiccRegValues.giccCtlrEnable;
}
// send end of interrupt to irq line for gic
// ctrlr irq controller Configrmation
// irq irq number
pub fn gicv2Eoi(irq: u32) void {
Gicd.gicdClearPending(irq);
}
// find pending irq
// irqp an irq number to be processed
pub fn gicv2FindPendingIrq() ![@bitSizeOf(usize)]u32 {
var ret_array = [_]u32{0} ** @bitSizeOf(usize);
var i: u32 = 0;
var i_found: u32 = 0;
while (@bitSizeOf(usize) > i) : (i += 1) {
if (try Gicd.gicdProbePending(i)) {
ret_array[i_found] = i;
i_found += 1;
}
}
return ret_array;
}
};
pub const Gicd = struct {
// init the gic distributor
fn init() !void {
var i: u32 = 0;
var irq_num: u32 = 0;
// diable distributor
GicdRegMap.ctlr.* = GiccRegValues.giccCtlrDisable;
// disable all irqs & clear pending
irq_num = try std.math.divExact(u32, @bitSizeOf(usize) + intPerReg, intPerReg);
while (irq_num > i) : (i += 1) {
(try calcReg(GicdRegMap.icenabler, i, icenablerPerReg)).* = ~@as(u32, 0);
(try calcReg(GicdRegMap.icpendr, i, icpendrPerReg)).* = ~@as(u32, 0);
}
i = 0;
// set all of interrupt priorities as the lowest priority
irq_num = try std.math.divExact(u32, @bitSizeOf(usize) + ipriorityPerReg, ipriorityPerReg);
while (irq_num > i) : (i += 1) {
(try calcReg(GicdRegMap.ipriorityr, i, ipriorityPerReg)).* = ~@as(u32, 0);
}
i = 0;
// set target of all of shared arm to processor 0
i = try std.math.divExact(u32, intNoSpi0, itargetsrPerReg);
while ((try std.math.divExact(u32, @bitSizeOf(usize) + itargetsrPerReg, itargetsrPerReg)) > i) : (i += 1) {
(try calcReg(GicdRegMap.itargetsr, i, itargetsrPerReg)).* = @as(u32, GicdRegValues.itargetsrCore0TargetBmap);
}
// set trigger type for all armeral interrupts level triggered
i = try std.math.divExact(u32, intNoPpi0, icfgrPerReg);
while ((try std.math.divExact(u32, @bitSizeOf(usize) + icfgrPerReg, icfgrPerReg)) > i) : (i += 1) {
(try calcReg(GicdRegMap.icfgr, i, icfgrPerReg)).* = GicdRegValues.gicdIcfgrLevel;
}
// enable distributor
GicdRegMap.ctlr.* = GicdRegValues.gicdCtlrEnable;
}
pub fn gicdEnableInt(irq_id: InterruptIds) !void {
const clear_ena_bit = try calcShift(@intFromEnum(irq_id), isenablerPerReg);
const reg = try calcReg(GicdRegMap.isenabler, @intFromEnum(irq_id), isenablerPerReg);
reg.* = reg.* | (@as(u32, 1) << clear_ena_bit);
}
pub fn gicdDisableInt(irq_id: InterruptIds) !void {
// irq_id mod 32
const clear_ena_bit = try calcShift(@intFromEnum(irq_id), isdisablerPerReg);
const reg = try calcReg(GicdRegMap.icenabler, @intFromEnum(irq_id), isdisablerPerReg);
reg.* = reg.* << clear_ena_bit;
}
pub fn gicdClearPending(irq_id: InterruptIds) !void {
// irq_id mod 32
const clear_ena_bit = try calcShift(@intFromEnum(irq_id), icpendrPerReg);
const reg = try calcReg(GicdRegMap.icpendr, @intFromEnum(irq_id), icpendrPerReg);
reg.* = reg.* << clear_ena_bit;
}
pub fn gicdProbePending(irq_id: u32) !bool {
// irq_id mod 32
const clear_ena_ind = try calcShift(irq_id, icpendrPerReg);
const cleared_ena_bit = @as(u32, 1) << clear_ena_ind;
const is_pending = (try calcReg(GicdRegMap.icpendr, irq_id, icpendrPerReg)).* & cleared_ena_bit;
return is_pending != 0;
}
// from the gicv2 docs:
// For interrupt ID m, when DIV and MOD are the integer division and modulo operations:
// • the corresponding GICD_ICENABLERn number, n, is given by m = n DIV 32 (32 ints per reg)
// • the offset of the required GICD_ICENABLERn is (0x180 + (4*n))
// • the bit number of the required Clear-enable bit in this register is m MOD 32 (calcShift...)
fn calcReg(addr_start: *volatile u32, irq_id: u32, n_per_reg: u32) !*volatile u32 {
return @as(*volatile u32, @ptrFromInt(@intFromPtr(addr_start) + try std.math.divFloor(u32, irq_id, n_per_reg)));
}
fn calcShift(irq_id: u32, n_per_reg: u32) !u5 {
return @as(u5, @truncate(try std.math.mod(u32, irq_id, n_per_reg)));
}
// set an interrupt target processor
// irq irq number
// p target processor mask
// 0x1 processor 0
// 0x2 processor 1
// 0x4 processor 2
// 0x8 processor 3
pub fn gicdSetTarget(irq_id: InterruptIds, p: u32) !void {
const reg = try calcReg(GicdRegMap.itargetsr, @intFromEnum(irq_id), itargetsrPerReg);
const shift = try calcShift(@intFromEnum(irq_id), itargetsrPerReg) * 8;
var update_val: u32 = reg.*;
update_val &= ~(@as(u32, 0xff) << shift);
update_val |= p << shift;
reg.* = update_val;
}
// set an interrupt priority
// irq irq number
// prio interrupt priority in arm specific expression
pub fn gicdSetPriority(irq_id: InterruptIds, prio: u8) !void {
const reg = try calcReg(GicdRegMap.ipriorityr, @intFromEnum(irq_id), ipriorityPerReg);
const prio_shift = @as(u3, @truncate((try std.math.mod(u32, @intFromEnum(irq_id), ipriorityPerReg)) * 8));
var update_val = reg.*;
update_val &= ~(@as(u32, @intCast(0xff)) << prio_shift);
update_val |= prio << prio_shift;
reg.* = update_val;
}
// configure irq
// irq irq number
// config configuration value for gicd_icfgr
pub fn gicdConfig(irq_id: InterruptIds, config: u32) !void {
const reg = try calcReg(GicdRegMap.icfgr, @intFromEnum(irq_id), icfgrPerReg);
const shift = try calcShift(@intFromEnum(irq_id), icfgrPerReg) * 2; // gicd_icfgr has 16 fields, each field has 2bits.
var update_val = reg.*;
update_val &= ~((@as(u32, 0x03)) << shift); // clear the field
update_val |= ((@as(u32, config)) << shift); // set the value to the field correponding to irq
reg.* = update_val;
}
};
};
}
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/arm/cpuContext.zig | const std = @import("std");
const periph = @import("periph");
const kprint = periph.uart.UartWriter(.ttbr1).kprint;
pub const CpuContext = packed struct {
// debug info
int_type: usize,
el: usize,
far_el1: usize,
esr_el1: usize,
sp_sel: usize,
// sys regs
sp_el0: usize,
elr_el1: usize,
fp: usize,
sp_el1: usize,
// gp regs
x30: usize,
x29: usize,
x28: usize,
x27: usize,
x26: usize,
x25: usize,
x24: usize,
x23: usize,
x22: usize,
x21: usize,
x20: usize,
x19: usize,
x18: usize,
x17: usize,
x16: usize,
x15: usize,
x14: usize,
x13: usize,
x12: usize,
x11: usize,
x10: usize,
x9: usize,
x8: usize,
x7: usize,
x6: usize,
x5: usize,
x4: usize,
x3: usize,
x2: usize,
x1: usize,
x0: usize,
// smid regs
q31: f128,
q30: f128,
q29: f128,
q28: f128,
q27: f128,
q26: f128,
q25: f128,
q24: f128,
q23: f128,
q22: f128,
q21: f128,
q20: f128,
q19: f128,
q18: f128,
q17: f128,
q16: f128,
q15: f128,
q14: f128,
q13: f128,
q12: f128,
q11: f128,
q10: f128,
q9: f128,
q8: f128,
q7: f128,
q6: f128,
q5: f128,
q4: f128,
q3: f128,
q2: f128,
q1: f128,
q0: f128,
pub fn init() CpuContext {
return std.mem.zeroInit(CpuContext, .{});
}
// the labels are not functions since fns would manipulate the sp which needs to stay the same
// since the CpuState is pushed there
// _restoreContextFromSp restores sp to sp_el0 if SpSel is sp_el1 and the otherway around
// that way all registers can be restored without clobbers. Requires that SpSel is set to a different one then
// currently selected.
comptime {
asm (
\\.globl _restoreContextFromSp
\\_restoreContextFromSp:
// pop and discard debug info
\\ldp x0, x1, [sp], #16
\\ldp x0, x1, [sp], #16
\\ldp x0, x2, [sp], #16
// sys regs
\\ldp x0, x1, [sp], #16
\\msr elr_el1, x0
\\mov fp, x1
\\ldp x1, x30, [sp], #16
// * loading context struct sp to correct el sp *
\\mrs x0, spsel
// spsel == 0
\\cmp x0, #0
\\beq load_sp_to_el1
// spsel == 1
\\msr sp_el0, x2
\\b skip_sp_to_el1_load
// spsel == 0
\\load_sp_to_el1:
\\msr spsel, #1
\\mov sp, x1
\\msr spsel, #0
\\skip_sp_to_el1_load:
// * *
// gp regs
\\ldp x29, x28, [sp], #16
\\ldp x27, x26, [sp], #16
\\ldp x25, x24, [sp], #16
\\ldp x23, x22, [sp], #16
\\ldp x21, x20, [sp], #16
\\ldp x19, x18, [sp], #16
\\ldp x17, x16, [sp], #16
\\ldp x15, x14, [sp], #16
\\ldp x13, x12, [sp], #16
\\ldp x11, x10, [sp], #16
\\ldp x9, x8, [sp], #16
\\ldp x7, x6, [sp], #16
\\ldp x5, x4, [sp], #16
\\ldp x3, x2, [sp], #16
\\ldp x1, x0, [sp], #16
// smid regs
\\ldp q31, q30, [sp], #32
\\ldp q29, q28, [sp], #32
\\ldp q27, q26, [sp], #32
\\ldp q25, q24, [sp], #32
\\ldp q23, q22, [sp], #32
\\ldp q21, q20, [sp], #32
\\ldp q19, q18, [sp], #32
\\ldp q17, q16, [sp], #32
\\ldp q15, q14, [sp], #32
\\ldp q13, q12, [sp], #32
\\ldp q11, q10, [sp], #32
\\ldp q9, q8, [sp], #32
\\ldp q7, q6, [sp], #32
\\ldp q5, q4, [sp], #32
\\ldp q3, q2, [sp], #32
\\ldp q1, q0, [sp], #32
\\eret
);
asm (
\\.globl _restoreContextWithoutSwitchFromSp
\\_restoreContextWithoutSwitchFromSp:
// pop and discard debug info
\\ldp x0, x1, [sp], #16
\\ldp x0, x1, [sp], #16
\\ldp x0, x1, [sp], #16
// sys regs
// \\msr sp_el0, x1
\\ldp x0, x1, [sp], #16
\\msr elr_el1, x0
\\mov fp, x1
\\ldp x1, x30, [sp], #16
// \\mov sp, x1
// gp regs
\\ldp x29, x28, [sp], #16
\\ldp x27, x26, [sp], #16
\\ldp x25, x24, [sp], #16
\\ldp x23, x22, [sp], #16
\\ldp x21, x20, [sp], #16
\\ldp x19, x18, [sp], #16
\\ldp x17, x16, [sp], #16
\\ldp x15, x14, [sp], #16
\\ldp x13, x12, [sp], #16
\\ldp x11, x10, [sp], #16
\\ldp x9, x8, [sp], #16
\\ldp x7, x6, [sp], #16
\\ldp x5, x4, [sp], #16
\\ldp x3, x2, [sp], #16
\\ldp x1, x0, [sp], #16
// smid regs
\\ldp q31, q30, [sp], #32
\\ldp q29, q28, [sp], #32
\\ldp q27, q26, [sp], #32
\\ldp q25, q24, [sp], #32
\\ldp q23, q22, [sp], #32
\\ldp q21, q20, [sp], #32
\\ldp q19, q18, [sp], #32
\\ldp q17, q16, [sp], #32
\\ldp q15, q14, [sp], #32
\\ldp q13, q12, [sp], #32
\\ldp q11, q10, [sp], #32
\\ldp q9, q8, [sp], #32
\\ldp q7, q6, [sp], #32
\\ldp q5, q4, [sp], #32
\\ldp q3, q2, [sp], #32
\\ldp q1, q0, [sp], #32
\\eret
);
// _saveCurrContextOnStack is now embedded in bl&kernel exc_vector.S since zig cannot init global assembler
// macros which are required since a label jump would trash the link register
// asm (
// \\.globl _saveCurrContextOnStack ....
}
};
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/arm/processor.zig | const board = @import("board");
const std = @import("std");
const AddrSpace = board.boardConfig.AddrSpace;
pub const ExceptionLevels = enum { el0, el1, el2, el3 };
pub const ProccessorRegMap = struct {
pub const TcrReg = packed struct {
t0sz: u6 = 0,
reserved0: bool = false,
epd0: bool = false,
irgno0: u2 = 0,
orgn0: u2 = 0,
sh0: u2 = 0,
tg0: u2 = 0,
t1sz: u6 = 0,
a1: bool = false,
epd1: bool = false,
irgn1: u2 = 0,
orgn1: u2 = 0,
sh1: u2 = 0,
tg1: u2 = 0,
ips: u3 = 0,
reserved1: bool = false,
as: bool = false,
tbi0: bool = false,
tbi1: bool = false,
ha: bool = false,
hd: bool = false,
hpd0: bool = false,
hpd1: bool = false,
hwu059: bool = false,
hwu060: bool = false,
hwu061: bool = false,
hwu062: bool = false,
hwu159: bool = false,
hwu160: bool = false,
hwu161: bool = false,
hwu162: bool = false,
tbid0: bool = false,
tbid1: bool = false,
nfd0: bool = false,
nfd1: bool = false,
e0pd0: bool = false,
e0pd1: bool = false,
tcma0: bool = false,
tcma1: bool = false,
ds: bool = false,
reserved2: u4 = 0,
pub fn asInt(self: TcrReg) usize {
return @as(u64, @bitCast(self));
}
pub inline fn setTcrEl(comptime el: ExceptionLevels, val: usize) void {
asm volatile ("msr tcr_" ++ @tagName(el) ++ ", %[val]"
:
: [val] "r" (val),
);
}
pub fn readTcrEl(comptime el: ExceptionLevels) usize {
const x: usize = asm ("mrs %[curr], tcr_" ++ @tagName(el)
: [curr] "=r" (-> usize),
);
return x;
}
pub fn calcTxSz(gran: board.boardConfig.Granule.GranuleParams) u6 {
// in bits
const addr_space_indicator = 12;
const addr_bsize = @bitSizeOf(usize);
const bits_per_level = std.math.log2(gran.table_size);
const n_lvl = @intFromEnum(gran.lvls_required) + 1;
return @as(u6, @truncate(addr_bsize - (addr_space_indicator + (n_lvl * bits_per_level))));
}
};
pub const Esr_el1 = struct {
pub const Ifsc = enum(u6) {
addrSizeFaultLvl0 = 0b000000, // Address size fault, level 0 of translation or translation table base register.
addrSizeFaultLvl1 = 0b000001, // Address size fault, level 1.
addrSizeFaultLvl2 = 0b000010, // Address size fault, level 2.
addrSizeFaultLvl3 = 0b000011, // Address size fault, level 3.
transFaultLvl0 = 0b000100, // Translation fault, level 0.
transFaultLvl1 = 0b000101, // Translation fault, level 1.
transFaultLvl2 = 0b000110, // Translation fault, level 2.
transFaultLvl3 = 0b000111, // Translation fault, level 3.
accessFlagFaultLvl1 = 0b001001, // Access flag fault, level 1.
accessFlagFaultLvl2 = 0b001010,
accessFlagFaultLvl3 = 0b001011,
accessFlagFaultLvl0 = 0b001000,
permFaultLvl0 = 0b001100,
permFaultLvl1 = 0b001101,
permFaultLvl2 = 0b001110,
permFaultLvl3 = 0b001111,
syncExternalAbortNotOnTableWalk = 0b010000,
syncExternalAbortNotOnTableWalkLvlN1 = 0b010011, // Synchronous External abort on translation table walk or hardware update of translation table, level -1.
syncExternalAbortOnTableWalkLvl0 = 0b010100, // Synchronous External abort on translation table walk or hardware update of translation table, level 0.
syncExternalAbortOnTableWalkLvl1 = 0b010101, // Synchronous External abort on translation table walk or hardware update of translation table, level 1.
syncExternalAbortOnTableWalkLvl2 = 0b010110, // Synchronous External abort on translation table walk or hardware update of translation table, level 2.
syncExternalAbortOnTableWalkLvl3 = 0b010111, // Synchronous External abort on translation table walk or hardware update of translation table, level 3.
syncParityOrEccErrOnMemAccessOrWalk = 0b011000, // Synchronous parity or ECC error on memory access, not on translation table walk.
syncParityOrEccErrOnMemAccessOrWalkLvlN1 = 0b011011, // Synchronous parity or ECC error on memory access on translation table walk or hardware update of translation table, level -1.
syncParityOrEccErrOnMemAccessOrWalkLvl0 = 0b011100, // Synchronous parity or ECC error on memory access on translation table walk or hardware update of translation table, level 0.
syncParityOrEccErrOnMemAccessOrWalkLvl1 = 0b011101, // Synchronous parity or ECC error on memory access on translation table walk or hardware update of translation table, level 1.
syncParityOrEccErrOnMemAccessOrWalkLvl2 = 0b011110, // Synchronous parity or ECC error on memory access on translation table walk or hardware update of translation table, level 2.
syncParityOrEccErrOnMemAccessOrWalkLvl3 = 0b011111, // Synchronous parity or ECC error on memory access on translation table walk or hardware update of translation table, level 3.
granuleProtectionFaultOnWalkLvlN1 = 0b100011, // Granule Protection Fault on translation table walk or hardware update of translation table, level -1.
granuleProtectionFaultOnWalkLvl0 = 0b100100, // Granule Protection Fault on translation table walk or hardware update of translation table, level 0.
granuleProtectionFaultOnWalkLvl1 = 0b100101, // Granule Protection Fault on translation table walk or hardware update of translation table, level 1.
granuleProtectionFaultOnWalkLvl2 = 0b100110, // Granule Protection Fault on translation table walk or hardware update of translation table, level 2.
granuleProtectionFaultOnWalkLvl3 = 0b100111, // Granule Protection Fault on translation table walk or hardware update of translation table, level 3.
granuleProtectionFaultNotOnWalk = 0b101000, // Granule Protection Fault, not on translation table walk or hardware update of translation table.
addrSizeFaukltLvlN1 = 0b101001, // Address size fault, level -1.
transFaultLvlN1 = 0b101011, // Translation fault, level -1.
tlbConflictAbort = 0b110000, // TLB conflict abort.
unsupportedAtomicHardwareUpdateFault = 0b110001, // Unsupported atomic hardware update fault.
};
pub const ExceptionClass = enum(u6) {
trappedWF = 0b000001,
trappedMCR = 0b000011,
trappedMcrr = 0b000100,
trappedMCRWithAcc = 0b000101,
trappedLdcStcAcc = 0b000110,
sveAsmidFpAcc = 0b000111,
trappedLdStInst = 0b001010,
trappedMrrcWithAcc = 0b001100,
branchTargetExc = 0b001101,
illegalExecState = 0b001110,
svcInstExcAArch32 = 0b010001,
svcInstExAArch64 = 0b010101,
trappedMsrMrsSiAarch64 = 0b011000,
sveFuncTrappedAcc = 0b011001,
excFromPointerAuthInst = 0b011100,
instAbortFromLowerExcLvl = 0b100000,
instAbortTakenWithoutExcLvlChange = 0b100001,
pcAlignFaultExc = 0b100010,
dataAbortFromLowerExcLvl = 0b100100,
dataAbortWithoutExcLvlChange = 0b100101,
spAlignmentFaultExc = 0b100110,
trappedFpExcAarch32 = 0b101000,
trappedFpExcAarch64 = 0b101100,
brkPExcFromLowerExcLvl = 0b101111,
brkPExcWithoutExcLvlChg = 0b110001,
softwStepExcpFromLowerExcLvl = 0b110010,
softwStepExcTakenWithoutExcLvlChange = 0b110011,
watchPointExcpFromALowerExcLvl = 0b110100,
watchPointExcpWithoutTakenWithoutExcLvlChange = 0b110101,
bkptInstExecAarch32 = 0b111000,
bkptInstExecAarch64 = 0b111100,
};
};
pub const SpsrReg = packed struct {
pub inline fn setSpsrReg(comptime el: ExceptionLevels, val: usize) void {
asm volatile ("msr spsr_" ++ @tagName(el) ++ ", %[val]"
:
: [val] "r" (val),
);
}
pub inline fn readSpsrReg(comptime el: ExceptionLevels) usize {
return asm volatile ("mrs %[curr], spsr_" ++ @tagName(el)
: [curr] "=r" (-> usize),
);
}
};
pub const MairReg = packed struct {
attr0: u8 = 0,
attr1: u8 = 0,
attr2: u8 = 0,
attr3: u8 = 0,
attr4: u8 = 0,
attr5: u8 = 0,
attr6: u8 = 0,
attr7: u8 = 0,
pub fn asInt(self: MairReg) usize {
return @as(u64, @bitCast(self));
}
pub inline fn setMairEl(comptime el: ExceptionLevels, val: usize) void {
asm volatile ("msr mair_" ++ @tagName(el) ++ ", %[val]"
:
: [val] "r" (val),
);
}
pub fn readTcrEl(comptime el: ExceptionLevels) usize {
const x: usize = asm ("mrs %[curr], mair_" ++ @tagName(el)
: [curr] "=r" (-> usize),
);
return x;
}
};
pub const SctlrEl = struct {
pub inline fn setSctlrEl(comptime el: ExceptionLevels, val: usize) void {
asm volatile ("msr sctlr_" ++ @tagName(el) ++ ", %[val]"
:
: [val] "r" (val),
);
}
pub fn readSctlrEl(comptime el: ExceptionLevels) usize {
const x: usize = asm ("mrs %[curr], sctlr_" ++ @tagName(el)
: [curr] "=r" (-> usize),
);
return x;
}
};
// enables for el0/1 for el1
pub inline fn enableMmu(comptime el: ExceptionLevels) void {
// var val = SctlrEl.readSctlrEl(el);
const val = 1 << 0;
SctlrEl.setSctlrEl(el, val);
asm volatile ("isb");
}
pub inline fn disableMmu(comptime el: ExceptionLevels) void {
var val = SctlrEl.readSctlrEl(el);
val &= ~(1 << 0);
SctlrEl.setSctlrEl(el, val);
asm volatile ("isb");
}
pub inline fn setSp(addr: usize) void {
asm volatile ("mov sp, %[addr]"
:
: [addr] "r" (addr),
);
isb();
}
pub inline fn branchToAddr(addr: usize) void {
asm volatile ("br %[pc_addr]"
:
: [pc_addr] "r" (addr),
);
}
pub fn invalidateMmuTlbEl1() void {
// https://developer.arm.com/documentation/ddi0488/c/system-control/aarch64-register-summary/aarch64-tlb-maintenance-operations
asm volatile ("TLBI VMALLE1IS");
}
pub fn setTTBR1(addr: usize) void {
asm volatile ("msr ttbr1_el1, %[addr]"
:
: [addr] "r" (addr),
);
}
pub fn setTTBR0(addr: usize) void {
asm volatile ("msr ttbr0_el1, %[addr]"
:
: [addr] "r" (addr),
);
}
pub fn readTTBR0() usize {
return asm ("mrs %[curr], ttbr0_el1"
: [curr] "=r" (-> usize),
);
}
pub fn readTTBR1() usize {
return asm ("mrs %[curr], ttbr1_el1"
: [curr] "=r" (-> usize),
);
}
pub fn invalidateCache() void {
asm volatile ("IC IALLUIS");
}
pub fn invalidateOldPageTableEntries() void {
const ttbr1: usize = asm ("mrs %[curr], ttbr1_el1"
: [curr] "=r" (-> usize),
);
const ttbr0: usize = asm ("mrs %[curr], ttbr0_el1"
: [curr] "=r" (-> usize),
);
asm volatile ("dc civac, %[addr]"
:
: [addr] "r" (ttbr0),
);
asm volatile ("dc civac, %[addr]"
:
: [addr] "r" (ttbr1),
);
}
pub inline fn isb() void {
asm volatile ("isb");
}
pub inline fn dsb() void {
asm volatile ("dsb SY");
}
pub inline fn setExceptionVec(exc_vec_addr: usize) void {
// .foramt(.{@tagName(exc_lvl)}) std.fmt.comptimePrint()
asm volatile ("msr vbar_el1, %[exc_vec]"
:
: [exc_vec] "r" (exc_vec_addr),
);
asm volatile ("isb");
}
pub inline fn exceptionSvc() void {
// Supervisor call. generates an exception targeting exception level 1 (EL1).
asm volatile ("svc #0xdead");
}
pub fn getCurrentEl() usize {
const x: usize = asm ("mrs %[curr], CurrentEL"
: [curr] "=r" (-> usize),
);
return x >> 2;
}
pub fn getCurrentSp() usize {
const x: usize = asm ("mov %[curr], sp"
: [curr] "=r" (-> usize),
);
return x;
}
// ! is inlined and volatile !
pub inline fn getCurrentPc() usize {
return asm volatile ("adr %[pc], ."
: [pc] "=r" (-> usize),
);
}
pub inline fn setSpsel(exc_l: ExceptionLevels) void {
asm volatile ("msr spsel, %[el]"
:
: [el] "r" (@intFromEnum(exc_l)),
);
}
pub inline fn nop() void {
asm volatile ("nop");
}
// has to happen at el3
pub fn isSecState(el: ExceptionLevels) bool {
if (el != .elr)
@compileError("can only read security state in el3");
// reading NS bit
const x: usize = asm ("mrs %[curr], scr_el3"
: [curr] "=r" (-> usize),
);
return (x & (1 << 0)) != 0;
}
pub fn panic() noreturn {
while (true) {}
}
pub const DaifReg = packed struct(u4) {
debug: bool,
serr: bool,
irqs: bool,
fiqs: bool,
pub fn setDaifClr(daif_config: DaifReg) void {
asm volatile ("msr daifclr, %[conf]"
:
: [conf] "I" (daif_config),
);
}
pub fn setDaif(daif_config: DaifReg) void {
asm volatile ("msr daifset, %[conf]"
:
: [conf] "I" (daif_config),
);
}
pub fn enableIrq() callconv(.C) void {
asm volatile ("msr daifclr, %[conf]"
:
: [conf] "I" (DaifReg{ .debug = false, .serr = false, .irqs = true, .fiqs = false }),
);
}
pub fn disableIrq() callconv(.C) void {
asm volatile ("msr daifset, %[conf]"
:
: [conf] "I" (DaifReg{ .debug = false, .serr = false, .irqs = true, .fiqs = false }),
);
}
};
};
comptime {
@export(ProccessorRegMap.DaifReg.enableIrq, .{ .name = "enableIrq", .linkage = .Strong });
@export(ProccessorRegMap.DaifReg.disableIrq, .{ .name = "disableIrq", .linkage = .Strong });
}
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/arm/arm.zig | const board = @import("board");
pub const mmu = @import("mmu.zig");
pub const gicv2 = @import("gicv2.zig");
pub const processor = @import("processor.zig");
pub const cpuContext = @import("cpuContext.zig");
|
0 | repos/MinimalRoboticsPlatform/src | repos/MinimalRoboticsPlatform/src/arm/mmu.zig | const std = @import("std");
const board = @import("board");
const utils = @import("utils");
const kprint = @import("periph").uart.UartWriter(.ttbr1).kprint;
const ProccessorRegMap = @import("processor.zig").ProccessorRegMap;
const Granule = board.boardConfig.Granule;
const GranuleParams = board.boardConfig.Granule.GranuleParams;
const TransLvl = board.boardConfig.TransLvl;
pub const Mapping = struct {
mem_size: usize,
pointing_addr_start: usize,
virt_addr_start: usize,
granule: GranuleParams,
addr_space: board.boardConfig.AddrSpace,
// currently only supported for sections
flags_last_lvl: TableDescriptorAttr,
flags_non_last_lvl: TableDescriptorAttr,
};
const Error = error{
FlagConfigErr,
PageTableConfigErr,
};
// In addition to an output address, a translation table descriptor that refers to a page or region of memory
// includes fields that define properties of the target memory region. These fields can be classified as
// address map control, access control, and region attribute fields.
pub const TableDescriptorAttr = packed struct {
// block indicates next trans lvl (or physical for sections) and page the last trans lvl (with physical addr)
pub const DescType = enum(u1) { block = 0, page = 1 };
// redirects read from mem tables to mairx reg (domain)
pub const AttrIndex = enum(u3) { mair0 = 0, mair1 = 1, mair2 = 2, mair3 = 3, mair4 = 4, mair5 = 5, mair6 = 6, mair7 = 7 };
pub const Sharability = enum(u2) { non_sharable = 0, unpredictable = 1, outer_sharable = 2, innner_sharable = 3 };
// for Non-secure stage 1 of the EL1&0 translation regime
pub const Stage1AccessPerm = enum(u2) { only_el1_read_write = 0, read_write = 1, only_el1_read_only = 2, read_only = 3 };
// for Non-secure EL1&0 stage 2 translation regime
pub const Stage2AccessPerm = enum(u2) { none = 0, read_only = 1, write_only = 2, read_write = 3 };
// for secure EL2&3 translation regime
pub const SecureAccessPerm = enum(u2) { read_write = 0, read_only = 3 };
// https://armv8-ref.codingbelief.com/en/chapter_d4/d43_1_vmsav8-64_translation_table_descriptor_formats.html
// https://armv8-ref.codingbelief.com/en/chapter_d4/d43_2_armv8_translation_table_level_3_descriptor_formats.html
// identifies whether the descriptor is valid, and is 1 for a valid descriptor.
valid: bool = true,
// identifies the descriptor type, and is encoded as:
descType: DescType = .block,
// 4 following are onl important for block entries
// https://armv8-ref.codingbelief.com/en/chapter_d4/d43_3_memory_attribute_fields_in_the_vmsav8-64_translation_table_formats_descriptors.html
attrIndex: AttrIndex = .mair0,
// For memory accesses from Secure state, specifies whether the output address is in the Secure or Non-secure address map
ns: bool = false,
// depends on translation level (Stage2AccessPerm, Stage1AccessPerm, SecureAccessPerm)
accessPerm: Stage1AccessPerm = .read_only,
sharableAttr: Sharability = .non_sharable,
// The access flag indicates when a page or section of memory is accessed for the first time since the
// Access flag in the corresponding translation table descriptor was set to 0.
accessFlag: bool = true,
// the not global bit. Determines whether the TLB descriptor applies to all ASID values, or only to the current ASID value
notGlobal: bool = false,
// upper attr following
address: u39 = 0,
// indicating that the translation table descriptor is one of a contiguous set or descriptors, that might be cached in a single TLB descriptor
contiguous: bool = false,
// priviledeg execute-never bit. Determines whether the region is executable at EL1
pxn: bool = false,
// execute-never bit. Determines whether the region is executable
uxn: bool = false,
_padding2: u10 = 0,
pub fn asInt(self: TableDescriptorAttr) usize {
return @as(u64, @bitCast(self));
}
};
pub fn PageTable(comptime total_mem_size: usize, comptime gran: GranuleParams) !type {
const req_table_total = try calctotalTablesReq(gran, total_mem_size);
return struct {
const Self = @This();
pub const totaPageTableSize = req_table_total * gran.table_size;
lma_offset: usize,
total_size: usize,
page_table_gran: GranuleParams,
page_table: *volatile [req_table_total][gran.table_size]usize,
pub fn init(page_tables: *volatile [req_table_total * gran.table_size]usize, lma_offset: usize) !Self {
return Self{
.lma_offset = lma_offset,
.total_size = total_mem_size,
.page_table_gran = gran,
.page_table = @as(*volatile [req_table_total][gran.table_size]usize, @ptrCast(page_tables)),
};
}
fn calcTransLvlDescriptorSize(mapping: Mapping, lvl: TransLvl) usize {
return std.math.pow(usize, mapping.granule.table_size, @intFromEnum(mapping.granule.lvls_required) - @intFromEnum(lvl)) * mapping.granule.page_size;
}
pub fn mapMem(self: *Self, mapping_without_adjusted_flags: Mapping) !void {
var mapping = mapping_without_adjusted_flags;
if (std.meta.eql(mapping.granule, board.boardConfig.Granule.FourkSection)) mapping.flags_last_lvl.descType = .block;
if (std.meta.eql(mapping.granule, board.boardConfig.Granule.Fourk)) mapping.flags_last_lvl.descType = .page;
mapping.flags_non_last_lvl.descType = .page;
if (!std.meta.eql(mapping.granule, gran)) return Error.PageTableConfigErr;
var table_offset: usize = 0;
var i_lvl: usize = 0;
var phys_count = mapping.pointing_addr_start | mapping.flags_last_lvl.asInt();
while (i_lvl <= @intFromEnum(mapping.granule.lvls_required)) : (i_lvl += 1) {
const curr_lvl_desc_size = calcTransLvlDescriptorSize(mapping, @as(TransLvl, @enumFromInt(i_lvl)));
var next_lvl_desc_size: usize = 0;
var vas_next_offset_in_tables: usize = 0;
if (i_lvl != @intFromEnum(mapping.granule.lvls_required)) {
next_lvl_desc_size = calcTransLvlDescriptorSize(mapping, @as(TransLvl, @enumFromInt(i_lvl + 1)));
vas_next_offset_in_tables = try std.math.divFloor(usize, try std.math.divExact(usize, mapping.virt_addr_start, next_lvl_desc_size), mapping.granule.table_size);
}
const vas_offset_in_descriptors = try std.math.divFloor(usize, mapping.virt_addr_start, curr_lvl_desc_size);
const vas_offset_in_tables = try std.math.divFloor(usize, vas_offset_in_descriptors, mapping.granule.table_size);
const vas_offset_in_descriptors_rest = try std.math.mod(usize, vas_offset_in_descriptors, mapping.granule.table_size);
const to_map_in_descriptors = try std.math.divCeil(usize, mapping.mem_size + mapping.virt_addr_start, curr_lvl_desc_size);
const to_map_in_tables = try std.math.divCeil(usize, to_map_in_descriptors, mapping.granule.table_size);
const to_map_in_descriptors_rest = try std.math.mod(usize, to_map_in_descriptors, mapping.granule.table_size);
const total_mem_size_padding_in_descriptors = try std.math.divFloor(usize, total_mem_size, curr_lvl_desc_size);
var total_mem_size_padding_in_tables = try std.math.divFloor(usize, total_mem_size_padding_in_descriptors, mapping.granule.table_size);
if (total_mem_size_padding_in_tables >= to_map_in_tables) total_mem_size_padding_in_tables -= to_map_in_tables;
var i_table: usize = vas_offset_in_tables;
var i_descriptor: usize = vas_offset_in_descriptors_rest;
var left_descriptors: usize = 0;
while (i_table < to_map_in_tables) : (i_table += 1) {
// if last table is reached, only write the to_map_in_descriptors_rest
left_descriptors = mapping.granule.table_size;
// explicitely casting to signed bc substraction could result in negative num.
if (i_table == @as(i128, to_map_in_tables - 1) and to_map_in_descriptors_rest != 0)
left_descriptors = to_map_in_descriptors_rest;
while (i_descriptor < left_descriptors) : (i_descriptor += 1) {
// last lvl translation links to physical mem
if (i_lvl == @intFromEnum(mapping.granule.lvls_required)) {
self.page_table[table_offset + i_table][i_descriptor] = phys_count;
phys_count += mapping.granule.page_size;
} else {
if (vas_next_offset_in_tables >= i_descriptor) vas_next_offset_in_tables -= i_descriptor;
var link_to_table_addr = utils.toTtbr0(usize, @intFromPtr(&self.page_table[table_offset + to_map_in_tables + i_descriptor + vas_next_offset_in_tables + total_mem_size_padding_in_tables])) + self.lma_offset;
if (i_lvl == @intFromEnum(TransLvl.first_lvl) or i_lvl == @intFromEnum(TransLvl.second_lvl))
link_to_table_addr |= mapping.flags_non_last_lvl.asInt();
self.page_table[table_offset + i_table][i_descriptor] = link_to_table_addr;
}
}
i_descriptor = 0;
}
table_offset += i_table + total_mem_size_padding_in_tables;
}
}
};
}
fn calctotalTablesReq(comptime granule: Granule.GranuleParams, comptime mem_size: usize) !usize {
const req_descriptors = try std.math.divExact(usize, mem_size, granule.page_size);
var req_table_total_: usize = 0;
var ci_lvl: usize = 1;
while (ci_lvl <= @intFromEnum(granule.lvls_required) + 1) : (ci_lvl += 1) {
req_table_total_ += try std.math.divCeil(usize, req_descriptors, std.math.pow(usize, granule.table_size, ci_lvl));
}
return req_table_total_;
}
|
0 | repos | repos/Zprob/README.md | # Zprob
A simple console progress bar for Zig(no dependencies required).
Only tested on zig 0.13.0.
## Usage
only need import `Zprob.zig`(in `src` folder) and use `Zprob` struct.
run `zig build run` to see `example.zig`'s output.
`example.zig`:
```zig
const std = @import("std");
const Zprob = @import("Zprob.zig");
pub fn main() !void {
// Get a new Zprob instance.
// The capacity is set to 100.
// The output file is set to the standard output.
var zprob = Zprob{ .capacity = 100, .out = &std.io.getStdOut() };
// Reset(initialize) the progress bar.
// Must be called just before the loop.
zprob.Reset();
for (0..100) |i| {
_ = i;
// Because write to the standard output may fail, we use `try`.
// Can't use `defer` here because return value is not `void`.
try zprob.Update(1, "test");
}
// Reuse the Zprob instance.
zprob.Resize(1000);
var b: u32 = 0;
while (b < 1000) : (b += 1) {
var buffer: [10]u8 = undefined;
const curr_number_str = std.fmt.bufPrint(buffer[0..], "{}", .{b}) catch unreachable;
// Update the progress bar with description.
try zprob.Update(1, curr_number_str);
std.time.sleep(10_000_000);
}
zprob.Reset();
b = 0;
while (b < 1000) : (try zprob.Update(1, "")) {
b += 1;
std.time.sleep(10_000_000);
}
}
``` |
0 | repos | repos/Zprob/build.zig.zon | .{
.name = "Zprob",
.version = "0.1.0",
.minimum_zig_version = "0.13.0",
.dependencies = .{},
.paths = .{
"build.zig",
"build.zig.zon",
"src",
// For example...
//"LICENSE",
//"README.md",
},
}
|
0 | repos | repos/Zprob/build.zig | const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const exe = b.addExecutable(.{
.name = "Zprob",
.root_source_file = b.path("src/exsample.zig"),
.target = target,
.optimize = optimize,
});
b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe);
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the exsample");
run_step.dependOn(&run_cmd.step);
}
|
0 | repos/Zprob | repos/Zprob/src/exsample.zig | const std = @import("std");
const Zprob = @import("Zprob.zig");
pub fn main() !void {
// Get a new Zprob instance.
// The capacity is set to 100.
// The output file is set to the standard output.
var zprob = Zprob{ .capacity = 100, .out = &std.io.getStdOut() };
// Reset(initialize) the progress bar.
// Must be called just before the loop.
zprob.Reset();
for (0..100) |i| {
_ = i;
// Because write to the standard output may fail, we use `try`.
// Can't use `defer` here because return value is not `void`.
try zprob.Update(1, "test");
}
// Reuse the Zprob instance.
zprob.Resize(1000);
var b: u32 = 0;
while (b < 1000) : (b += 1) {
var buffer: [10]u8 = undefined;
const curr_number_str = std.fmt.bufPrint(buffer[0..], "{}", .{b}) catch unreachable;
// Update the progress bar with description.
try zprob.Update(1, curr_number_str);
std.time.sleep(10_000_000);
}
zprob.Reset();
b = 0;
while (b < 1000) : (try zprob.Update(1, "")) {
b += 1;
std.time.sleep(10_000_000);
}
}
|
0 | repos/Zprob | repos/Zprob/src/Zprob.zig | //! A simple console progress bar for Zig.
/// The length of range to iterate.
capacity: u32 = 0,
/// File to write the progress bar to, usually `std.io.getStdOut()`.
/// Must be set before calling `Update`.
out: ?*const std.fs.File = null,
progress: u32 = 0,
start_time: i64 = 0,
p: u8 = 0,
bar: [bar_len]u8 = init_bar(),
const bar_len = 112;
const ZprobError = error{
OutFileNotSet,
};
inline fn init_bar() [bar_len]u8 {
var bar: [bar_len]u8 = [_]u8{0} ** bar_len;
const head = "\r[\x1b[46m\x1b[0m";
for (head, 0..) |c, i| {
bar[i] = c;
}
for (0..100) |i| {
bar[i + 11] = ' ';
}
bar[bar_len - 1] = ']';
return bar;
}
/// Update the progress bar's status.
/// `count` is the number of items processed in this iteration.
/// `desc` is the description text to show of the current iteration.
pub fn Update(self: *Self, count: u32, desc: []const u8) anyerror!void {
if (self.capacity == 0) {
return self.UpdateBar(100, desc);
} else {
self.progress += count;
if (self.progress >= self.capacity) {
self.progress = self.capacity;
}
const p: u8 = @intCast(self.progress * 100 / self.capacity);
return self.UpdateBar(p, desc);
}
}
inline fn UpdateBar(self: *Self, p: u8, desc: []const u8) anyerror!void {
self.p = p;
for (0..p) |i| {
self.bar[i + 7] = ' ';
}
var buffer: [100]u8 = undefined;
const number_str = std.fmt.bufPrint(buffer[0..], "{}/{}|", .{ self.progress, self.capacity }) catch unreachable;
var len = self.SetString(number_str, 0);
len = self.SetString(self.GetSpeed(), len);
self.SetChar('|', len);
len += 1;
len = self.SetString(desc, len);
const tail = "\x1b[0m";
self.SetStringForce(tail, p + 7);
if (self.out == null) {
return ZprobError.OutFileNotSet;
} else {
try self.out.?.*.writer().print("{s}", .{self.bar});
if (self.progress == self.capacity) {
try self.out.?.*.writer().print("\n", .{});
}
}
}
fn GetSpeed(self: *Self) []const u8 {
const time_cost: i64 = std.time.milliTimestamp() - self.start_time;
var buffer: [100]u8 = undefined;
var per: f64 = @as(f64, @floatFromInt(time_cost)) / @as(f64, @floatFromInt(self.progress * 1000));
const flag: bool = per < 1;
per = if (flag) 1.0 / per else per;
const left: f64 = @as(f64, @floatFromInt(self.capacity - self.progress)) / per;
if (flag) {
return std.fmt.bufPrint(buffer[0..], "{d:.2}it/s,{d:.2}s left", .{ per, left }) catch unreachable;
} else {
return std.fmt.bufPrint(buffer[0..], "{d:.2}s/it,{d:.2}s left", .{ per, left }) catch unreachable;
}
}
inline fn SetString(self: *Self, s: []const u8, i: u8) u8 {
for (s, 0..) |c, j| {
self.SetChar(c, @intCast(j + i));
}
return @intCast(s.len + i);
}
inline fn SetChar(self: *Self, c: u8, i: u8) void {
if (i >= self.p) {
self.bar[i + 11] = c;
} else {
self.bar[i + 7] = c;
}
}
inline fn SetStringForce(self: *Self, s: []const u8, i: u8) void {
for (s, 0..) |c, j| {
self.bar[i + j] = c;
}
}
/// Reset status, must be called just before the loop, or use Resize instead.
/// This will reset the progress to 0 and start the timer.
pub fn Reset(self: *Self) void {
self.progress = 0;
self.bar = init_bar();
self.start_time = std.time.milliTimestamp();
}
/// Resize the capacity of the progress bar, will reset the status as well.
pub fn Resize(self: *Self, len: u32) void {
self.capacity = len;
self.Reset();
}
const std = @import("std");
const Self = @This();
|
0 | repos | repos/zig_learn_opengl/README.md | # [**Learn OpenGL**](https://learnopengl.com/) using [Zig](https://ziglang.org/).
Windowing library: [mach/glfw - Ziggified GLFW bindings](https://github.com/hexops/mach-glfw) by slimsag
(Stephen Gutekanst).
OpenGL bindings for Zig were generated by the [zig-opengl](https://github.com/MasterQ32/zig-opengl) project by MasterQ32 (Felix Queißner).
[zstbi](https://github.com/michal-z/zig-gamedev/tree/main/libs/zstbi) - stb image bindings, [zmath](https://github.com/michal-z/zig-gamedev/tree/main/libs/zmath) - SIMD math library, provided by [Michal Ziulek](https://github.com/michal-z), part of the [zig-gamedev](https://github.com/michal-z/zig-gamedev) project.
Sample programs can be used together with the reference book: [Learn OpenGL - Graphics Programming](https://learnopengl.com/) by [Joey de Vries](http://joeydevries.com/#home).
---
Zig Language installation [How-to instructions](https://ziglang.org/learn/getting-started/).
---
## **I. Getting Started**
### Hello Triangle
- [**hello_triangle**](src/getting_started/hello_triangle/): Minimal setup for drawing a trianlge on screen.<br />`zig build hello_triangle-run`
<br /><a href="src/getting_started/hello_triangle"><img src="src/getting_started/hello_triangle/image.png" alt="hello triangle" height="200"></a>
- [**hello_rectangle**](src/getting_started/hello_rectangle/): Draw a rectangle efficiently with indexed rendering using the **'Element Buffer Object'**. <br />`zig build hello_rectangle-run`
<br /><a href="src/getting_started/hello_rectangle"><img src="src/getting_started/hello_rectangle/image.png" alt="hello triangle" height="200"></a>
### Shaders
- [**shaders**](src/getting_started/shaders/): Little programs that rest on the GPU <br />
`zig build shaders-run`
<br /><a href="src/getting_started/shaders"><img src="src/getting_started/shaders/image.png" alt="shaders" height="200"></a>
[Shader](src/common/shader.zig) struct mirrors the C++ Shader Class in the book.
### Textures
- [**textures**](src/getting_started/textures/): Decorate objects with textures <br />
`zig build textures-run`
<br /><a href="src/getting_started/textures"><img src="src/getting_started/textures/image.png" alt="textures" height="200"></a>
### Transformations
- [**Transformations**](src/getting_started/transformations/): Apply a transformation matrix to vertex data <br />
`zig build transformations-run`
<br /><a href="src/getting_started/transformations"><img src="src/getting_started/transformations/image.png" alt="transformations" height="200"></a>
### Coordinate Systems
- [**Coordinate systems**](src/getting_started/coordinate_systems/): Model, View, Projection matrices <br />
`zig build coordinate_systems-run`
<br /><a href="src/getting_started/coordinate_systems"><img src="src/getting_started/coordinate_systems/image.png" alt="coordinate_systems" height="200"></a>
### Camera
- [**Camera rotation**](src/getting_started/camera_rotate/): Camera rotation around world origin <br />
`zig build camera_rotate-run`
- [**Simple camera**](src/getting_started/simple_camera/): Fly-like camera <br />
`zig build simple_camera-run`
## **II. Lighting**
### Basic Lighting
- [**Basic Lighting**](src/getting_started/basic_lighting/): Phong lighting model <br />
`zig build basic_lighting-run`
<br /><a href="src/getting_started/basic_lighting"><img src="src/getting_started/basic_lighting/image.png" alt="basic_lighting" height="200"></a> |
0 | repos | repos/zig_learn_opengl/build.zig | const std = @import("std");
const glfw = @import("libs/mach-glfw/build.zig");
const zstbi = @import("libs/zstbi/build.zig");
const zmath = @import("libs/zmath/build.zig");
fn installExe(b: *std.build.Builder, exe: *std.build.LibExeObjStep, comptime name: []const u8, dependencies: []const ExeDependency) !void {
exe.want_lto = false;
if (exe.optimize == .ReleaseFast)
exe.strip = true;
for (dependencies) |dep| {
exe.addModule(dep.name, dep.module);
}
try glfw.link(b, exe, .{});
zstbi.link(exe);
const install = b.step(name, "Build '" ++ name);
install.dependOn(&b.addInstallArtifact(exe).step);
const run_step = b.step(name ++ "-run", "Run " ++ name);
const run_cmd = exe.run();
run_cmd.step.dependOn(install);
run_step.dependOn(&run_cmd.step);
b.getInstallStep().dependOn(install);
}
pub fn build(b: *std.Build) !void {
const options = Options{
.build_mode = b.standardOptimizeOption(.{}),
.target = b.standardTargetOptions(.{}),
};
// Modules
const zmath_module = zmath.package(b, .{}).module;
const zstbi_module = zstbi.package(b, .{}).module;
const glfw_module = glfw.module(b);
const gl_module = b.createModule(.{ .source_file = .{ .path = "libs/gl.zig" }, .dependencies = &.{} });
const shader_module = b.createModule(.{ .source_file = .{ .path = "libs/Shader.zig" }, .dependencies = &.{.{ .name = "gl", .module = gl_module }} });
const common_module = b.createModule(.{ .source_file = .{ .path = "libs/common.zig" }, .dependencies = &.{} });
const camera_module = b.createModule(.{ .source_file = .{ .path = "libs/Camera.zig" }, .dependencies = &.{ .{ .name = "gl", .module = gl_module }, .{ .name = "Shader", .module = shader_module }, .{ .name = "zmath", .module = zmath_module }, .{ .name = "common", .module = common_module } } });
// Dependencies
const exe_dependencies: []const ExeDependency = &.{ .{ .name = "zmath", .module = zmath_module }, .{ .name = "zstbi", .module = zstbi_module }, .{ .name = "gl", .module = gl_module }, .{ .name = "glfw", .module = glfw_module }, .{ .name = "Shader", .module = shader_module }, .{ .name = "common", .module = common_module }, .{ .name = "Camera", .module = camera_module } };
const hello_triangle = @import("src/getting_started/hello_triangle/build.zig");
const hello_rectangle = @import("src/getting_started/hello_rectangle/build.zig");
const shaders = @import("src/getting_started/shaders/build.zig");
const textures = @import("src/getting_started/textures/build.zig");
const transformations = @import("src/getting_started/transformations/build.zig");
const coordinate_systems = @import("src/getting_started/coordinate_systems/build.zig");
const camera_rotate = @import("src/getting_started/camera_rotate/build.zig");
const simple_camera = @import("src/getting_started/simple_camera/build.zig");
const basic_lighting = @import("src/getting_started/basic_lighting/build.zig");
try installExe(b, hello_triangle.build(b, options), "hello_triangle", exe_dependencies);
try installExe(b, hello_rectangle.build(b, options), "hello_rectangle", exe_dependencies);
try installExe(b, shaders.build(b, options), "shaders", exe_dependencies);
try installExe(b, textures.build(b, options), "textures", exe_dependencies);
try installExe(b, transformations.build(b, options), "transformations", exe_dependencies);
try installExe(b, coordinate_systems.build(b, options), "coordinate_systems", exe_dependencies);
try installExe(b, camera_rotate.build(b, options), "camera_rotate", exe_dependencies);
try installExe(b, simple_camera.build(b, options), "simple_camera", exe_dependencies);
try installExe(b, basic_lighting.build(b, options), "basic_lighting", exe_dependencies);
}
pub const Options = struct {
build_mode: std.builtin.Mode,
target: std.zig.CrossTarget,
};
pub const ExeDependency = struct {
name: []const u8,
module: *std.Build.Module,
};
|
0 | repos/zig_learn_opengl/src/getting_started | repos/zig_learn_opengl/src/getting_started/transformations/main.zig | const std = @import("std");
const math = std.math;
const glfw = @import("glfw");
const zstbi = @import("zstbi");
const zm = @import("zmath");
const gl = @import("gl");
const Shader = @import("Shader");
const common = @import("common");
const WindowSize = struct {
pub const width: u32 = 800;
pub const height: u32 = 600;
};
pub fn main() !void {
// glfw: initialize and configure
// ------------------------------
if (!glfw.init(.{})) {
std.log.err("GLFW initialization failed", .{});
return;
}
defer glfw.terminate();
// glfw window creation
// --------------------
const window = glfw.Window.create(WindowSize.width, WindowSize.height, "mach-glfw + zig-opengl", null, null, .{
.opengl_profile = .opengl_core_profile,
.context_version_major = 4,
.context_version_minor = 1,
}) orelse {
std.log.err("GLFW Window creation failed", .{});
return;
};
defer window.destroy();
glfw.makeContextCurrent(window);
glfw.Window.setFramebufferSizeCallback(window, framebuffer_size_callback);
// Load all OpenGL function pointers
// ---------------------------------------
const proc: glfw.GLProc = undefined;
try gl.load(proc, glGetProcAddress);
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var allocator = gpa.allocator();
var arena_allocator_state = std.heap.ArenaAllocator.init(allocator);
defer arena_allocator_state.deinit();
const arena = arena_allocator_state.allocator();
// create shader program
var shader_program: Shader = Shader.create(arena, "content/shader.vs", "content/shader.fs");
// set up vertex data (and buffer(s)) and configure vertex attributes
// ------------------------------------------------------------------
const vertices = [_]f32{
// positions // colors // texture coords
0.5, 0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, // top right
0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, // bottom right
-0.5, -0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, // bottom left
-0.5, 0.5, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, // top left
};
const indices = [_]c_uint{
// note that we start from 0!
0, 1, 3, // first triangle
1, 2, 3, // second triangle
};
var VBO: c_uint = undefined;
var VAO: c_uint = undefined;
var EBO: c_uint = undefined;
gl.genVertexArrays(1, &VAO);
defer gl.deleteVertexArrays(1, &VAO);
gl.genBuffers(1, &VBO);
defer gl.deleteBuffers(1, &VBO);
gl.genBuffers(1, &EBO);
defer gl.deleteBuffers(1, &EBO);
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
gl.bindVertexArray(VAO);
gl.bindBuffer(gl.ARRAY_BUFFER, VBO);
// Fill our buffer with the vertex data
gl.bufferData(gl.ARRAY_BUFFER, @sizeOf(f32) * vertices.len, &vertices, gl.STATIC_DRAW);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, EBO);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, 6 * @sizeOf(c_uint), &indices, gl.STATIC_DRAW);
// vertex
gl.vertexAttribPointer(0, 3, gl.FLOAT, gl.FALSE, 8 * @sizeOf(f32), null);
gl.enableVertexAttribArray(0);
// colors
const col_offset: [*c]c_uint = (3 * @sizeOf(f32));
gl.vertexAttribPointer(1, 3, gl.FLOAT, gl.FALSE, 8 * @sizeOf(f32), col_offset);
gl.enableVertexAttribArray(1);
// texture coords
const tex_offset: [*c]c_uint = (6 * @sizeOf(f32));
gl.vertexAttribPointer(2, 2, gl.FLOAT, gl.FALSE, 8 * @sizeOf(f32), tex_offset);
gl.enableVertexAttribArray(2);
// zstbi: loading an image.
zstbi.init(allocator);
defer zstbi.deinit();
const image1_path = common.pathToContent(arena, "content/container.jpg") catch unreachable;
var image1 = try zstbi.Image.init(&image1_path, 0);
defer image1.deinit();
std.debug.print("\nImage 1 info:\n\n img width: {any}\n img height: {any}\n nchannels: {any}\n", .{ image1.width, image1.height, image1.num_components });
zstbi.setFlipVerticallyOnLoad(true);
const image2_path = common.pathToContent(arena, "content/awesomeface.png") catch unreachable;
var image2 = try zstbi.Image.init(&image2_path, 0);
defer image2.deinit();
std.debug.print("\nImage 2 info:\n\n img width: {any}\n img height: {any}\n nchannels: {any}\n", .{ image2.width, image2.height, image2.num_components });
// Create and bind texture1 resource
var texture1: c_uint = undefined;
gl.genTextures(1, &texture1);
gl.activeTexture(gl.TEXTURE0); // activate the texture unit first before binding texture
gl.bindTexture(gl.TEXTURE_2D, texture1);
// set the texture1 wrapping parameters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
// set texture1 filtering parameters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
// Generate the texture1
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, @intCast(c_int, image1.width), @intCast(c_int, image1.height), 0, gl.RGB, gl.UNSIGNED_BYTE, @ptrCast([*c]const u8, image1.data));
gl.generateMipmap(gl.TEXTURE_2D);
// Texture2
var texture2: c_uint = undefined;
gl.genTextures(1, &texture2);
gl.activeTexture(gl.TEXTURE1); // activate the texture unit first before binding texture
gl.bindTexture(gl.TEXTURE_2D, texture2);
// set the texture1 wrapping parameters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
// set texture1 filtering parameters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
// Generate the texture1
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, @intCast(c_int, image2.width), @intCast(c_int, image2.height), 0, gl.RGBA, gl.UNSIGNED_BYTE, @ptrCast([*c]const u8, image2.data));
gl.generateMipmap(gl.TEXTURE_2D);
shader_program.use();
shader_program.setInt("texture1", 0);
shader_program.setInt("texture2", 1);
while (!window.shouldClose()) {
processInput(window);
gl.clearColor(0.0, 0.0, 0.0, 0.0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture1);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, texture2);
gl.bindVertexArray(VAO);
// Construction of the tranformation matrix
const rotZ = zm.rotationZ(@floatCast(f32, glfw.getTime()));
const scale = zm.scaling(0.5, 0.5, 0.5);
const transformM = zm.mul(rotZ, scale);
var transform: [16]f32 = undefined;
zm.storeMat(&transform, transformM);
// Sending our transformation matrix to our vertex shader
const transformLoc = gl.getUniformLocation(shader_program.ID, "transform");
gl.uniformMatrix4fv(transformLoc, 1, gl.FALSE, &transform);
gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_INT, null);
window.swapBuffers();
glfw.pollEvents();
}
}
fn glGetProcAddress(p: glfw.GLProc, proc: [:0]const u8) ?gl.FunctionPointer {
_ = p;
return glfw.getProcAddress(proc);
}
fn framebuffer_size_callback(window: glfw.Window, width: u32, height: u32) void {
_ = window;
gl.viewport(0, 0, @intCast(c_int, width), @intCast(c_int, height));
}
fn processInput(window: glfw.Window) void {
if (glfw.Window.getKey(window, glfw.Key.escape) == glfw.Action.press) {
_ = glfw.Window.setShouldClose(window, true);
}
}
|
0 | repos/zig_learn_opengl/src/getting_started | repos/zig_learn_opengl/src/getting_started/transformations/build.zig | const std = @import("std");
const Options = @import("../../../build.zig").Options;
inline fn thisDir() []const u8 {
return comptime std.fs.path.dirname(@src().file) orelse ".";
}
const content_dir = "content/";
pub fn build(b: *std.Build, options: Options) *std.build.CompileStep {
const exe = b.addExecutable(.{
.name = "transformations",
.root_source_file = .{ .path = thisDir() ++ "/main.zig" },
.target = options.target,
.optimize = options.build_mode,
});
const install_content_step = b.addInstallDirectory(.{
.source_dir = thisDir() ++ "/" ++ content_dir,
.install_dir = .{ .custom = "" },
.install_subdir = "bin/" ++ content_dir,
});
exe.step.dependOn(&install_content_step.step);
return exe;
}
|
0 | repos/zig_learn_opengl/src/getting_started/transformations | repos/zig_learn_opengl/src/getting_started/transformations/content/shader.fs | #version 330 core
out vec4 FragColor;
in vec3 ourColor;
in vec2 texCoord;
uniform sampler2D texture1;
uniform sampler2D texture2;
void main()
{
FragColor = mix(texture(texture1, texCoord),texture(texture2, texCoord), 0.5f) * vec4(ourColor, 1.0f);
};
|
0 | repos/zig_learn_opengl/src/getting_started/transformations | repos/zig_learn_opengl/src/getting_started/transformations/content/shader.vs | #version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;
layout (location = 2) in vec2 aTexCoord;
out vec3 ourColor;
out vec2 texCoord;
uniform mat4 transform;
void main()
{
gl_Position = transform * vec4(aPos, 1.0f);
ourColor = aColor;
texCoord = aTexCoord;
} |
0 | repos/zig_learn_opengl/src/getting_started | repos/zig_learn_opengl/src/getting_started/camera_rotate/main.zig | const std = @import("std");
const math = std.math;
const glfw = @import("glfw");
const zstbi = @import("zstbi");
const zm = @import("zmath");
const gl = @import("gl");
const Shader = @import("Shader");
const common = @import("common");
const WindowSize = struct {
pub const width: u32 = 800;
pub const height: u32 = 600;
};
pub fn main() !void {
// glfw: initialize and configure
// ------------------------------
if (!glfw.init(.{})) {
std.log.err("GLFW initialization failed", .{});
return;
}
defer glfw.terminate();
// glfw window creation
// --------------------
const window = glfw.Window.create(WindowSize.width, WindowSize.height, "mach-glfw + zig-opengl", null, null, .{
.opengl_profile = .opengl_core_profile,
.context_version_major = 4,
.context_version_minor = 1,
}) orelse {
std.log.err("GLFW Window creation failed", .{});
return;
};
defer window.destroy();
glfw.makeContextCurrent(window);
glfw.Window.setFramebufferSizeCallback(window, framebuffer_size_callback);
// Load all OpenGL function pointers
// ---------------------------------------
const proc: glfw.GLProc = undefined;
try gl.load(proc, glGetProcAddress);
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var allocator = gpa.allocator();
var arena_allocator_state = std.heap.ArenaAllocator.init(allocator);
defer arena_allocator_state.deinit();
const arena = arena_allocator_state.allocator();
// create shader program
var shader_program: Shader = Shader.create(arena, "content/shader.vs", "content/shader.fs");
// set up vertex data (and buffer(s)) and configure vertex attributes
// ------------------------------------------------------------------
const vertices_2D = [_]f32{
// positions // colors // texture coords
0.5, 0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, // top right
0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, // bottom right
-0.5, -0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, // bottom left
-0.5, 0.5, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, // top left
};
_ = vertices_2D;
const vertices_3D = [_]f32{
-0.5, -0.5, -0.5, 0.0, 0.0,
0.5, -0.5, -0.5, 1.0, 0.0,
0.5, 0.5, -0.5, 1.0, 1.0,
0.5, 0.5, -0.5, 1.0, 1.0,
-0.5, 0.5, -0.5, 0.0, 1.0,
-0.5, -0.5, -0.5, 0.0, 0.0,
-0.5, -0.5, 0.5, 0.0, 0.0,
0.5, -0.5, 0.5, 1.0, 0.0,
0.5, 0.5, 0.5, 1.0, 1.0,
0.5, 0.5, 0.5, 1.0, 1.0,
-0.5, 0.5, 0.5, 0.0, 1.0,
-0.5, -0.5, 0.5, 0.0, 0.0,
-0.5, 0.5, 0.5, 1.0, 0.0,
-0.5, 0.5, -0.5, 1.0, 1.0,
-0.5, -0.5, -0.5, 0.0, 1.0,
-0.5, -0.5, -0.5, 0.0, 1.0,
-0.5, -0.5, 0.5, 0.0, 0.0,
-0.5, 0.5, 0.5, 1.0, 0.0,
0.5, 0.5, 0.5, 1.0, 0.0,
0.5, 0.5, -0.5, 1.0, 1.0,
0.5, -0.5, -0.5, 0.0, 1.0,
0.5, -0.5, -0.5, 0.0, 1.0,
0.5, -0.5, 0.5, 0.0, 0.0,
0.5, 0.5, 0.5, 1.0, 0.0,
-0.5, -0.5, -0.5, 0.0, 1.0,
0.5, -0.5, -0.5, 1.0, 1.0,
0.5, -0.5, 0.5, 1.0, 0.0,
0.5, -0.5, 0.5, 1.0, 0.0,
-0.5, -0.5, 0.5, 0.0, 0.0,
-0.5, -0.5, -0.5, 0.0, 1.0,
-0.5, 0.5, -0.5, 0.0, 1.0,
0.5, 0.5, -0.5, 1.0, 1.0,
0.5, 0.5, 0.5, 1.0, 0.0,
0.5, 0.5, 0.5, 1.0, 0.0,
-0.5, 0.5, 0.5, 0.0, 0.0,
-0.5, 0.5, -0.5, 0.0, 1.0,
};
const cube_positions = [_][3]f32{
.{ 0.0, 0.0, 0.0 },
.{ 2.0, 5.0, -15.0 },
.{ -1.5, -2.2, -2.5 },
.{ -3.8, -2.0, -12.3 },
.{ 2.4, -0.4, -3.5 },
.{ -1.7, 3.0, -7.5 },
.{ 1.3, -2.0, -2.5 },
.{ 1.5, 2.0, -2.5 },
.{ 1.5, 0.2, -1.5 },
.{ -1.3, 1.0, -1.5 },
};
var VBO: c_uint = undefined;
var VAO: c_uint = undefined;
gl.genVertexArrays(1, &VAO);
defer gl.deleteVertexArrays(1, &VAO);
gl.genBuffers(1, &VBO);
defer gl.deleteBuffers(1, &VBO);
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
gl.bindVertexArray(VAO);
gl.bindBuffer(gl.ARRAY_BUFFER, VBO);
// Fill our buffer with the vertex data
gl.bufferData(gl.ARRAY_BUFFER, @sizeOf(f32) * vertices_3D.len, &vertices_3D, gl.STATIC_DRAW);
// vertex
gl.vertexAttribPointer(0, 3, gl.FLOAT, gl.FALSE, 5 * @sizeOf(f32), null);
gl.enableVertexAttribArray(0);
// texture coords
const tex_offset: [*c]c_uint = (3 * @sizeOf(f32));
gl.vertexAttribPointer(1, 2, gl.FLOAT, gl.FALSE, 5 * @sizeOf(f32), tex_offset);
gl.enableVertexAttribArray(1);
// zstbi: loading an image.
zstbi.init(allocator);
defer zstbi.deinit();
const image1_path = common.pathToContent(arena, "content/container.jpg") catch unreachable;
var image1 = try zstbi.Image.init(&image1_path, 0);
defer image1.deinit();
std.debug.print(
"\nImage 1 info:\n\n img width: {any}\n img height: {any}\n nchannels: {any}\n",
.{ image1.width, image1.height, image1.num_components },
);
zstbi.setFlipVerticallyOnLoad(true);
const image2_path = common.pathToContent(arena, "content/awesomeface.png") catch unreachable;
var image2 = try zstbi.Image.init(&image2_path, 0);
defer image2.deinit();
std.debug.print(
"\nImage 2 info:\n\n img width: {any}\n img height: {any}\n nchannels: {any}\n",
.{ image2.width, image2.height, image2.num_components },
);
// Create and bind texture1 resource
var texture1: c_uint = undefined;
gl.genTextures(1, &texture1);
gl.activeTexture(gl.TEXTURE0); // activate the texture unit first before binding texture
gl.bindTexture(gl.TEXTURE_2D, texture1);
// set the texture1 wrapping parameters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
// set texture1 filtering parameters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
// Generate the texture1
gl.texImage2D(
gl.TEXTURE_2D,
0,
gl.RGB,
@intCast(c_int, image1.width),
@intCast(c_int, image1.height),
0,
gl.RGB,
gl.UNSIGNED_BYTE,
@ptrCast([*c]const u8, image1.data),
);
gl.generateMipmap(gl.TEXTURE_2D);
// Texture2
var texture2: c_uint = undefined;
gl.genTextures(1, &texture2);
gl.activeTexture(gl.TEXTURE1); // activate the texture unit first before binding texture
gl.bindTexture(gl.TEXTURE_2D, texture2);
// set the texture1 wrapping parameters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
// set texture1 filtering parameters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
// Generate the texture1
gl.texImage2D(
gl.TEXTURE_2D,
0,
gl.RGB,
@intCast(c_int, image2.width),
@intCast(c_int, image2.height),
0,
gl.RGBA,
gl.UNSIGNED_BYTE,
@ptrCast([*c]const u8, image2.data),
);
gl.generateMipmap(gl.TEXTURE_2D);
// Enable OpenGL depth testing (use Z-buffer information)
gl.enable(gl.DEPTH_TEST);
shader_program.use();
shader_program.setInt("texture1", 0);
shader_program.setInt("texture2", 1);
// Create the transformation matrices:
// Degree to radians conversion factor
const rad_conversion = math.pi / 180.0;
// Buffer to store Model matrix
var model: [16]f32 = undefined;
// View matrix
var view: [16]f32 = undefined;
// Buffer to store Orojection matrix (in render loop)
var proj: [16]f32 = undefined;
while (!window.shouldClose()) {
processInput(window);
gl.clearColor(0.0, 0.0, 0.0, 0.0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture1);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, texture2);
gl.bindVertexArray(VAO);
// Projection matrix
const projM = x: {
var window_size = window.getSize();
var fov = @intToFloat(f32, window_size.width) / @intToFloat(f32, window_size.height);
var projM = zm.perspectiveFovRhGl(45.0 * rad_conversion, fov, 0.1, 100.0);
break :x projM;
};
zm.storeMat(&proj, projM);
shader_program.setMat4f("projection", proj);
// View matrix: Camera
const radius: f32 = 10.0;
const camX: f32 = @floatCast(f32, @sin(glfw.getTime())) * radius;
const camZ: f32 = @floatCast(f32, @cos(glfw.getTime())) * radius;
const viewM = zm.lookAtRh(
zm.loadArr3(.{ camX, 0.0, camZ }),
zm.loadArr3(.{ 0.0, 0.0, 0.0 }),
zm.loadArr3(.{ 0.0, 1.0, 0.0 }),
);
zm.storeMat(&view, viewM);
shader_program.setMat4f("view", view);
for (cube_positions, 0..) |cube_position, i| {
// Model matrix
const cube_trans = zm.translation(cube_position[0], cube_position[1], cube_position[2]);
const rotation_direction = (((@mod(@intToFloat(f32, i + 1), 2.0)) * 2.0) - 1.0);
const cube_rot = zm.matFromAxisAngle(
zm.f32x4(1.0, 0.3, 0.5, 1.0),
@floatCast(f32, glfw.getTime()) * 55.0 * rotation_direction * rad_conversion,
);
const modelM = zm.mul(cube_rot, cube_trans);
zm.storeMat(&model, modelM);
shader_program.setMat4f("model", model);
gl.drawArrays(gl.TRIANGLES, 0, 36);
}
window.swapBuffers();
glfw.pollEvents();
}
}
fn glGetProcAddress(p: glfw.GLProc, proc: [:0]const u8) ?gl.FunctionPointer {
_ = p;
return glfw.getProcAddress(proc);
}
fn framebuffer_size_callback(window: glfw.Window, width: u32, height: u32) void {
_ = window;
gl.viewport(0, 0, @intCast(c_int, width), @intCast(c_int, height));
}
fn processInput(window: glfw.Window) void {
if (glfw.Window.getKey(window, glfw.Key.escape) == glfw.Action.press) {
_ = glfw.Window.setShouldClose(window, true);
}
}
|
0 | repos/zig_learn_opengl/src/getting_started | repos/zig_learn_opengl/src/getting_started/camera_rotate/build.zig | const std = @import("std");
const Options = @import("../../../build.zig").Options;
inline fn thisDir() []const u8 {
return comptime std.fs.path.dirname(@src().file) orelse ".";
}
const content_dir = "content/";
pub fn build(b: *std.Build, options: Options) *std.build.CompileStep {
const exe = b.addExecutable(.{
.name = "camera_rotate",
.root_source_file = .{ .path = thisDir() ++ "/main.zig" },
.target = options.target,
.optimize = options.build_mode,
});
const install_content_step = b.addInstallDirectory(.{
.source_dir = thisDir() ++ "/" ++ content_dir,
.install_dir = .{ .custom = "" },
.install_subdir = "bin/" ++ content_dir,
});
exe.step.dependOn(&install_content_step.step);
return exe;
}
|
0 | repos/zig_learn_opengl/src/getting_started/camera_rotate | repos/zig_learn_opengl/src/getting_started/camera_rotate/content/shader.fs | #version 330 core
out vec4 FragColor;
in vec2 texCoord;
uniform sampler2D texture1;
uniform sampler2D texture2;
void main()
{
FragColor = mix(texture(texture1, texCoord),texture(texture2, texCoord), 0.5f);
};
|
0 | repos/zig_learn_opengl/src/getting_started/camera_rotate | repos/zig_learn_opengl/src/getting_started/camera_rotate/content/shader.vs | #version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aTexCoord;
out vec2 texCoord;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main()
{
gl_Position = projection * view * model * vec4(aPos, 1.0f);
texCoord = aTexCoord;
} |
0 | repos/zig_learn_opengl/src/getting_started | repos/zig_learn_opengl/src/getting_started/shaders/main.zig | const std = @import("std");
const glfw = @import("glfw");
const gl = @import("gl");
const Shader = @import("Shader");
const WindowSize = struct {
pub const width: u32 = 800;
pub const height: u32 = 600;
};
pub fn main() !void {
// glfw: initialize and configure
// ------------------------------
if (!glfw.init(.{})) {
std.log.err("GLFW initialization failed", .{});
return;
}
defer glfw.terminate();
// glfw window creation
// --------------------
const window = glfw.Window.create(WindowSize.width, WindowSize.height, "mach-glfw + zig-opengl", null, null, .{
.opengl_profile = .opengl_core_profile,
.context_version_major = 4,
.context_version_minor = 1,
}) orelse {
std.log.err("GLFW Window creation failed", .{});
return;
};
defer window.destroy();
glfw.makeContextCurrent(window);
glfw.Window.setFramebufferSizeCallback(window, framebuffer_size_callback);
// Load all OpenGL function pointers
// ---------------------------------------
const proc: glfw.GLProc = undefined;
try gl.load(proc, glGetProcAddress);
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var allocator = gpa.allocator();
var arena_allocator_state = std.heap.ArenaAllocator.init(allocator);
defer arena_allocator_state.deinit();
const arena_allocator = arena_allocator_state.allocator();
// create shader program
var shader_program: Shader = Shader.create(arena_allocator, "shaders/shader_ex3.vs", "shaders/shader_ex3.fs");
// set up vertex data (and buffer(s)) and configure vertex attributes
// ------------------------------------------------------------------
const vertices = [_]f32{
-0.5, -0.5, 0.0, 1.0, 0.0, 0.0,
0.5, -0.5, 0.0, 0.0, 1.0, 0.0,
0.0, 0.5, 0.0, 0.0, 0.0, 1.0,
};
var VBO: c_uint = undefined;
var VAO: c_uint = undefined;
gl.genVertexArrays(1, &VAO);
defer gl.deleteVertexArrays(1, &VAO);
gl.genBuffers(1, &VBO);
defer gl.deleteBuffers(1, &VBO);
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
gl.bindVertexArray(VAO);
gl.bindBuffer(gl.ARRAY_BUFFER, VBO);
// Fill our buffer with the vertex data
gl.bufferData(gl.ARRAY_BUFFER, @sizeOf(f32) * vertices.len, &vertices, gl.STATIC_DRAW);
// Specify and link our vertext attribute description
gl.vertexAttribPointer(0, 3, gl.FLOAT, gl.FALSE, 6 * @sizeOf(f32), null);
gl.enableVertexAttribArray(0);
const offset: [*c]c_uint = (3 * @sizeOf(f32));
gl.vertexAttribPointer(1, 3, gl.FLOAT, gl.FALSE, 6 * @sizeOf(f32), offset);
gl.enableVertexAttribArray(1);
while (!window.shouldClose()) {
processInput(window);
gl.clearColor(0.0, 0.0, 0.0, 0.0);
gl.clear(gl.COLOR_BUFFER_BIT);
// update the uniform color
const timeValue = glfw.getTime();
const offsetValue = @floatCast(f32, @sin(timeValue * 2) / 2.0 + 0.5);
shader_program.setVec3f("offset", [3]f32{ offsetValue, offsetValue, offsetValue });
shader_program.use();
gl.bindVertexArray(VAO);
gl.drawArrays(gl.TRIANGLES, 0, 3);
window.swapBuffers();
glfw.pollEvents();
}
}
fn glGetProcAddress(p: glfw.GLProc, proc: [:0]const u8) ?gl.FunctionPointer {
_ = p;
return glfw.getProcAddress(proc);
}
fn framebuffer_size_callback(window: glfw.Window, width: u32, height: u32) void {
_ = window;
gl.viewport(0, 0, @intCast(c_int, width), @intCast(c_int, height));
}
fn processInput(window: glfw.Window) void {
if (glfw.Window.getKey(window, glfw.Key.escape) == glfw.Action.press) {
_ = glfw.Window.setShouldClose(window, true);
}
}
|
0 | repos/zig_learn_opengl/src/getting_started | repos/zig_learn_opengl/src/getting_started/shaders/build.zig | const std = @import("std");
const Options = @import("../../../build.zig").Options;
inline fn thisDir() []const u8 {
return comptime std.fs.path.dirname(@src().file) orelse ".";
}
const content_dir = "shaders/";
pub fn build(b: *std.Build, options: Options) *std.build.CompileStep {
const exe = b.addExecutable(.{
.name = "shaders",
.root_source_file = .{ .path = thisDir() ++ "/main.zig" },
.target = options.target,
.optimize = options.build_mode,
});
const install_content_step = b.addInstallDirectory(.{
.source_dir = thisDir() ++ "/" ++ content_dir,
.install_dir = .{ .custom = "" },
.install_subdir = "bin/" ++ content_dir,
});
exe.step.dependOn(&install_content_step.step);
return exe;
}
|
0 | repos/zig_learn_opengl/src/getting_started/shaders | repos/zig_learn_opengl/src/getting_started/shaders/shaders/shader_ex3.fs | #version 330 core
out vec4 FragColor;
in vec3 ourColor;
in vec3 vertPos;
void main()
{
FragColor = vec4(vertPos, 1.0);
};
|
0 | repos/zig_learn_opengl/src/getting_started/shaders | repos/zig_learn_opengl/src/getting_started/shaders/shaders/shader.fs | #version 330 core
out vec4 FragColor;
in vec3 ourColor;
void main()
{
FragColor = vec4(ourColor, 0.5);
};
|
0 | repos/zig_learn_opengl/src/getting_started/shaders | repos/zig_learn_opengl/src/getting_started/shaders/shaders/shader_ex3.vs | #version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;
uniform vec3 offset;
out vec3 ourColor;
out vec3 vertPos;
void main()
{
gl_Position = vec4(aPos * offset, 1.0f);
ourColor = aColor;
vertPos = aPos + offset;
} |
0 | repos/zig_learn_opengl/src/getting_started/shaders | repos/zig_learn_opengl/src/getting_started/shaders/shaders/shader.vs | #version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;
uniform vec3 offset;
out vec3 ourColor;
void main()
{
gl_Position = vec4(aPos + offset, 1.0f);
ourColor = aColor;
} |
0 | repos/zig_learn_opengl/src/getting_started | repos/zig_learn_opengl/src/getting_started/simple_camera/main.zig | const std = @import("std");
const math = std.math;
const glfw = @import("glfw");
const zstbi = @import("zstbi");
const zm = @import("zmath");
const gl = @import("gl");
const Shader = @import("Shader");
const Camera = @import("Camera");
const common = @import("common");
// Camera
const camera_pos = zm.loadArr3(.{ 0.0, 0.0, 5.0 });
var lastX: f64 = 0.0;
var lastY: f64 = 0.0;
var first_mouse = true;
var camera = Camera.camera(camera_pos);
// Timing
var delta_time: f32 = 0.0;
var last_frame: f32 = 0.0;
const WindowSize = struct {
pub const width: u32 = 800;
pub const height: u32 = 600;
};
pub fn main() !void {
// glfw: initialize and configure
// ------------------------------
if (!glfw.init(.{})) {
std.log.err("GLFW initialization failed", .{});
return;
}
defer glfw.terminate();
// glfw window creation
// --------------------
const window = glfw.Window.create(WindowSize.width, WindowSize.height, "mach-glfw + zig-opengl", null, null, .{
.opengl_profile = .opengl_core_profile,
.context_version_major = 4,
.context_version_minor = 1,
}) orelse {
std.log.err("GLFW Window creation failed", .{});
return;
};
defer window.destroy();
glfw.makeContextCurrent(window);
glfw.Window.setFramebufferSizeCallback(window, framebuffer_size_callback);
// Capture mouse, disable cursor visibility
glfw.Window.setInputMode(window, glfw.Window.InputMode.cursor, glfw.Window.InputModeCursor.disabled);
glfw.Window.setCursorPosCallback(window, mouseCallback);
glfw.Window.setScrollCallback(window, mouseScrollCallback);
// Load all OpenGL function pointers
// ---------------------------------------
const proc: glfw.GLProc = undefined;
try gl.load(proc, glGetProcAddress);
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var allocator = gpa.allocator();
var arena_allocator_state = std.heap.ArenaAllocator.init(allocator);
defer arena_allocator_state.deinit();
const arena = arena_allocator_state.allocator();
// create shader program
var shader_program: Shader = Shader.create(arena, "content/shader.vs", "content/shader.fs");
// set up vertex data (and buffer(s)) and configure vertex attributes
// ------------------------------------------------------------------
const vertices_2D = [_]f32{
// positions // colors // texture coords
0.5, 0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, // top right
0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, // bottom right
-0.5, -0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, // bottom left
-0.5, 0.5, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, // top left
};
_ = vertices_2D;
const vertices_3D = [_]f32{ -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5, 0.5, -0.5, 1.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, -0.5, -0.5, 0.5, 0.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, 0.5, 0.0, 0.0, -0.5, 0.5, 0.5, 1.0, 0.0, -0.5, 0.5, -0.5, 1.0, 1.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, -0.5, 0.5, 0.0, 0.0, -0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, 0.5, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, -0.5, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 1.0, 1.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, -0.5, -0.5, 0.5, 0.0, 0.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, -0.5, 0.5, 0.5, 0.0, 0.0, -0.5, 0.5, -0.5, 0.0, 1.0 };
const cube_positions = [_][3]f32{ .{ 0.0, 0.0, 0.0 }, .{ 2.0, 5.0, -15.0 }, .{ -1.5, -2.2, -2.5 }, .{ -3.8, -2.0, -12.3 }, .{ 2.4, -0.4, -3.5 }, .{ -1.7, 3.0, -7.5 }, .{ 1.3, -2.0, -2.5 }, .{ 1.5, 2.0, -2.5 }, .{ 1.5, 0.2, -1.5 }, .{ -1.3, 1.0, -1.5 } };
var VBO: c_uint = undefined;
var VAO: c_uint = undefined;
gl.genVertexArrays(1, &VAO);
defer gl.deleteVertexArrays(1, &VAO);
gl.genBuffers(1, &VBO);
defer gl.deleteBuffers(1, &VBO);
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
gl.bindVertexArray(VAO);
gl.bindBuffer(gl.ARRAY_BUFFER, VBO);
// Fill our buffer with the vertex data
gl.bufferData(gl.ARRAY_BUFFER, @sizeOf(f32) * vertices_3D.len, &vertices_3D, gl.STATIC_DRAW);
// vertex
gl.vertexAttribPointer(0, 3, gl.FLOAT, gl.FALSE, 5 * @sizeOf(f32), null);
gl.enableVertexAttribArray(0);
// texture coords
const tex_offset: [*c]c_uint = (3 * @sizeOf(f32));
gl.vertexAttribPointer(1, 2, gl.FLOAT, gl.FALSE, 5 * @sizeOf(f32), tex_offset);
gl.enableVertexAttribArray(1);
// zstbi: loading an image.
zstbi.init(allocator);
defer zstbi.deinit();
const image1_path = common.pathToContent(arena, "content/container.jpg") catch unreachable;
var image1 = try zstbi.Image.init(&image1_path, 0);
defer image1.deinit();
std.debug.print("\nImage 1 info:\n\n img width: {any}\n img height: {any}\n nchannels: {any}\n", .{ image1.width, image1.height, image1.num_components });
zstbi.setFlipVerticallyOnLoad(true);
const image2_path = common.pathToContent(arena, "content/awesomeface.png") catch unreachable;
var image2 = try zstbi.Image.init(&image2_path, 0);
defer image2.deinit();
std.debug.print("\nImage 2 info:\n\n img width: {any}\n img height: {any}\n nchannels: {any}\n", .{ image2.width, image2.height, image2.num_components });
// Create and bind texture1 resource
var texture1: c_uint = undefined;
gl.genTextures(1, &texture1);
gl.activeTexture(gl.TEXTURE0); // activate the texture unit first before binding texture
gl.bindTexture(gl.TEXTURE_2D, texture1);
// set the texture1 wrapping parameters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
// set texture1 filtering parameters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
// Generate the texture1
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, @intCast(c_int, image1.width), @intCast(c_int, image1.height), 0, gl.RGB, gl.UNSIGNED_BYTE, @ptrCast([*c]const u8, image1.data));
gl.generateMipmap(gl.TEXTURE_2D);
// Texture2
var texture2: c_uint = undefined;
gl.genTextures(1, &texture2);
gl.activeTexture(gl.TEXTURE1); // activate the texture unit first before binding texture
gl.bindTexture(gl.TEXTURE_2D, texture2);
// set the texture1 wrapping parameters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
// set texture1 filtering parameters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
// Generate the texture1
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, @intCast(c_int, image2.width), @intCast(c_int, image2.height), 0, gl.RGBA, gl.UNSIGNED_BYTE, @ptrCast([*c]const u8, image2.data));
gl.generateMipmap(gl.TEXTURE_2D);
// Enable OpenGL depth testing (use Z-buffer information)
gl.enable(gl.DEPTH_TEST);
shader_program.use();
shader_program.setInt("texture1", 0);
shader_program.setInt("texture2", 1);
// Buffer to store Model matrix
var model: [16]f32 = undefined;
// View matrix
var view: [16]f32 = undefined;
// Buffer to store Orojection matrix (in render loop)
var proj: [16]f32 = undefined;
while (!window.shouldClose()) {
// Time per frame
const current_frame = @floatCast(f32, glfw.getTime());
delta_time = current_frame - last_frame;
last_frame = current_frame;
processInput(window);
gl.clearColor(0.0, 0.0, 0.0, 0.0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture1);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, texture2);
gl.bindVertexArray(VAO);
// Projection matrix
const projM = x: {
const window_size = window.getSize();
const aspect = @intToFloat(f32, window_size.width) / @intToFloat(f32, window_size.height);
var projM = zm.perspectiveFovRhGl(camera.zoom * common.RAD_CONVERSION, aspect, 0.1, 100.0);
break :x projM;
};
zm.storeMat(&proj, projM);
shader_program.setMat4f("projection", proj);
// View matrix: Camera
const viewM = camera.getViewMatrix();
zm.storeMat(&view, viewM);
shader_program.setMat4f("view", view);
for (cube_positions, 0..) |cube_position, i| {
// Model matrix
const cube_trans = zm.translation(cube_position[0], cube_position[1], cube_position[2]);
const rotation_direction = (((@mod(@intToFloat(f32, i + 1), 2.0)) * 2.0) - 1.0);
const cube_rot = zm.matFromAxisAngle(zm.f32x4(1.0, 0.3, 0.5, 1.0), @floatCast(f32, glfw.getTime()) * 55.0 * rotation_direction * common.RAD_CONVERSION);
const modelM = zm.mul(cube_rot, cube_trans);
zm.storeMat(&model, modelM);
shader_program.setMat4f("model", model);
gl.drawArrays(gl.TRIANGLES, 0, 36);
}
window.swapBuffers();
glfw.pollEvents();
}
}
fn glGetProcAddress(p: glfw.GLProc, proc: [:0]const u8) ?gl.FunctionPointer {
_ = p;
return glfw.getProcAddress(proc);
}
fn framebuffer_size_callback(window: glfw.Window, width: u32, height: u32) void {
_ = window;
gl.viewport(0, 0, @intCast(c_int, width), @intCast(c_int, height));
}
fn processInput(window: glfw.Window) void {
if (glfw.Window.getKey(window, glfw.Key.escape) == glfw.Action.press) {
_ = glfw.Window.setShouldClose(window, true);
}
if (glfw.Window.getKey(window, glfw.Key.w) == glfw.Action.press) {
camera.processKeyboard(Camera.CameraMovement.FORWARD, delta_time);
}
if (glfw.Window.getKey(window, glfw.Key.s) == glfw.Action.press) {
camera.processKeyboard(Camera.CameraMovement.BACKWARD, delta_time);
}
if (glfw.Window.getKey(window, glfw.Key.a) == glfw.Action.press) {
camera.processKeyboard(Camera.CameraMovement.LEFT, delta_time);
}
if (glfw.Window.getKey(window, glfw.Key.d) == glfw.Action.press) {
camera.processKeyboard(Camera.CameraMovement.RIGHT, delta_time);
}
}
fn mouseCallback(window: glfw.Window, xpos: f64, ypos: f64) void {
_ = window;
if (first_mouse) {
lastX = xpos;
lastY = ypos;
first_mouse = false;
}
var xoffset = xpos - lastX;
var yoffset = ypos - lastY;
lastX = xpos;
lastY = ypos;
camera.processMouseMovement(xoffset, yoffset, true);
}
fn mouseScrollCallback(window: glfw.Window, xoffset: f64, yoffset: f64) void {
_ = window;
_ = xoffset;
camera.processMouseScroll(yoffset);
}
|
0 | repos/zig_learn_opengl/src/getting_started | repos/zig_learn_opengl/src/getting_started/simple_camera/build.zig | const std = @import("std");
const Options = @import("../../../build.zig").Options;
inline fn thisDir() []const u8 {
return comptime std.fs.path.dirname(@src().file) orelse ".";
}
const content_dir = "content/";
pub fn build(b: *std.build.Builder, options: Options) *std.build.CompileStep {
const exe = b.addExecutable(.{
.name = "simple_camera",
.root_source_file = .{ .path = thisDir() ++ "/main.zig" },
.target = options.target,
.optimize = options.build_mode,
});
const install_content_step = b.addInstallDirectory(.{
.source_dir = thisDir() ++ "/" ++ content_dir,
.install_dir = .{ .custom = "" },
.install_subdir = "bin/" ++ content_dir,
});
exe.step.dependOn(&install_content_step.step);
return exe;
}
|
0 | repos/zig_learn_opengl/src/getting_started/simple_camera | repos/zig_learn_opengl/src/getting_started/simple_camera/content/shader.fs | #version 330 core
out vec4 FragColor;
in vec2 texCoord;
uniform sampler2D texture1;
uniform sampler2D texture2;
void main()
{
FragColor = mix(texture(texture1, texCoord),texture(texture2, texCoord), 0.5f);
};
|
0 | repos/zig_learn_opengl/src/getting_started/simple_camera | repos/zig_learn_opengl/src/getting_started/simple_camera/content/shader.vs | #version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aTexCoord;
out vec2 texCoord;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main()
{
gl_Position = projection * view * model * vec4(aPos, 1.0f);
texCoord = aTexCoord;
} |
0 | repos/zig_learn_opengl/src/getting_started | repos/zig_learn_opengl/src/getting_started/textures/main.zig | const std = @import("std");
const glfw = @import("glfw");
const zstbi = @import("zstbi");
const gl = @import("gl");
const Shader = @import("Shader");
const common = @import("common");
const WindowSize = struct {
pub const width: u32 = 800;
pub const height: u32 = 600;
};
pub fn main() !void {
// glfw: initialize and configure
// ------------------------------
if (!glfw.init(.{})) {
std.log.err("GLFW initialization failed", .{});
return;
}
defer glfw.terminate();
// glfw window creation
// --------------------
const window = glfw.Window.create(WindowSize.width, WindowSize.height, "mach-glfw + zig-opengl", null, null, .{
.opengl_profile = .opengl_core_profile,
.context_version_major = 4,
.context_version_minor = 1,
}) orelse {
std.log.err("GLFW Window creation failed", .{});
return;
};
defer window.destroy();
glfw.makeContextCurrent(window);
glfw.Window.setFramebufferSizeCallback(window, framebuffer_size_callback);
// Load all OpenGL function pointers
// ---------------------------------------
const proc: glfw.GLProc = undefined;
try gl.load(proc, glGetProcAddress);
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var allocator = gpa.allocator();
var arena_allocator_state = std.heap.ArenaAllocator.init(allocator);
defer arena_allocator_state.deinit();
const arena = arena_allocator_state.allocator();
// create shader program
var shader_program: Shader = Shader.create(
arena,
"content/shader.vs",
"content/shader.fs",
);
// set up vertex data (and buffer(s)) and configure vertex attributes
// ------------------------------------------------------------------
const vertices = [_]f32{
// positions // colors // texture coords
0.5, 0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, // top right
0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, // bottom right
-0.5, -0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, // bottom left
-0.5, 0.5, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, // top left
};
const indices = [_]c_uint{
// note that we start from 0!
0, 1, 3, // first triangle
1, 2, 3, // second triangle
};
var VBO: c_uint = undefined;
var VAO: c_uint = undefined;
var EBO: c_uint = undefined;
gl.genVertexArrays(1, &VAO);
defer gl.deleteVertexArrays(1, &VAO);
gl.genBuffers(1, &VBO);
defer gl.deleteBuffers(1, &VBO);
gl.genBuffers(1, &EBO);
defer gl.deleteBuffers(1, &EBO);
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
gl.bindVertexArray(VAO);
gl.bindBuffer(gl.ARRAY_BUFFER, VBO);
// Fill our buffer with the vertex data
gl.bufferData(gl.ARRAY_BUFFER, @sizeOf(f32) * vertices.len, &vertices, gl.STATIC_DRAW);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, EBO);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, 6 * @sizeOf(c_uint), &indices, gl.STATIC_DRAW);
// vertex
gl.vertexAttribPointer(0, 3, gl.FLOAT, gl.FALSE, 8 * @sizeOf(f32), null);
gl.enableVertexAttribArray(0);
// colors
const col_offset: [*c]c_uint = (3 * @sizeOf(f32));
gl.vertexAttribPointer(1, 3, gl.FLOAT, gl.FALSE, 8 * @sizeOf(f32), col_offset);
gl.enableVertexAttribArray(1);
// texture coords
const tex_offset: [*c]c_uint = (6 * @sizeOf(f32));
gl.vertexAttribPointer(2, 2, gl.FLOAT, gl.FALSE, 8 * @sizeOf(f32), tex_offset);
gl.enableVertexAttribArray(2);
// zstbi: loading an image.
zstbi.init(allocator);
defer zstbi.deinit();
const image1_path = common.pathToContent(arena, "content/container.jpg") catch unreachable;
var image1 = try zstbi.Image.init(&image1_path, 0);
defer image1.deinit();
std.debug.print(
"\nImage 1 info:\n\n img width: {any}\n img height: {any}\n nchannels: {any}\n",
.{ image1.width, image1.height, image1.num_components },
);
zstbi.setFlipVerticallyOnLoad(true);
const image2_path = common.pathToContent(arena, "content/awesomeface.png") catch unreachable;
var image2 = try zstbi.Image.init(&image2_path, 0);
defer image2.deinit();
std.debug.print(
"\nImage 2 info:\n\n img width: {any}\n img height: {any}\n nchannels: {any}\n",
.{ image2.width, image2.height, image2.num_components },
);
// Create and bind texture1 resource
var texture1: c_uint = undefined;
gl.genTextures(1, &texture1);
gl.activeTexture(gl.TEXTURE0); // activate the texture unit first before binding texture
gl.bindTexture(gl.TEXTURE_2D, texture1);
// set the texture1 wrapping parameters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
// set texture1 filtering parameters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
// Generate the texture1
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, @intCast(c_int, image1.width), @intCast(c_int, image1.height), 0, gl.RGB, gl.UNSIGNED_BYTE, @ptrCast([*c]const u8, image1.data));
gl.generateMipmap(gl.TEXTURE_2D);
// Texture2
var texture2: c_uint = undefined;
gl.genTextures(1, &texture2);
gl.activeTexture(gl.TEXTURE1); // activate the texture unit first before binding texture
gl.bindTexture(gl.TEXTURE_2D, texture2);
// set the texture1 wrapping parameters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
// set texture1 filtering parameters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
// Generate the texture1
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, @intCast(c_int, image2.width), @intCast(c_int, image2.height), 0, gl.RGBA, gl.UNSIGNED_BYTE, @ptrCast([*c]const u8, image2.data));
gl.generateMipmap(gl.TEXTURE_2D);
shader_program.use();
shader_program.setInt("texture1", 0);
shader_program.setInt("texture2", 1);
while (!window.shouldClose()) {
processInput(window);
gl.clearColor(0.0, 0.0, 0.0, 0.0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture1);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, texture2);
gl.bindVertexArray(VAO);
gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_INT, null);
window.swapBuffers();
glfw.pollEvents();
}
}
fn glGetProcAddress(p: glfw.GLProc, proc: [:0]const u8) ?gl.FunctionPointer {
_ = p;
return glfw.getProcAddress(proc);
}
fn framebuffer_size_callback(window: glfw.Window, width: u32, height: u32) void {
_ = window;
gl.viewport(0, 0, @intCast(c_int, width), @intCast(c_int, height));
}
fn processInput(window: glfw.Window) void {
if (glfw.Window.getKey(window, glfw.Key.escape) == glfw.Action.press) {
_ = glfw.Window.setShouldClose(window, true);
}
}
|
0 | repos/zig_learn_opengl/src/getting_started | repos/zig_learn_opengl/src/getting_started/textures/build.zig | const std = @import("std");
const Options = @import("../../../build.zig").Options;
inline fn thisDir() []const u8 {
return comptime std.fs.path.dirname(@src().file) orelse ".";
}
const content_dir = "content/";
pub fn build(b: *std.Build, options: Options) *std.build.CompileStep {
const exe = b.addExecutable(.{
.name = "textures",
.root_source_file = .{ .path = thisDir() ++ "/main.zig" },
.target = options.target,
.optimize = options.build_mode,
});
const install_content_step = b.addInstallDirectory(.{
.source_dir = thisDir() ++ "/" ++ content_dir,
.install_dir = .{ .custom = "" },
.install_subdir = "bin/" ++ content_dir,
});
exe.step.dependOn(&install_content_step.step);
return exe;
}
|
0 | repos/zig_learn_opengl/src/getting_started/textures | repos/zig_learn_opengl/src/getting_started/textures/content/shader.fs | #version 330 core
out vec4 FragColor;
in vec3 ourColor;
in vec2 texCoord;
uniform sampler2D texture1;
uniform sampler2D texture2;
void main()
{
FragColor = mix(texture(texture1, texCoord),texture(texture2, texCoord), 0.5f) * vec4(ourColor, 1.0f);
};
|
0 | repos/zig_learn_opengl/src/getting_started/textures | repos/zig_learn_opengl/src/getting_started/textures/content/shader.vs | #version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;
layout (location = 2) in vec2 aTexCoord;
out vec3 ourColor;
out vec2 texCoord;
void main()
{
gl_Position = vec4(aPos, 1.0f);
ourColor = aColor;
texCoord = aTexCoord;
} |
0 | repos/zig_learn_opengl/src/getting_started | repos/zig_learn_opengl/src/getting_started/coordinate_systems/main.zig | const std = @import("std");
const math = std.math;
const glfw = @import("glfw");
const zstbi = @import("zstbi");
const zm = @import("zmath");
const gl = @import("gl");
const Shader = @import("Shader");
const common = @import("common");
const WindowSize = struct {
pub const width: u32 = 800;
pub const height: u32 = 600;
};
pub fn main() !void {
// glfw: initialize and configure
// ------------------------------
if (!glfw.init(.{})) {
std.log.err("GLFW initialization failed", .{});
return;
}
defer glfw.terminate();
// glfw window creation
// --------------------
const window = glfw.Window.create(WindowSize.width, WindowSize.height, "mach-glfw + zig-opengl", null, null, .{
.opengl_profile = .opengl_core_profile,
.context_version_major = 4,
.context_version_minor = 1,
}) orelse {
std.log.err("GLFW Window creation failed", .{});
return;
};
defer window.destroy();
glfw.makeContextCurrent(window);
glfw.Window.setFramebufferSizeCallback(window, framebuffer_size_callback);
// Load all OpenGL function pointers
// ---------------------------------------
const proc: glfw.GLProc = undefined;
try gl.load(proc, glGetProcAddress);
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var allocator = gpa.allocator();
var arena_allocator_state = std.heap.ArenaAllocator.init(allocator);
defer arena_allocator_state.deinit();
const arena = arena_allocator_state.allocator();
// create shader program
var shader_program: Shader = Shader.create(arena, "content/shader.vs", "content/shader.fs");
// set up vertex data (and buffer(s)) and configure vertex attributes
// ------------------------------------------------------------------
const vertices_2D = [_]f32{
// positions // colors // texture coords
0.5, 0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, // top right
0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, // bottom right
-0.5, -0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, // bottom left
-0.5, 0.5, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, // top left
};
_ = vertices_2D;
const vertices_3D = [_]f32{
-0.5, -0.5, -0.5, 0.0, 0.0,
0.5, -0.5, -0.5, 1.0, 0.0,
0.5, 0.5, -0.5, 1.0, 1.0,
0.5, 0.5, -0.5, 1.0, 1.0,
-0.5, 0.5, -0.5, 0.0, 1.0,
-0.5, -0.5, -0.5, 0.0, 0.0,
-0.5, -0.5, 0.5, 0.0, 0.0,
0.5, -0.5, 0.5, 1.0, 0.0,
0.5, 0.5, 0.5, 1.0, 1.0,
0.5, 0.5, 0.5, 1.0, 1.0,
-0.5, 0.5, 0.5, 0.0, 1.0,
-0.5, -0.5, 0.5, 0.0, 0.0,
-0.5, 0.5, 0.5, 1.0, 0.0,
-0.5, 0.5, -0.5, 1.0, 1.0,
-0.5, -0.5, -0.5, 0.0, 1.0,
-0.5, -0.5, -0.5, 0.0, 1.0,
-0.5, -0.5, 0.5, 0.0, 0.0,
-0.5, 0.5, 0.5, 1.0, 0.0,
0.5, 0.5, 0.5, 1.0, 0.0,
0.5, 0.5, -0.5, 1.0, 1.0,
0.5, -0.5, -0.5, 0.0, 1.0,
0.5, -0.5, -0.5, 0.0, 1.0,
0.5, -0.5, 0.5, 0.0, 0.0,
0.5, 0.5, 0.5, 1.0, 0.0,
-0.5, -0.5, -0.5, 0.0, 1.0,
0.5, -0.5, -0.5, 1.0, 1.0,
0.5, -0.5, 0.5, 1.0, 0.0,
0.5, -0.5, 0.5, 1.0, 0.0,
-0.5, -0.5, 0.5, 0.0, 0.0,
-0.5, -0.5, -0.5, 0.0, 1.0,
-0.5, 0.5, -0.5, 0.0, 1.0,
0.5, 0.5, -0.5, 1.0, 1.0,
0.5, 0.5, 0.5, 1.0, 0.0,
0.5, 0.5, 0.5, 1.0, 0.0,
-0.5, 0.5, 0.5, 0.0, 0.0,
-0.5, 0.5, -0.5, 0.0, 1.0,
};
const cube_positions = [_][3]f32{
.{ 0.0, 0.0, 0.0 },
.{ 2.0, 5.0, -15.0 },
.{ -1.5, -2.2, -2.5 },
.{ -3.8, -2.0, -12.3 },
.{ 2.4, -0.4, -3.5 },
.{ -1.7, 3.0, -7.5 },
.{ 1.3, -2.0, -2.5 },
.{ 1.5, 2.0, -2.5 },
.{ 1.5, 0.2, -1.5 },
.{ -1.3, 1.0, -1.5 },
};
var VBO: c_uint = undefined;
var VAO: c_uint = undefined;
gl.genVertexArrays(1, &VAO);
defer gl.deleteVertexArrays(1, &VAO);
gl.genBuffers(1, &VBO);
defer gl.deleteBuffers(1, &VBO);
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
gl.bindVertexArray(VAO);
gl.bindBuffer(gl.ARRAY_BUFFER, VBO);
// Fill our buffer with the vertex data
gl.bufferData(gl.ARRAY_BUFFER, @sizeOf(f32) * vertices_3D.len, &vertices_3D, gl.STATIC_DRAW);
// vertex
gl.vertexAttribPointer(0, 3, gl.FLOAT, gl.FALSE, 5 * @sizeOf(f32), null);
gl.enableVertexAttribArray(0);
// texture coords
const tex_offset: [*c]c_uint = (3 * @sizeOf(f32));
gl.vertexAttribPointer(1, 2, gl.FLOAT, gl.FALSE, 5 * @sizeOf(f32), tex_offset);
gl.enableVertexAttribArray(1);
// zstbi: loading an image.
zstbi.init(allocator);
defer zstbi.deinit();
const image1_path = common.pathToContent(arena, "content/container.jpg") catch unreachable;
var image1 = try zstbi.Image.init(&image1_path, 0);
defer image1.deinit();
std.debug.print("\nImage 1 info:\n\n img width: {any}\n img height: {any}\n nchannels: {any}\n", .{ image1.width, image1.height, image1.num_components });
zstbi.setFlipVerticallyOnLoad(true);
const image2_path = common.pathToContent(arena, "content/awesomeface.png") catch unreachable;
var image2 = try zstbi.Image.init(&image2_path, 0);
defer image2.deinit();
std.debug.print("\nImage 2 info:\n\n img width: {any}\n img height: {any}\n nchannels: {any}\n", .{ image2.width, image2.height, image2.num_components });
// Create and bind texture1 resource
var texture1: c_uint = undefined;
gl.genTextures(1, &texture1);
gl.activeTexture(gl.TEXTURE0); // activate the texture unit first before binding texture
gl.bindTexture(gl.TEXTURE_2D, texture1);
// set the texture1 wrapping parameters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
// set texture1 filtering parameters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
// Generate the texture1
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, @intCast(c_int, image1.width), @intCast(c_int, image1.height), 0, gl.RGB, gl.UNSIGNED_BYTE, @ptrCast([*c]const u8, image1.data));
gl.generateMipmap(gl.TEXTURE_2D);
// Texture2
var texture2: c_uint = undefined;
gl.genTextures(1, &texture2);
gl.activeTexture(gl.TEXTURE1); // activate the texture unit first before binding texture
gl.bindTexture(gl.TEXTURE_2D, texture2);
// set the texture1 wrapping parameters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
// set texture1 filtering parameters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
// Generate the texture1
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, @intCast(c_int, image2.width), @intCast(c_int, image2.height), 0, gl.RGBA, gl.UNSIGNED_BYTE, @ptrCast([*c]const u8, image2.data));
gl.generateMipmap(gl.TEXTURE_2D);
// Enable OpenGL depth testing (use Z-buffer information)
gl.enable(gl.DEPTH_TEST);
shader_program.use();
shader_program.setInt("texture1", 0);
shader_program.setInt("texture2", 1);
// Create the transformation matrices:
// Degree to radians conversion factor
const rad_conversion = math.pi / 180.0;
// Buffer to store Model matrix
var model: [16]f32 = undefined;
// View matrix
const viewM = zm.translation(0.0, 0.0, -5.0);
var view: [16]f32 = undefined;
zm.storeMat(&view, viewM);
shader_program.setMat4f("view", view);
// Buffer to store Orojection matrix (in render loop)
var proj: [16]f32 = undefined;
while (!window.shouldClose()) {
processInput(window);
gl.clearColor(0.0, 0.0, 0.0, 0.0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture1);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, texture2);
gl.bindVertexArray(VAO);
// Projection matrix
const projM = x: {
var window_size = window.getSize();
var fov = @intToFloat(f32, window_size.width) / @intToFloat(f32, window_size.height);
var projM = zm.perspectiveFovRhGl(45.0 * rad_conversion, fov, 0.1, 100.0);
break :x projM;
};
zm.storeMat(&proj, projM);
shader_program.setMat4f("projection", proj);
for (cube_positions, 0..) |cube_position, i| {
const cube_trans = zm.translation(cube_position[0], cube_position[1], cube_position[2]);
const rotation_direction = (((@mod(@intToFloat(f32, i + 1), 2.0)) * 2.0) - 1.0);
const cube_rot = zm.matFromAxisAngle(
zm.f32x4(1.0, 0.3, 0.5, 1.0),
@floatCast(f32, glfw.getTime()) * 55.0 * rotation_direction * rad_conversion,
);
const modelM = zm.mul(cube_rot, cube_trans);
zm.storeMat(&model, modelM);
shader_program.setMat4f("model", model);
gl.drawArrays(gl.TRIANGLES, 0, 36);
}
window.swapBuffers();
glfw.pollEvents();
}
}
fn glGetProcAddress(p: glfw.GLProc, proc: [:0]const u8) ?gl.FunctionPointer {
_ = p;
return glfw.getProcAddress(proc);
}
fn framebuffer_size_callback(window: glfw.Window, width: u32, height: u32) void {
_ = window;
gl.viewport(0, 0, @intCast(c_int, width), @intCast(c_int, height));
}
fn processInput(window: glfw.Window) void {
if (glfw.Window.getKey(window, glfw.Key.escape) == glfw.Action.press) {
_ = glfw.Window.setShouldClose(window, true);
}
}
|
0 | repos/zig_learn_opengl/src/getting_started | repos/zig_learn_opengl/src/getting_started/coordinate_systems/build.zig | const std = @import("std");
const Options = @import("../../../build.zig").Options;
inline fn thisDir() []const u8 {
return comptime std.fs.path.dirname(@src().file) orelse ".";
}
const content_dir = "content/";
pub fn build(b: *std.Build, options: Options) *std.build.CompileStep {
const exe = b.addExecutable(.{
.name = "coordinate_system",
.root_source_file = .{ .path = thisDir() ++ "/main.zig" },
.target = options.target,
.optimize = options.build_mode,
});
const install_content_step = b.addInstallDirectory(.{
.source_dir = thisDir() ++ "/" ++ content_dir,
.install_dir = .{ .custom = "" },
.install_subdir = "bin/" ++ content_dir,
});
exe.step.dependOn(&install_content_step.step);
return exe;
}
|
0 | repos/zig_learn_opengl/src/getting_started/coordinate_systems | repos/zig_learn_opengl/src/getting_started/coordinate_systems/content/shader.fs | #version 330 core
out vec4 FragColor;
in vec2 texCoord;
uniform sampler2D texture1;
uniform sampler2D texture2;
void main()
{
FragColor = mix(texture(texture1, texCoord),texture(texture2, texCoord), 0.5f);
};
|
0 | repos/zig_learn_opengl/src/getting_started/coordinate_systems | repos/zig_learn_opengl/src/getting_started/coordinate_systems/content/shader.vs | #version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aTexCoord;
out vec2 texCoord;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main()
{
gl_Position = projection * view * model * vec4(aPos, 1.0f);
texCoord = aTexCoord;
} |
0 | repos/zig_learn_opengl/src/getting_started | repos/zig_learn_opengl/src/getting_started/hello_rectangle/main.zig | const std = @import("std");
const glfw = @import("glfw");
const gl = @import("gl");
const vertexShaderSource =
\\ #version 410 core
\\ layout (location = 0) in vec3 aPos;
\\ void main()
\\ {
\\ gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);
\\ }
;
const fragmentShaderSource =
\\ #version 410 core
\\ out vec4 FragColor;
\\ void main() {
\\ FragColor = vec4(1.0, 0.5, 0.2, 1.0);
\\ }
;
const WindowSize = struct {
pub const width: u32 = 800;
pub const height: u32 = 600;
};
pub fn main() !void {
// glfw: initialize and configure
// ------------------------------
if (!glfw.init(.{})) {
std.log.err("GLFW initialization failed", .{});
return;
}
defer glfw.terminate();
// glfw window creation
// --------------------
const window = glfw.Window.create(WindowSize.width, WindowSize.height, "mach-glfw + zig-opengl", null, null, .{
.opengl_profile = .opengl_core_profile,
.context_version_major = 4,
.context_version_minor = 1,
}) orelse {
std.log.err("GLFW Window creation failed", .{});
return;
};
defer window.destroy();
glfw.makeContextCurrent(window);
glfw.Window.setFramebufferSizeCallback(window, framebuffer_size_callback);
// Load all OpenGL function pointers
// ---------------------------------------
const proc: glfw.GLProc = undefined;
try gl.load(proc, glGetProcAddress);
// Create vertex shader
var vertexShader: c_uint = undefined;
vertexShader = gl.createShader(gl.VERTEX_SHADER);
defer gl.deleteShader(vertexShader);
// Attach the shader source to the vertex shader object and compile it
gl.shaderSource(vertexShader, 1, @ptrCast([*c]const [*c]const u8, &vertexShaderSource), 0);
gl.compileShader(vertexShader);
// Check if vertex shader was compiled successfully
var success: c_int = undefined;
var infoLog: [512]u8 = [_]u8{0} ** 512;
gl.getShaderiv(vertexShader, gl.COMPILE_STATUS, &success);
if (success == 0) {
gl.getShaderInfoLog(vertexShader, 512, 0, &infoLog);
std.log.err("{s}", .{infoLog});
}
// Fragment shader
var fragmentShader: c_uint = undefined;
fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
defer gl.deleteShader(fragmentShader);
gl.shaderSource(fragmentShader, 1, @ptrCast([*c]const [*c]const u8, &fragmentShaderSource), 0);
gl.compileShader(fragmentShader);
gl.getShaderiv(fragmentShader, gl.COMPILE_STATUS, &success);
if (success == 0) {
gl.getShaderInfoLog(fragmentShader, 512, 0, &infoLog);
std.log.err("{s}", .{infoLog});
}
// create a program object
var shaderProgram: c_uint = undefined;
shaderProgram = gl.createProgram();
defer gl.deleteProgram(shaderProgram);
// attach compiled shader objects to the program object and link
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
// check if shader linking was successfull
gl.getProgramiv(shaderProgram, gl.LINK_STATUS, &success);
if (success == 0) {
gl.getProgramInfoLog(shaderProgram, 512, 0, &infoLog);
std.log.err("{s}", .{infoLog});
}
// set up vertex data (and buffer(s)) and configure vertex attributes
// ------------------------------------------------------------------
// const vertices = [9]f32{ -0.5, -0.5, 0.0, 0.5, -0.5, 0.0, 0.0, 0.5, 0.0 };
const vertices = [12]f32{
0.5, 0.5, 0.0, // top right
0.5, -0.5, 0.0, // bottom right
-0.5, -0.5, 0.0, // bottom left
-0.5, 0.5, 0.0, // top left
};
const indices = [6]c_uint{
// note that we start from 0!
0, 1, 3, // first triangle
1, 2, 3, // second triangle
};
var VBO: c_uint = undefined;
var VAO: c_uint = undefined;
var EBO: c_uint = undefined;
gl.genVertexArrays(1, &VAO);
defer gl.deleteVertexArrays(1, &VAO);
gl.genBuffers(1, &VBO);
defer gl.deleteBuffers(1, &VBO);
gl.genBuffers(1, &EBO);
defer gl.deleteBuffers(1, &EBO);
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
gl.bindVertexArray(VAO);
gl.bindBuffer(gl.ARRAY_BUFFER, VBO);
// Fill our buffer with the vertex data
gl.bufferData(gl.ARRAY_BUFFER, @sizeOf(f32) * vertices.len, &vertices, gl.STATIC_DRAW);
// copy our index array in an element buffer for OpenGL to use
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, EBO);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, 6 * @sizeOf(c_uint), &indices, gl.STATIC_DRAW);
// Specify and link our vertext attribute description
gl.vertexAttribPointer(0, 3, gl.FLOAT, gl.FALSE, 3 * @sizeOf(f32), null);
gl.enableVertexAttribArray(0);
// note that this is allowed, the call to glVertexAttribPointer registered VBO as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind
gl.bindBuffer(gl.ARRAY_BUFFER, 0);
// You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other
// VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary.
gl.bindVertexArray(0);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, 0);
// Wireframe mode
gl.polygonMode(gl.FRONT_AND_BACK, gl.LINE);
while (!window.shouldClose()) {
processInput(window);
gl.clearColor(0.2, 0.3, 0.3, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
// Activate shaderProgram
gl.useProgram(shaderProgram);
gl.bindVertexArray(VAO); // seeing as we only have a single VAO there's no need to bind it every time, but we'll do so to keep things a bit more organized
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, EBO);
gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_INT, null);
gl.bindVertexArray(0);
window.swapBuffers();
glfw.pollEvents();
}
}
fn glGetProcAddress(p: glfw.GLProc, proc: [:0]const u8) ?gl.FunctionPointer {
_ = p;
return glfw.getProcAddress(proc);
}
fn framebuffer_size_callback(window: glfw.Window, width: u32, height: u32) void {
_ = window;
gl.viewport(0, 0, @intCast(c_int, width), @intCast(c_int, height));
}
fn processInput(window: glfw.Window) void {
if (glfw.Window.getKey(window, glfw.Key.escape) == glfw.Action.press) {
_ = glfw.Window.setShouldClose(window, true);
}
}
|
0 | repos/zig_learn_opengl/src/getting_started | repos/zig_learn_opengl/src/getting_started/hello_rectangle/README.md | # Indexed drawing of a rectangle with Element Buffer Objects (EBO) aka (index buffer).
From [Hello Triangle](https://learnopengl.com/Getting-started/Hello-Triangle) chapter: Element Buffer Objects section.
 |
0 | repos/zig_learn_opengl/src/getting_started | repos/zig_learn_opengl/src/getting_started/hello_rectangle/build.zig | const std = @import("std");
const Options = @import("../../../build.zig").Options;
inline fn thisDir() []const u8 {
return comptime std.fs.path.dirname(@src().file) orelse ".";
}
pub fn build(b: *std.Build, options: Options) *std.build.CompileStep {
const exe = b.addExecutable(.{
.name = "hello_rectangle",
.root_source_file = .{ .path = thisDir() ++ "/main.zig" },
.target = options.target,
.optimize = options.build_mode,
});
return exe;
}
|
0 | repos/zig_learn_opengl/src/getting_started | repos/zig_learn_opengl/src/getting_started/basic_lighting/main.zig | const std = @import("std");
const math = std.math;
const glfw = @import("glfw");
const zstbi = @import("zstbi");
const zm = @import("zmath");
const gl = @import("gl");
const Shader = @import("Shader");
const Camera = @import("Camera");
const common = @import("common");
// Camera
const camera_pos = zm.loadArr3(.{ 0.0, 0.0, 5.0 });
var lastX: f64 = 0.0;
var lastY: f64 = 0.0;
var first_mouse = true;
var camera = Camera.camera(camera_pos);
// Timing
var delta_time: f32 = 0.0;
var last_frame: f32 = 0.0;
// lighting
var light_position = [_]f32{ 10.0, 10.0, 10.0 };
const WindowSize = struct {
pub const width: u32 = 800;
pub const height: u32 = 600;
};
pub fn main() !void {
// glfw: initialize and configure
// ------------------------------
if (!glfw.init(.{})) {
std.log.err("GLFW initialization failed", .{});
return;
}
defer glfw.terminate();
// glfw window creation
// --------------------
const window = glfw.Window.create(WindowSize.width, WindowSize.height, "mach-glfw + zig-opengl", null, null, .{
.opengl_profile = .opengl_core_profile,
.context_version_major = 4,
.context_version_minor = 1,
}) orelse {
std.log.err("GLFW Window creation failed", .{});
return;
};
defer window.destroy();
glfw.makeContextCurrent(window);
glfw.Window.setFramebufferSizeCallback(window, framebuffer_size_callback);
// Capture mouse, disable cursor visibility
glfw.Window.setInputMode(window, glfw.Window.InputMode.cursor, glfw.Window.InputModeCursor.disabled);
glfw.Window.setCursorPosCallback(window, mouseCallback);
glfw.Window.setScrollCallback(window, mouseScrollCallback);
// Load all OpenGL function pointers
// ---------------------------------------
const proc: glfw.GLProc = undefined;
try gl.load(proc, glGetProcAddress);
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var allocator = gpa.allocator();
var arena_allocator_state = std.heap.ArenaAllocator.init(allocator);
defer arena_allocator_state.deinit();
const arena = arena_allocator_state.allocator();
// Enable OpenGL depth testing (use Z-buffer information)
gl.enable(gl.DEPTH_TEST);
// create shader program
var shader_program: Shader = Shader.create(arena, "content/shader.vs", "content/shader.fs");
var light_shader: Shader = Shader.create(arena, "content/light_shader.vs", "content/light_shader.fs");
// set up vertex data (and buffer(s)) and configure vertex attributes
// ------------------------------------------------------------------
const vertices_2D = [_]f32{
// positions // colors // texture coords
0.5, 0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, // top right
0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, // bottom right
-0.5, -0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, // bottom left
-0.5, 0.5, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, // top left
};
_ = vertices_2D;
const vertices_3D = [_]f32{
-0.5, -0.5, -0.5, 0.0, 0.0, -1.0,
0.5, -0.5, -0.5, 0.0, 0.0, -1.0,
0.5, 0.5, -0.5, 0.0, 0.0, -1.0,
0.5, 0.5, -0.5, 0.0, 0.0, -1.0,
-0.5, 0.5, -0.5, 0.0, 0.0, -1.0,
-0.5, -0.5, -0.5, 0.0, 0.0, -1.0,
-0.5, -0.5, 0.5, 0.0, 0.0, 1.0,
0.5, -0.5, 0.5, 0.0, 0.0, 1.0,
0.5, 0.5, 0.5, 0.0, 0.0, 1.0,
0.5, 0.5, 0.5, 0.0, 0.0, 1.0,
-0.5, 0.5, 0.5, 0.0, 0.0, 1.0,
-0.5, -0.5, 0.5, 0.0, 0.0, 1.0,
-0.5, 0.5, 0.5, -1.0, 0.0, 0.0,
-0.5, 0.5, -0.5, -1.0, 0.0, 0.0,
-0.5, -0.5, -0.5, -1.0, 0.0, 0.0,
-0.5, -0.5, -0.5, -1.0, 0.0, 0.0,
-0.5, -0.5, 0.5, -1.0, 0.0, 0.0,
-0.5, 0.5, 0.5, -1.0, 0.0, 0.0,
0.5, 0.5, 0.5, 1.0, 0.0, 0.0,
0.5, 0.5, -0.5, 1.0, 0.0, 0.0,
0.5, -0.5, -0.5, 1.0, 0.0, 0.0,
0.5, -0.5, -0.5, 1.0, 0.0, 0.0,
0.5, -0.5, 0.5, 1.0, 0.0, 0.0,
0.5, 0.5, 0.5, 1.0, 0.0, 0.0,
-0.5, -0.5, -0.5, 0.0, -1.0, 0.0,
0.5, -0.5, -0.5, 0.0, -1.0, 0.0,
0.5, -0.5, 0.5, 0.0, -1.0, 0.0,
0.5, -0.5, 0.5, 0.0, -1.0, 0.0,
-0.5, -0.5, 0.5, 0.0, -1.0, 0.0,
-0.5, -0.5, -0.5, 0.0, -1.0, 0.0,
-0.5, 0.5, -0.5, 0.0, 1.0, 0.0,
0.5, 0.5, -0.5, 0.0, 1.0, 0.0,
0.5, 0.5, 0.5, 0.0, 1.0, 0.0,
0.5, 0.5, 0.5, 0.0, 1.0, 0.0,
-0.5, 0.5, 0.5, 0.0, 1.0, 0.0,
-0.5, 0.5, -0.5, 0.0, 1.0, 0.0,
};
var VBO: c_uint = undefined;
var VAO: c_uint = undefined;
var light_VAO: c_uint = undefined;
gl.genVertexArrays(1, &VAO);
defer gl.deleteVertexArrays(1, &VAO);
gl.genVertexArrays(1, &light_VAO);
defer gl.deleteVertexArrays(1, &light_VAO);
gl.genBuffers(1, &VBO);
defer gl.deleteBuffers(1, &VBO);
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
gl.bindVertexArray(VAO);
gl.bindBuffer(gl.ARRAY_BUFFER, VBO);
// Fill our buffer with the vertex data
gl.bufferData(gl.ARRAY_BUFFER, @sizeOf(f32) * vertices_3D.len, &vertices_3D, gl.STATIC_DRAW);
// vertex
gl.vertexAttribPointer(0, 3, gl.FLOAT, gl.FALSE, 6 * @sizeOf(f32), null);
gl.enableVertexAttribArray(0);
// normal attribute
const normal_offset: [*c]c_uint = (3 * @sizeOf(f32));
gl.vertexAttribPointer(1, 3, gl.FLOAT, gl.FALSE, 6 * @sizeOf(f32), normal_offset);
gl.enableVertexAttribArray(1);
// Configure light VAO
gl.bindVertexArray(light_VAO);
gl.bindBuffer(gl.ARRAY_BUFFER, VBO);
gl.vertexAttribPointer(0, 3, gl.FLOAT, gl.FALSE, 6 * @sizeOf(f32), null);
gl.enableVertexAttribArray(0);
// View matrix
var view: [16]f32 = undefined;
// Buffer to store Orojection matrix (in render loop)
var proj: [16]f32 = undefined;
var light_model: [16]f32 = undefined;
while (!window.shouldClose()) {
// Time per frame
const current_frame = @floatCast(f32, glfw.getTime());
delta_time = current_frame - last_frame;
last_frame = current_frame;
processInput(window);
gl.clearColor(0.0, 0.0, 0.0, 0.0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
light_position[0] = 1.0 + zm.sin(@floatCast(f32, glfw.getTime())) * 2.0;
light_position[1] = 1.0 + zm.sin(@floatCast(f32, glfw.getTime()) / 2.0) * 1.0;
shader_program.use();
shader_program.setVec3f("objectColor", .{ 1.0, 0.5, 0.31 });
shader_program.setVec3f("lightColor", .{ 1.0, 1.0, 1.0 });
shader_program.setVec3f("lightPos", light_position);
shader_program.setVec3f("viewPos", zm.vecToArr3(camera.position));
// Projection matrix
const projM = x: {
const window_size = window.getSize();
const aspect = @intToFloat(f32, window_size.width) / @intToFloat(f32, window_size.height);
var projM = zm.perspectiveFovRhGl(camera.zoom * common.RAD_CONVERSION, aspect, 0.1, 100.0);
break :x projM;
};
zm.storeMat(&proj, projM);
shader_program.setMat4f("projection", proj);
// View matrix: Camera
const viewM = camera.getViewMatrix();
zm.storeMat(&view, viewM);
shader_program.setMat4f("view", view);
gl.bindVertexArray(VAO);
gl.drawArrays(gl.TRIANGLES, 0, 36);
const light_trans = zm.translation(light_position[0], light_position[1], light_position[2]);
const light_modelM = zm.mul(light_trans, zm.scaling(0.2, 0.2, 0.2));
zm.storeMat(&light_model, light_modelM);
light_shader.use();
light_shader.setMat4f("projection", proj);
light_shader.setMat4f("view", view);
light_shader.setMat4f("model", light_model);
gl.bindVertexArray(light_VAO);
gl.drawArrays(gl.TRIANGLES, 0, 36);
window.swapBuffers();
glfw.pollEvents();
}
}
fn glGetProcAddress(p: glfw.GLProc, proc: [:0]const u8) ?gl.FunctionPointer {
_ = p;
return glfw.getProcAddress(proc);
}
fn framebuffer_size_callback(window: glfw.Window, width: u32, height: u32) void {
_ = window;
gl.viewport(0, 0, @intCast(c_int, width), @intCast(c_int, height));
}
fn processInput(window: glfw.Window) void {
if (glfw.Window.getKey(window, glfw.Key.escape) == glfw.Action.press) {
_ = glfw.Window.setShouldClose(window, true);
}
if (glfw.Window.getKey(window, glfw.Key.w) == glfw.Action.press) {
camera.processKeyboard(Camera.CameraMovement.FORWARD, delta_time);
}
if (glfw.Window.getKey(window, glfw.Key.s) == glfw.Action.press) {
camera.processKeyboard(Camera.CameraMovement.BACKWARD, delta_time);
}
if (glfw.Window.getKey(window, glfw.Key.a) == glfw.Action.press) {
camera.processKeyboard(Camera.CameraMovement.LEFT, delta_time);
}
if (glfw.Window.getKey(window, glfw.Key.d) == glfw.Action.press) {
camera.processKeyboard(Camera.CameraMovement.RIGHT, delta_time);
}
}
fn mouseCallback(window: glfw.Window, xpos: f64, ypos: f64) void {
_ = window;
if (first_mouse) {
lastX = xpos;
lastY = ypos;
first_mouse = false;
}
var xoffset = xpos - lastX;
var yoffset = ypos - lastY;
lastX = xpos;
lastY = ypos;
camera.processMouseMovement(xoffset, yoffset, true);
}
fn mouseScrollCallback(window: glfw.Window, xoffset: f64, yoffset: f64) void {
_ = window;
_ = xoffset;
camera.processMouseScroll(yoffset);
}
|
0 | repos/zig_learn_opengl/src/getting_started | repos/zig_learn_opengl/src/getting_started/basic_lighting/build.zig | const std = @import("std");
const Options = @import("../../../build.zig").Options;
inline fn thisDir() []const u8 {
return comptime std.fs.path.dirname(@src().file) orelse ".";
}
const content_dir = "content/";
pub fn build(b: *std.build.Builder, options: Options) *std.build.CompileStep {
const exe = b.addExecutable(.{
.name = "basic_lighting",
.root_source_file = .{ .path = thisDir() ++ "/main.zig" },
.target = options.target,
.optimize = options.build_mode,
});
const install_content_step = b.addInstallDirectory(.{
.source_dir = thisDir() ++ "/" ++ content_dir,
.install_dir = .{ .custom = "" },
.install_subdir = "bin/" ++ content_dir,
});
exe.step.dependOn(&install_content_step.step);
return exe;
}
|
0 | repos/zig_learn_opengl/src/getting_started/basic_lighting | repos/zig_learn_opengl/src/getting_started/basic_lighting/content/light_shader.vs | #version 330 core
layout (location = 0) in vec3 aPos;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main()
{
gl_Position = projection * view * model * vec4(aPos, 1.0f);
} |
0 | repos/zig_learn_opengl/src/getting_started/basic_lighting | repos/zig_learn_opengl/src/getting_started/basic_lighting/content/light_shader.fs | #version 330 core
out vec4 FragColor;
void main()
{
FragColor = vec4(1.0f);
};
|
0 | repos/zig_learn_opengl/src/getting_started/basic_lighting | repos/zig_learn_opengl/src/getting_started/basic_lighting/content/shader.fs | #version 330 core
out vec4 FragColor;
in vec3 FragPos;
in vec3 Normal;
uniform vec3 lightPos;
uniform vec3 objectColor;
uniform vec3 lightColor;
uniform vec3 viewPos;
void main()
{
float ambientStrength = 0.1;
vec3 ambient = ambientStrength * lightColor;
float specularStrength = 0.75;
vec3 norm = normalize(Normal);
vec3 lightDir = normalize(lightPos - FragPos);
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse = diff * lightColor;
vec3 viewDir = normalize(viewPos - FragPos);
vec3 reflectDir = reflect(-lightDir, norm);
float spec = pow(max(dot(viewDir, reflectDir), 0.0), 256);
vec3 specular = specularStrength * spec * lightColor;
vec3 result = (ambient + diffuse + specular) * objectColor;
FragColor = vec4(result, 1.0f);
};
|
0 | repos/zig_learn_opengl/src/getting_started/basic_lighting | repos/zig_learn_opengl/src/getting_started/basic_lighting/content/shader.vs | #version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
out vec3 FragPos;
out vec3 Normal;
void main()
{
gl_Position = projection * view * vec4(aPos, 1.0f);
FragPos = vec3(vec4(aPos, 1.0));
Normal = aNormal;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.